hasRole()不适用于JWT

hasRole()不适用于JWT

问题描述:

我使用Spring Security实施了JWT。hasRole()不适用于JWT

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

"timestamp": 1507840896561, 
    "status": 403, 
    "error": "Forbidden", 
    "message": "Access is denied", 
    "path": "/teacher/dashboard" 

WebSecurityConfig延伸WebSecurityConfigurerAdapter定义/teacher/**这样的角色:

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_TEACHER和春季安全警告我不要使用ROLE_前缀。我也试过hasAuthority("TEACHER") and again got 403`。

我的智威汤逊的有效载荷:

{ 
    "sub": "[email protected]: Username: [email protected]; Password: [PROTECTED]; Enabled: true; AccountNonExpired: true; credentialsNonExpired: true; AccountNonLocked: true; Granted Authorities: ROLE_TEACHER", 
    "exp": 1508704641 
} 

令牌已Granted Authorities: ROLE_TEACHER但我不断收到拒绝访问错误。我是否错过了某些东西或者是否有任何其他实现来定义url的角色?

+0

请问您可以在您的问题中添加带有“DEBUG”级别设置(在日志配置中)的Spring安全日志。 – dur

更改您的HTTP配置一样,再试,

.antMatchers("/teacher/**").access("hasAnyRole('TEACHER')") 

希望这将正常工作。

您也可以使用

@PreAuthorize("hasRole('ROLE_TEACHER')") 

要使用@PreAuthorize您需要先启用它检查方法级安全性的作用。要做到这一点与GolbalMethodSecurityConfiguration扩展您MethodSecurityConfig类,并添加注释

@EnableGlobalMethodSecurity(prePostEnabled = true, proxyTargetClass = true) 

prePostEnabled = true使您的应用程序授权before (pre)after (post)基础。它轮到你哪一个适合你。

+0

我第一次尝试你的第一个解决方案,并再次得到403。然后我尝试了第二个,我可以访问该URL,无论是否有令牌或任何角色。我仍然无法成功。 – Eniss

+0

请求发出时调试您的代码,并查看您的请求中存在哪个角色。像'request.isUserInRole()' –