REST API上基于角色的Spring安全性

时间:2016-08-10 18:49:47

标签: java spring rest spring-security

我遵循此代码库来实现spring security https://github.com/brahalla/Cerberus

我配置了像

这样的安全性后,我的资源得到了保护
@Override
    protected void configure(HttpSecurity httpSecurity) throws Exception {
        httpSecurity
                .csrf()
                .disable()
                .exceptionHandling()
                .authenticationEntryPoint(this.unauthorizedHandler)
                .and()
                .sessionManagement()
                .sessionCreationPolicy(SessionCreationPolicy.STATELESS)
                .and()
                .authorizeRequests()
                .antMatchers(HttpMethod.OPTIONS, "/**").permitAll()
                .antMatchers("/auth/**").permitAll()
                .anyRequest().authenticated();

        // Custom JWT based authentication
        httpSecurity
                .addFilterBefore(authenticationTokenFilterBean(), UsernamePasswordAuthenticationFilter.class);
    }

现在,我可以访问/auth来生成令牌。然后我创建了像thi s

这样的资源
@RequestMapping(value = "/api", method = GET)
@PreAuthorize("hasRole('ADMIN')")
ResponseEntity<?> sayHello() {
    return new ResponseEntity<>("Hello", OK);
}

我有像这样定义的硬编码用户

@Service
public class UserDetailsServiceImpl implements UserDetailsService {

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        User user = new User();
        user.setId(1L);
        user.setAuthorities(Roles.ADMIN.name());
        user.setEmail("a@a.com");
        user.setPassword(getEncryptedPass("admin"));
        user.setUsername("hola");
        return CerberusUserFactory.create(user);
    }

    private String getEncryptedPass(String admin) {
        PasswordEncoder passwordEncoder = new BCryptPasswordEncoder();
        return passwordEncoder.encode(admin);
    }


}

但是,每当我尝试在标题中使用api访问X-Auth-Token时(生成toke作为其值),我仍然会收到403(禁止访问)。我在这里缺少什么?

P.S :我已经尝试hasRole('Admin')hasRole('ROLE_ADMIN') ...它无效

0 个答案:

没有答案