通过JWT进行身份验证并通过本地数据库进行授权

时间:2020-05-19 19:59:18

标签: spring-security oauth jwt authorization auth0

在我的Spring Boot应用程序中,我的用户通过了第三方身份验证,并且收到了一个Jwt,我使用Spring Security中的NimbusJwtDecoder对其进行了解析。

 @Override
 public void configure(HttpSecurity http) throws Exception {
       http.authorizeRequests()
            .mvcMatchers("/api/private").authenticated()
            .mvcMatchers("/api/organisations").authenticated()
            .mvcMatchers("/api/project").authenticated()
            .mvcMatchers("/api/user").authenticated()
            .and()
            .oauth2ResourceServer().jwt();
    }

这很好,现在我想通过检索要存储在我自己的数据库中的角色和权限来添加授权。我有Jwt的用户名,但我不知道如何将其全部插入。将不胜感激任何帮助。

1 个答案:

答案 0 :(得分:0)

使用JWT对用户进行身份验证时,请将用户名添加到SecurityContext的主体中。

创建一个实现javax.servelet.Filter接口的AuthorisationFilter类。在此类中,使用securityContextHolder中的用户名从数据库中获取用户详细信息,然后将GrantAuthorities添加到上下文中。

在SecurityConfig中,创建一个FilterRegistrationBean,该过滤器将过滤器设置为AuthorisationFilter,将urlPatterns设置为(“ / *”)或适当的设置,并将Order设置为Ordered.LOWEST_PRECEDENCE