使用Spring Boot和JWT保护REST Api [英] Secure REST Api with Spring boot and JWT

查看:106
本文介绍了使用Spring Boot和JWT保护REST Api的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用实现了自我的JWT保护我的REST服务器(意味着JWT中没有处理自我的JWT,其他所有东西当然都是Spring.)

I'm trying to secure my REST server with JWT which I have implemented my self (Meaning that no spring stuff in the JWT handling it self, everything else is Spring of course).

我有这个课程:JWTToken implements Authentication.

我有一个过滤器,负责在SecurityContextHolder上设置JWTToken实例:

I have a filter that is responsible of setting the JWTToken instance at the SecurityContextHolder:

public class JwtFilter extends GenericFilterBean {
public void doFilter(...) {
     ....
     JWTToken token = new JWTToken(jwt); // this init the Authentication object with all the jwt claims
     SecurityContextHolder.getContext().setAuthentication(token);
     ....
}

我也有调试资源:

@RequestMapping(
        value = "/protected_resource",
        method = RequestMethod.POST
)
@RolesAllowed("admin")
public RESTResponse<String> debugJwt() {
    Authentication authentication = SecurityContextHolder.getContext().getAuthentication(); // here I can see that the context is the right one
    return new RESTResponse<>("This was successful", "feedback message", true);
}

我错过了在任何在线资源中都找不到的谜团,这就是如何实现WebSecurityConfigurerAdapter,特别是configure(HttpSecurity http) metohd的方法.

I am missing one peace of the puzzle which I could not found in any of the resources online and this is how to implement WebSecurityConfigurerAdapter and specifically the configure(HttpSecurity http) metohd.

例如,当我尝试执行此操作时:

When I tried do this, for instance:

http.authorizeRequests().anyRequest().authenticated()

请求没有通过此请求,资源也没有得到调用.

Requests did not pass through this and the resource was not getting called.

我在这里想念什么?

推荐答案

您的JWTToken类应实现以下方法:

Your JWTToken class should implement the method:

Collection<? extends GrantedAuthority> getAuthorities();

实现应返回用户授予的角色的集合,其中一个将是"admin"角色,例如:

The implementation should return a collection of the user granted roles, one of them will be the "admin" role, something like:

public Collection<? extends GrantedAuthority> getAuthorities() {
    return Collections.singletonList(new SimpleGrantedAuthority("admin"));
}

当然,在您的情况下,您将查询数据库或JWT令牌并解析用户角色.

Of course in your case you will query the DB or the JWT token and parse the user roles.

这篇关于使用Spring Boot和JWT保护REST Api的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆