hasRole()不能与JWT合作

时间:2017-10-13 13:04:54

标签: spring-security jwt

我使用Spring Security实现了JWT。

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

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

我在/teacher/** WebSecurityConfig中定义了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

我尝试将ROLE_的参数设置为hasAuthority("TEACHER") and again got,Spring Security警告我不要使用{ "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 403`。

我的JWT的有效载荷:

<html>        
    <style>
        .A{
            border:1px dotted black;
            display:inline-block;
        }

       .B{
            border:1px solid black;
            display:inline-block;
            width: 100px;
            height:100px;
            overflow:hidden;
        }

        .C{
            border:1px solid black;
            display:inline-block;
            width: 100px;
            height:100px;
            overflow:hidden;
        }
    </style>

    1
    <div class="A"> 
        <img src="man-profile.png">
    </div>

    2
    <div class="B">
        <img src="man-profile.png">
    </div>

    3
    <div class="B">
        <img src="man-profile.png" style="width:100;">
    </div>

    4
    <div class="C">
        <img src="picture.png" style="width:100;">
    </div>

    5
    <div class="C">
        <img src="picture.png" style="height:100;">
    </div>

    6
    <div class="C">
        <img src="picture.png" style="height:100; width:100%">
    </div>
</html>

令牌有'Authorization'但我一直收到拒绝访问错误。我是否遗漏了某些内容,或者是否有任何其他实现来定义网址的角色?

1 个答案:

答案 0 :(得分:1)

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

.antMatchers("/teacher/**").access("hasAnyRole('TEACHER')")
希望这样可以正常工作。

您还可以使用

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

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

@EnableGlobalMethodSecurity(prePostEnabled = true, proxyTargetClass = true)

prePostEnabled = true可让您的应用授权before (pre)after (post)。轮到哪一个适合你。