如何为具有Java Spring安全性的用户授予权限

时间:2018-12-09 13:42:53

标签: java spring spring-security

我尝试从数据库中获取一些用户并授予他们权限。这些是我的用户类字段。

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

我想通过字符串角色授予权限。 我尝试过:

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

但是我不知道如何从db中获取用户并在configureGlobal方法中使用它们。

2 个答案:

答案 0 :(得分:2)

方法1:

您可以设置dataSource并传递查询以读取用户和权限,如下所示:

@Autowired
private DataSource dataSource; //autowire the data source

    @Override
    public void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.jdbcAuthentication().dataSource(dataSource)
                .usersByUsernameQuery("select username, password, 1 as enabled from user where username=?") 
                .authoritiesByUsernameQuery("select username, authority from user_authority where username=?"); //check the for columns.
    }

在这种情况下,表看起来像这样

用户表:

CREATE TABLE user (
  username VARCHAR(50) NOT NULL PRIMARY KEY,
  email VARCHAR(50),
  password VARCHAR(500),
  activated BOOLEAN DEFAULT FALSE,
  activationkey VARCHAR(50) DEFAULT NULL,
  resetpasswordkey VARCHAR(50) DEFAULT NULL
);

user_authority 表:

CREATE TABLE user_authority (
    username VARCHAR(50) NOT NULL,
    authority VARCHAR(50) NOT NULL,
    FOREIGN KEY (username) REFERENCES user (username),
    FOREIGN KEY (authority) REFERENCES authority (name),
    UNIQUE INDEX user_authority_idx_1 (username, authority)
);

方法2:

如果需要,您可以为任何自定义实现实现用户详细信息服务,以下仅为示例用户名不区分大小写:

@Component("userDetailsService")
public class UserDetailsService implements org.springframework.security.core.userdetails.UserDetailsService {

    private final Logger log = LoggerFactory.getLogger(UserDetailsService.class);

    @Autowired
    private UserRepository userRepository;

    @Override
    @Transactional
    public UserDetails loadUserByUsername(final String login) {

        log.debug("Authenticating {}", login);
        String lowercaseLogin = login.toLowerCase();

        User userFromDatabase = userRepository.findByUsernameCaseInsensitive(lowercaseLogin);


        if (userFromDatabase == null) {
            throw new UsernameNotFoundException("User " + lowercaseLogin + " was not found in the database");
        } else if (!userFromDatabase.isActivated()) {
            throw new UserNotActivatedException("User " + lowercaseLogin + " is not activated");
        }

        Collection<GrantedAuthority> grantedAuthorities = new ArrayList<>();
        for (Authority authority : userFromDatabase.getAuthorities()) {
            GrantedAuthority grantedAuthority = new SimpleGrantedAuthority(authority.getName());
            grantedAuthorities.add(grantedAuthority);
        }

        return new org.springframework.security.core.userdetails.User(userFromDatabase.getUsername(), userFromDatabase.getPassword(), grantedAuthorities);

    }

}

和安全配置:

    @Autowired
    private UserDetailsService userDetailsService;

    @Bean
    public PasswordEncoder passwordEncoder() {
        return new StandardPasswordEncoder();
    }

    @Autowired
    public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {

        auth
                .userDetailsService(userDetailsService)
                .passwordEncoder(passwordEncoder());

    }

希望有帮助

答案 1 :(得分:1)

您可以使用JdbcUserDetailsManager从数据库加载用户

@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 = ?")
}

usersByUsernameQuery中的1表示已启用。