Spring,@ RolesAllowed和数据库来保护页面

时间:2015-01-31 22:11:17

标签: java spring spring-security

我的数据库中有两个表格。用户和user_role。

CREATE TABLE `user` (
  `username` varchar(50) NOT NULL,
  `password` varchar(255) NOT NULL,
  `enable` tinyint(4) NOT NULL DEFAULT '1',
  PRIMARY KEY (`username`),
  UNIQUE KEY `unique_username` (`username`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1

CREATE TABLE `user_roles` (
  `user_role_id` int(11) NOT NULL AUTO_INCREMENT,
  `username` varchar(45) NOT NULL,
  `ROLE` varchar(45) NOT NULL,
  PRIMARY KEY (`user_role_id`),
  UNIQUE KEY `uni_username_role` (`ROLE`,`username`),
  KEY `fk_username_idx` (`username`),
  CONSTRAINT `fk_username` FOREIGN KEY (`username`) REFERENCES `user` (`username`)
) ENGINE=InnoDB AUTO_INCREMENT=4 DEFAULT CHARSET=latin1

' ROLE'在user_roles中显示用户具有{ROLE_USER,ROLE_ADMIN}

的角色

我想使用@RolesAllowed拒绝用户访问某些页面(并授予管理员访问权限),但我不知道如何从数据库获取user_role并将其发送给RolesAllowed。

在Controller中获取user_role并不是一个问题,但我不认为检查每个函数中的用户角色是个好主意。

或者,或许,比使用@RolesAllowed更好的解决方案?

对不起这个愚蠢的问题,这是我第一次看到Spring的5个小时。

1 个答案:

答案 0 :(得分:2)

您没有详细介绍您正在构建的应用程序的体系结构,但作为初学者,我可以从我正在构建的应用程序中提供一些示例。我正在使用Spring Boot,JPA,Spring Data和Spring Security。我有类似的要求,并解决了这个问题:

我已经实现了UserDetailsS​​ervice接口。它用于检索有关尝试登录的用户的信息。当我使用JPA和Spring Data时,服务和模型类看起来像这样(getters,setter和大多数字段为简洁而删除):

@Entity
// in your case this would map to the User table
public class Profile implements UserDetails {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Integer id;

    // you should probably use bean validation / jpa to assure uniqueness etc.
    private String name;
    ...

    @ElementCollection(fetch = FetchType.EAGER)
    private Set<Role> roles = ImmutableSet.<Role> of(new Role("USER"));
    ...
}

@Embeddable
// in your case this would map to the user_role table
public class Role implements GrantedAuthority {

    public final static Role USER = new Role("USER");
    public final static Role ADMIN = new Role("ADMIN");

    private String authority;

    ...

}

@Transactional
@Service
public class ProfileService implements UserDetailsService {

    private final ProfileRepository profileRepository;

    @Autowired
    public ProfileService(ProfileRepository profileRepository){
            this.profileRepository = profileRepository;
    }

    public Profile loadUserByUsername(String username) throws UsernameNotFoundException {
        Profile profile = profileRepository.findByUsername(username);

        // this is the only way to authenticate
        if (profile == null) {
            throw new UsernameNotFoundException("security.userNotFound");
        }

        return profile;
    }

// you may want to add profile creation etc.
...
}

完成此设置后,我必须配置Spring Security才能使用此服务。我主要使用Java Config,所以配置看起来像。

@Configuration
public class SecurityConfig extends WebSecurityConfigurerAdapter {
    @Autowired
    private ProfileService profileService;

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

    @Override
    protected void configure(AuthenticationManagerBuilder auth)
        throws Exception {
        auth.userDetailsService(profileService).passwordEncoder(passwordEncoder());
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.formLogin()
                .loginPage("/login")
                .permitAll()
                .and()
                .authorizeRequests()
                .antMatchers(HttpMethod.POST, "/**")
                .authenticated()
                ...
                // you may want to put more config here
      }
}