简体   繁体   English

基于 JWT 角色的 Spring Security 授权

[英]JWT role Based Authorization with Spring Security

I would like to give access to /hello URL to users which has a role 'ADMIN' I have a security configuration like this.我想向具有“ADMIN”角色的用户授予对 /hello URL 的访问权限,我有这样的安全配置。 From "/authenticate" URL I am getting the jwt token.从“/authenticate” URL 我得到 jwt 令牌。

    @Override
protected void configure(HttpSecurity http) throws Exception {
    http.csrf().disable()
            .authorizeRequests()
            .antMatchers("/authenticate").permitAll()
            //.antMatchers("/hello").hasRole("ADMIN")
            .anyRequest().authenticated().
            and().
            exceptionHandling().and().sessionManagement()
            .sessionCreationPolicy(SessionCreationPolicy.STATELESS);
    http.addFilterBefore(jwtRequestFilter, UsernamePasswordAuthenticationFilter.class);
}

I have tried to add @PreAuthorize annotation in my Controller, but it's not working all users have an access to that url.我试图在我的控制器中添加 @PreAuthorize 注释,但它不起作用所有用户都可以访问该 url。

    @GetMapping("/hello")
    @PreAuthorize("hasRole('ADMIN')")
    public String test(){
        return "Hello";
    }

After removing @PreAuthorize annotation from the controller and changing the security configuration like this it solved my problem.从控制器中删除 @PreAuthorize 注释并像这样更改安全配置后,它解决了我的问题。
@Darren Thanks a lot for your comment it resolved my issue. @Darren 非常感谢您的评论,它解决了我的问题。

@Override
protected void configure(HttpSecurity http) throws Exception {
    http.csrf().disable()
        .authorizeRequests()
        .antMatchers("/authenticate").permitAll()
        .antMatchers("/hello").hasAuthority("ADMIN")
        .anyRequest().authenticated().
        and().
        exceptionHandling().and().sessionManagement()
        .sessionCreationPolicy(SessionCreationPolicy.STATELESS);
    http.addFilterBefore(jwtRequestFilter, 
        UsernamePasswordAuthenticationFilter.class);
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM