【发布时间】:2018-03-25 15:13:19
【问题描述】:
我用 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_TEACHER,Spring Security 警告我不要使用ROLE_prefix。我也试过hasAuthority("TEACHER") and again got403`。
我的 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
}
令牌有Granted Authorities: ROLE_TEACHER,但我不断收到拒绝访问错误。我是否遗漏了什么,或者是否有任何其他实现来定义 url 的角色?
【问题讨论】:
-
您能否将设置了
DEBUG级别(在您的日志配置中)的 Spring Security 日志添加到您的问题中。 -
你找到解决办法了吗?
-
@Hiru 我改变了这个问题的整个方法。我不再使用这种方法了。
-
@Eniss 感谢您与我们联系。就我而言,我没有在 jwt 声明中添加角色。现在它对我来说工作正常。
标签: spring-security jwt