【问题标题】:Secure REST Api with Spring boot and JWT使用 Spring Boot 和 JWT 保护 REST Api
【发布时间】:2016-02-23 20:08:03
【问题描述】:

我正在尝试使用我自己实现的JWT 来保护我的 REST 服务器(这意味着 JWT 中没有弹簧东西可以自行处理,其他一切当然是Spring)。

我有这门课:JWTToken implements Authentication

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

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)方法。

当我尝试这样做时,例如:

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

请求没有通过这里,资源没有被调用。

我在这里错过了什么?

【问题讨论】:

    标签: java spring rest jwt


    【解决方案1】:

    您的JWTToken 类应该实现该方法:

    Collection<? extends GrantedAuthority> getAuthorities();
    

    实现应该返回用户授予角色的集合,其中一个是“管理员”角色,类似于:

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

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

    【讨论】:

      猜你喜欢
      • 2021-03-20
      • 2015-12-09
      • 2018-03-16
      • 1970-01-01
      • 2015-06-16
      • 2023-03-11
      • 2020-02-25
      • 2020-08-27
      • 2014-02-21
      相关资源
      最近更新 更多