使用角色JAVA访问时出现Spring Security 403错误

时间:2016-09-17 07:54:02

标签: java spring

所有用户都可以成功登录,但所有用户都只能打开使用 permitAll()方法的网址。我已经设定了角色" RADMIN"并且在具有该角色的用户登录后,由于 403 ERROR ,他无法打开meta或任何其他URL。可以打开的网址只有"登录","退出"," home"。

@Configuration
@ComponentScan("bg.package")
@EnableWebSecurity
@EnableGlobalMethodSecurity(prePostEnabled = true)
public class SpringSecurity extends WebSecurityConfigurerAdapter {

    @Autowired
    private AuthenticationService authenticationService;

    @Override
    public void configure(WebSecurity web) throws Exception {
        web.ignoring().antMatchers("/assets/**");
    }

@Override
    protected void configure(HttpSecurity http) throws Exception {
http.authorizeRequests()
        .antMatchers("/login", "/home", "/logout").permitAll()
        .antMatchers("meta/**").hasAuthority("RADMIN")
        .anyRequest().authenticated()
        .and().addFilterAfter(new CsrfHeaderFilter(), CsrfFilter.class);
}

@Autowired
    public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
        Md5PasswordEncoder encoder = new Md5PasswordEncoder();
        auth.userDetailsService(authenticationService).passwordEncoder(encoder);
    }
}

AuthService

@Service
public class AuthenticationService implements UserDetailsService {

    @Autowired
    private AuthDao authDao;

    @Override
    public UserDetails loadUserByUsername(String email) throws UsernameNotFoundException {

        AuthModel authModel = authDao.getUserInfo(email);
        GrantedAuthority authority = new SimpleGrantedAuthority(authModel.getRank());
        UserDetails userDetails = (UserDetails) new User(authModel.getName(), authModel.getPass(), Arrays.asList(authority));
        return userDetails;
    }

}

1 个答案:

答案 0 :(得分:2)

如果您使用hasAuthority()方法检查用户的角色,则还应在角色名称前添加前缀ROLE_。因此,检查角色的安全配置部分应如下所示:

.antMatchers("meta/**").hasAuthority("ROLE_RADMIN")

您也可以使用hasAuthority("ROLE_RADMIN")替代hasRole("RADMIN")而不是void putchar(c) { #asm mov ah, 0x0e mov bx, sp mov al, [bx+2] xor bx, bx int 0x10 #endasm }