java - Spring Boot 如何使用 jwt 管理用户角色

标签 java spring-boot spring-security jwt roles

我正在用 spring boot 编写一个 RESTful api。
我正在使用 spring boot、jersey、mongo db、swagger、spring boot security 和 jwt。

我已经编写了模型,数据库请求的存储库。现在我已经集成了 Security 和 jwt token 。

现在我需要离散化用户的角色,因为用户不能调用需要管理员权限的路由。

我有一个登录路径,它返回一个 token 。这是我的 SecurityConfig 的代码

...
@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter{

    @Autowired
    UserRepository userRepository;

    @Override
    public void configure(HttpSecurity httpSecurity) throws Exception {
        httpSecurity.csrf().disable().authorizeRequests()
                .antMatchers("/").permitAll()
                .antMatchers("/api/swagger.json").permitAll()
                .antMatchers(HttpMethod.POST, "/login").permitAll()
                .antMatchers("/api/*").authenticated()
                .and()

                .addFilterBefore(new JWTLoginFilter("/login", authenticationManager(), userRepository),
                        UsernamePasswordAuthenticationFilter.class)

                .addFilterBefore(new JWTAuthenticationFilter(),
                        UsernamePasswordAuthenticationFilter.class);
    }

}

我编写了 JWTLoginFilter,当用户登录时返回 token
...
@Override
public Authentication attemptAuthentication(HttpServletRequest req, HttpServletResponse res) throws AuthenticationException, IOException, ServletException {
    Credential creds = new ObjectMapper().readValue(req.getInputStream(), Credential.class);

    User user = userRepository.login(creds);

    if (user == null)
        throw new BadCredentialsException("");

    UsernamePasswordAuthenticationToken token = new UsernamePasswordAuthenticationToken(
        creds.getUsername(),
        creds.getPassword()
    );

    return token;
}
...

我想在我的端点类中插入这个方法
@PreAuthorize("hasRole('ROLE_ADMIN')")

这是端点的一部分
....

@Component
@Path("story")
@Api(value = "Story", produces = "application/json")
public class StoryEndpoint {

    private static final Logger LOGGER = LoggerFactory.getLogger(StoryEndpoint.class);

    @Autowired
    StoryRepository storyRepository;


    @GET
    @Path("/")
    @Produces(MediaType.APPLICATION_JSON)
    @PreAuthorize("hasRole('ROLE_ADMIN')") <--- I want insert here
    @ApiOperation(value = "Get All Story", response = Story.class)
    @ApiResponses(value = {
            @ApiResponse(code = 200, message = "hello resource found"),
            @ApiResponse(code = 404, message = "Given admin user not found")
    })
    public Response getAllStory(){
        Iterable<Story> stories = storyRepository.findAll();
        LOGGER.info("getAllStory");
        return (stories!=null) ? Response.ok(stories).build() : Response.ok(ResponseErrorGenerator.generate(Response.Status.NOT_FOUND)).status(Response.Status.NOT_FOUND).build();
    }
....

我如何制定一种机制来为用户分配角色,以及如何在 token 中传递角色并在路由上离散用户角色?

最佳答案

您需要将用户角色存储在 JWT token 中作为附加声明,在 token 验证后提取它们并作为主体的“权限”传递:

 Collection<? extends GrantedAuthority> authorities
                = Arrays.asList(claims.get(AUTHORITIES_KEY).toString().split(",")).stream()
                .map(authority -> new SimpleGrantedAuthority(authority))
                .collect(Collectors.toList());

        User principal = new User(claims.getSubject(), "",
                authorities);

        UsernamePasswordAuthenticationToken t
                = new UsernamePasswordAuthenticationToken(principal, "", authorities);

关于java - Spring Boot 如何使用 jwt 管理用户角色,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43253707/

相关文章:

java - 在 JSP 中链接不同的页面并保留当前的 ​​Spring Security session

java - Digital Ocean java服务器不断崩溃: java.net.SocketException:连接重置

java - 将嵌套 json 映射到 java 字段,无需写入容器名称

java - 向公众分发产品时的外部图书馆许可证

java - 使用java代码配置创建管理MongoDb连接的Jpa EntityManager

java - 为什么刷新访问 token 会未经授权?

java - Spring 安全 : using relative path

spring - 如何在冒充其他用户后获得原始用户?

java - 将 hive 函数转换为 java - 翻译和 regexp_replace

java - 意外错误