【问题标题】:hasRole() doesn't work with JWThasRole() 不适用于 JWT
【发布时间】: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


【解决方案1】:

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

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

希望这会正常工作。

您还可以使用

检查方法级别安全性中的角色
@PreAuthorize("hasRole('ROLE_TEACHER')")

要使用@PreAuthorize,您需要先启用它。为此,您可以使用 GolbalMethodSecurityConfiguration 扩展您的 MethodSecurityConfig 类并添加注释

@EnableGlobalMethodSecurity(prePostEnabled = true, proxyTargetClass = true)

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

【讨论】:

  • 我第一次尝试了你的第一个解决方案,又得到了 403。然后我尝试了第二个,无论我是否有令牌或任何角色,我都可以访问该 URL。我还是没能成功。
  • 当请求到来时调试你的代码,看看你的请求中存在哪个角色。类似request.isUserInRole()
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-07-04
  • 2019-07-16
  • 2016-09-01
  • 1970-01-01
  • 2020-10-27
  • 2016-11-11
相关资源
最近更新 更多