2015-09-22 23 views
-1

所以我也跟着这个教程https://spring.io/guides/tutorials/spring-security-and-angular-js/添加数据库春季安全和角度JS

但我有麻烦搞清楚如何添加数据库。

我已经加入这个特性文件,所以我在SQL连接到数据库

spring.datasource.url=jdbc:mysql://localhost:3306/login 
spring.datasource.username=root 
spring.datasource.password=root 

我创建一个表如下

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"); 
} 

而且东西我很困惑,就是那的我用我自己的数据库时仍然需要主体用户。

@RequestMapping("/user") 
public Principal user(Principal user) { 

    System.out.println(user.getName()); 
    System.out.println(user.toString()); 

    return user; 
} 

回答

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 +安全浏览:http://docs.spring.io/spring-security/site/docs/4.0.2.RELEASE/reference/htmlsingle/#mvc

http://docs.spring.io/spring-security/site/docs/4.0.2.RELEASE/reference/htmlsingle/#mvc-authentication-principal