Spring security hasRole()不';我不能和JWT一起工作

Spring security hasRole()不';我不能和JWT一起工作,spring-security,jwt,Spring Security,Jwt,我用Spring Security实现了JWT Spring Security/loginurl返回一个包含角色的JWT,但当我尝试访问需要角色的url时,它返回403 "timestamp": 1507840896561, "status": 403, "error": "Forbidden", "message": "Access is denied", "path": "/teacher/dashboard" 我在WebSecurityConfig中为/t

我用Spring Security实现了JWT

Spring Security
/login
url返回一个包含角色的JWT,但当我尝试访问需要角色的url时,它返回
403

"timestamp": 1507840896561,
    "status": 403,
    "error": "Forbidden",
    "message": "Access is denied",
    "path": "/teacher/dashboard"
我在
WebSecurityConfig
中为
/teacher/**
定义了这样一个角色,它扩展了
WebSecurityConfigurerAdapter

http
        .authorizeRequests()
        .antMatchers("/").permitAll()
        .antMatchers("/login").permitAll()
        .antMatchers("/api/register").permitAll()
        .antMatchers("/teacher/**").hasRole("TEACHER")
        .anyRequest().authenticated()

        .and()
        .formLogin()
        .loginPage("/login")
        .permitAll()

        .and()
        .logout()
        .permitAll();
http
        .csrf().disable();
http
        .formLogin()
        .defaultSuccessUrl("/", true)

        .and()
        .addFilterBefore(new SimpleCorsFilter(), ChannelProcessingFilter.class)

        .addFilter(new JWTAuthenticationFilter(authenticationManager()))
        .addFilter(new JWTAuthorizationFilter(authenticationManager()));
我试图将
hasRole()
的参数设置为
ROLE\u教师
,Spring Security警告我不要使用
ROLE\u
前缀。我还尝试了hasAuthority(“教师”)并再次获得了403`

我的JWT的有效载荷:

{
  "sub": "org.springframework.security.core.userdetails.User@394ca6ef: Username: teacher@postman.com; Password: [PROTECTED]; Enabled: true; AccountNonExpired: true; credentialsNonExpired: true; AccountNonLocked: true; Granted Authorities: ROLE_TEACHER",
  "exp": 1508704641
}

令牌已
授予权限:ROLE\u TEACHER
,但我一直拒绝访问错误。我是否遗漏了什么,或者是否有其他用于定义URL角色的实现?

像这样更改您的http配置,然后重试

.antMatchers("/teacher/**").access("hasAnyRole('TEACHER')")
希望这会很好

您还可以使用检查方法级别安全性中的角色

@PreAuthorize("hasRole('ROLE_TEACHER')")
要使用
@PreAuthorize
,您需要先启用它。为此,使用
GolbalMethodSecurityConfiguration
扩展您的
methodSecurityConfiguration
类并添加注释

@EnableGlobalMethodSecurity(prePostEnabled = true, proxyTargetClass = true)

prespenabled=true
允许应用程序在
之前(之前)
之后(之后)
基础上进行授权。轮到你了,哪一个适合你。

我第一次尝试了你的第一个解决方案,又得到了403。然后我尝试了第二个,我可以访问URL,无论我是否有令牌或任何角色。我仍然无法成功。请在请求出现时调试代码,并查看请求中存在哪个角色。类似于
request.isUserInRole()
您能否将设置了
DEBUG
级别的Spring安全日志(在您的日志配置中)添加到您的问题中。您找到解决方案了吗?@Hiru我更改了此问题的整个方法。我不再使用这种方法了。@Eniss谢谢你的帮助。在我的案例中,我没有在jwt声明中添加角色。现在对我来说很好。