How to give authorities for users with Java Spring security

Alex :

I try to get some users from db and give them authorities. Those are my user class fields.

private String  username;
private String  email;
private String  password;
private String  role;

I want give authorities by string role. I tried this:

@Autowired
    public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
        auth.inMemoryAuthentication()
          .withUser("user1").password(passwordEncoder().encode("user1Pass"))
          .authorities("ROLE_USER");
}

but I don't know how to get the users from db and use them in configureGlobal method.

chaoluo :

You can use the JdbcUserDetailsManager to load users from DB

@Autowired
public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
    auth.jdbcAuthentication()
           .dataSource({datasource})
           .usersByUsernameQuery("select username,password,1 "+ "from xxx " + "where username = ?")
           .authoritiesByUsernameQuery("select username, role "+ "from xxx " + "where username = ?")
}

The 1 in the usersByUsernameQuery means enabled.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=130259&siteId=1