所以我按照本教程https://spring.io/guides/tutorials/spring-security-and-angular-js/
但我无法弄清楚如何添加数据库。
我已将此添加到属性文件中,因此我已连接到数据库
spring.datasource.url=jdbc:mysql://localhost:3306/login
spring.datasource.username=root
spring.datasource.password=root
在sql中我创建一个表如下
CREATE TABLE IF NOT EXISTS `login`.`users` (
`idusers` INT NOT NULL AUTO_INCREMENT COMMENT '',
`username` VARCHAR(45) NULL COMMENT '',
`password` VARCHAR(256) NULL COMMENT '',
`authority` VARCHAR(45) NULL COMMENT '',
PRIMARY KEY (`idusers`) COMMENT '')
ENGINE = InnoDB;
并添加了一些用户。
我希望将其替换为数据库。
@Autowired
public void globalUserDetails(AuthenticationManagerBuilder auth) throws Exception {
auth.inMemoryAuthentication()
.withUser("user").password("password").roles("USER")
.and()
.withUser("admin").password("admin").roles("USER", "ADMIN", "READER", "WRITER")
.and()
.withUser("audit").password("audit").roles("USER", "ADMIN", "READER");
}
我感到困惑的是,在使用我自己的数据库时我还需要Principal用户。
@RequestMapping("/user")
public Principal user(Principal user) {
System.out.println(user.getName());
System.out.println(user.toString());
return user;
}
答案 0 :(得分:1)
查看文档(http://docs.spring.io/spring-security/site/docs/4.0.2.RELEASE/reference/htmlsingle/#jc-authentication-jdbc)
并了解您需要如何更改globalUserDetails
方法以使用jdbcAuthentication
代替inMemoryAuthentication
:
@Autowired
private DataSource dataSource;
@Autowired
public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
auth
.jdbcAuthentication()
.dataSource(dataSource)
.withDefaultSchema()
.withUser("user").password("password").roles("USER").and()
.withUser("admin").password("password").roles("USER", "ADMIN");
}
实际配置适用于内存数据库,因为它在初始化时创建新架构。在您的情况下,您应该将其更改为:
@Autowired
private DataSource dataSource;
@Autowired
public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
auth
.jdbcAuthentication()
.dataSource(dataSource)
.usersByUsernameQuery(/* set a query to suit your model*/)
.authoritiesByUsernameQuery(/* set a query to suit your model*/)
.groupAuthoritiesByUsername(/* set a query to suit your model*/);
}
Principal
只是一个界面,可让您访问当前登录的用户,不多也不少。
有关Spring MVC + Security的更多信息,请访问:http://docs.spring.io/spring-security/site/docs/4.0.2.RELEASE/reference/htmlsingle/#mvc