Spring 数据使用 JWT

Spring Data Rest with JWT

我正在尝试使用 jwt 保护一个简单的 Spring-Data-Rest 应用程序。 从 https://github.com/spring-projects/spring-data-examples/tree/master/rest/security

获取种子

SecurityConfig如下(使用普通用户名,密码认证) 如何将其更改为 JWT 身份验证

(已在存储库中使用 @PreAuthorize("hasRole('ROLE_USER')") 完成授权)

@Configuration
@EnableGlobalMethodSecurity(prePostEnabled = true)
public class SecurityConfiguration extends WebSecurityConfigurerAdapter {

  /**
   * This section defines the user accounts which can be used for
   * authentication as well as the roles each user has.
   */
  @Override
  public void configure(AuthenticationManagerBuilder auth) throws Exception {

    auth.inMemoryAuthentication()
      .withUser("greg").password("turnquist").roles("USER").and()
      .withUser("ollie").password("gierke").roles("USER", "ADMIN");
  }

  /**
   * This section defines the security policy for the app.
   * - BASIC authentication is supported (enough for this REST-based demo)
   * - /employees is secured using URL security shown below
   * - CSRF headers are disabled since we are only testing the REST interface,
   *   not a web one.
   *
   * NOTE: GET is not shown which defaults to permitted.
   */
  @Override
  protected void configure(HttpSecurity http) throws Exception {

    http
      .httpBasic().and()
      .authorizeRequests()
        .antMatchers(HttpMethod.POST, "/employees").hasRole("ADMIN")
        .antMatchers(HttpMethod.PUT, "/employees/**").hasRole("ADMIN")
        .antMatchers(HttpMethod.PATCH, "/employees/**").hasRole("ADMIN").and()
      .csrf().disable();
  }
}

这里是 spring 引导中 JWT 身份验证的一个很好的教程,但也可以应用于 spring 应用程序:https://auth0.com/blog/implementing-jwt-authentication-on-spring-boot/

根据您 SecurityConfiguration.configure 中的教程,您需要

http.authorizeRequests()
            .anyRequest().authenticated()
            .and()
            .addFilter(new JWTAuthenticationFilter(authenticationManager()))
            .addFilter(new JWTAuthorizationFilter(authenticationManager()))
            // this disables session creation on Spring Security
            .sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS);

JWTAuthenticationFilter 扩展 UsernamePasswordAuthenticationFilter,应用于 /login URL 并根据您的 login/password 生成 JWT 令牌,如果系统中存在这样的用户。

JWTAuthorizationFilter 验证来自 http header

的 JWT 令牌

当然,您需要添加更多移动部件才能通过本教程启用 JWT 身份验证。

我遵循了 Spring 安全 OAuth 的教程: https://projects.spring.io/spring-security-oauth/docs/oauth2.html

特别是您必须启用资源服务器。这是我的(修改后的)配置:

@EnableResourceServer
@EnableWebSecurity
@EnableGlobalMethodSecurity(prePostEnabled = true)
public class OAuth2ResourceServerConfig extends ResourceServerConfigurerAdapter {

    @Override
    public void configure(ResourceServerSecurityConfigurer resources) throws Exception {
        resources.tokenServices(tokenServices());
    }

    @Bean
    public TokenStore tokenStore() {
        return new JwtTokenStore(accessTokenConverter());
    }

    @Bean
    public JwtAccessTokenConverter accessTokenConverter() {
        JwtAccessTokenConverter converter = new JwtAccessTokenConverter();
        try {
            // Load the public key of the authorization server.
            String key = IOUtils.toString(getClass().getResource("/reng0-public.key"), Charset.forName("US-ASCII"));
            converter.setVerifierKey(key);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        return converter;
    }

    @Bean
    @Primary
    public ResourceServerTokenServices tokenServices() {
        DefaultTokenServices defaultTokenServices = new DefaultTokenServices();
        defaultTokenServices.setTokenStore(tokenStore());
        return defaultTokenServices;
    }
}

客户端必须添加 Authorization: Bearer header 才能正常工作。