使用 JWT 进行角色基础身份验证

问题描述 投票:0回答:1

我设计了一个具有用户和角色的系统。只有管理员和用户可以访问 api 端点。 请提供 Spring Security 中基于角色的 jwt 授权的通用代码。 请提及jwtfilter,jwtservice,jwtutil和jwt配置文件

java spring spring-boot spring-security spring-security-oauth2
1个回答
0
投票

为您提到的所有类编写完整代码有点困难。但您可以在下面提到的代码的基础上进行构建。

对带有 /admin/* 的 API 的任何请求都将检查“管理员”角色,对带有 /user/* 的 API 的任何请求都将检查“用户”角色。

@Configuration
@EnableWebSecurity
public class JwtConfiguration extends WebSecurityConfigurerAdapter {

    @Override
    protected void configure(HttpSecurity httpSecurity) throws Exception {
        httpSecurity.csrf().disable()
            .authorizeRequests()
                .antMatchers("/admin/**").hasRole("ADMIN")
                .antMatchers("/user/**").hasRole("USER")
                .anyRequest().authenticated();
    }
}

© www.soinside.com 2019 - 2024. All rights reserved.