Spring Boot 2 和 OAuth2/JWT

Posted

技术标签:

【中文标题】Spring Boot 2 和 OAuth2/JWT【英文标题】:Spring Boot 2 and OAuth2/JWT 【发布时间】:2018-08-05 03:51:20 【问题描述】:

我正在升级到 Spring Boot 2 版本,我的 OAuth2/JWT 自定义身份验证服务器不再工作。下面,您可以找到身份验证服务器和客户端应用程序的代码

OAuth2 认证服务器

应用程序

@SpringBootApplication
@EnableResourceServer
public class Application 

    public static void main(String[] args) 
        SpringApplication.run(Application.class, args);
    


application.properties

spring.profiles.active=dev

server.port=8888

WebSecurityConfigurerAdapter

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.annotation.Order;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.crypto.password.NoOpPasswordEncoder;

import lombok.extern.slf4j.Slf4j;

@Slf4j
@Configuration
@EnableWebSecurity
@Order(-20)
public class WebSecurityConfiguration extends WebSecurityConfigurerAdapter  


  @Override
  protected void configure(final HttpSecurity http) throws Exception 
      http.authorizeRequests().antMatchers("/login").permitAll().anyRequest().authenticated()
          .and().formLogin().permitAll();
  


  @Override
  protected void configure(AuthenticationManagerBuilder auth) throws Exception 
    auth
    .parentAuthenticationManager(authenticationManagerBean())
    .inMemoryAuthentication()
    .passwordEncoder(NoOpPasswordEncoder.getInstance())
    .withUser("demo").password("demo").roles("USER");

  

  @Bean
  @Override
  public AuthenticationManager authenticationManagerBean() throws Exception 
      return super.authenticationManagerBean();
  


AuthorizationServerConfigurerAdapter

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.oauth2.config.annotation.configurers.ClientDetailsServiceConfigurer;
import org.springframework.security.oauth2.config.annotation.web.configuration.AuthorizationServerConfigurerAdapter;
import org.springframework.security.oauth2.config.annotation.web.configuration.EnableAuthorizationServer;
import org.springframework.security.oauth2.config.annotation.web.configurers.AuthorizationServerEndpointsConfigurer;
import org.springframework.security.oauth2.provider.token.DefaultTokenServices;
import org.springframework.security.oauth2.provider.token.TokenStore;
import org.springframework.security.oauth2.provider.token.store.JwtAccessTokenConverter;
import org.springframework.security.oauth2.provider.token.store.JwtTokenStore;

@Configuration
@EnableAuthorizationServer
public class OAuth2AuthorizationServerConfiguration extends AuthorizationServerConfigurerAdapter 

  public static final Logger LOGGER = LoggerFactory.getLogger(AuthorizationServerConfigurerAdapter.class);

  @Autowired
  private AuthenticationManager authenticationManager;

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

  @Bean
  public JwtAccessTokenConverter accessTokenConverter() 
      JwtAccessTokenConverter converter = new JwtAccessTokenConverter();
      converter.setSigningKey("abcd");
      return converter;
  

  @Bean
  @Primary
  public DefaultTokenServices tokenServices() 
      DefaultTokenServices defaultTokenServices = new DefaultTokenServices();
      defaultTokenServices.setTokenStore(tokenStore());
      defaultTokenServices.setSupportRefreshToken(true);
      defaultTokenServices.setTokenEnhancer(accessTokenConverter());
      return defaultTokenServices;
  

  @Override
  public void configure(ClientDetailsServiceConfigurer clientDetailsServiceConfigurer) throws Exception 
    clientDetailsServiceConfigurer
    .inMemory()
        .withClient("coating-app")
        .secret("coating-pass")
        .authorizedGrantTypes("authorization_code")
        .authorities("ROLE_CLIENT", "ROLE_TRUSTED_CLIENT")
        .scopes("read", "write", "trust")
        .resourceIds("test-api")
        .autoApprove(true);
  

@Override
  public void configure(AuthorizationServerSecurityConfigurer oauthServer) throws Exception 

    oauthServer.tokenKeyAccess("permitAll()")
    .checkTokenAccess("isAuthenticated()");
  

  @Override
  public void configure(AuthorizationServerEndpointsConfigurer endpoints) throws Exception 
      endpoints
        .authenticationManager(authenticationManager)
        .tokenServices(tokenServices())
        .tokenStore(tokenStore())
        .accessTokenConverter(accessTokenConverter());
  


客户端应用程序

application.properties

spring.profiles.active=dev

server.port=8080

server.servlet.context-path=/coating/webapp
server.servlet.session.cookie.name=UI2SESSION


spring.security.oauth2.client.registration.my-client.client-id=coating-app
spring.security.oauth2.client.registration.my-client.client-secret=coating-pass
spring.security.oauth2.client.registration.my-client.client-authentication-method=basic
spring.security.oauth2.client.registration.my-client.authorization-grant-type=authorization_code
spring.security.oauth2.client.registration.my-client.redirect-uri-template=baseUrl/login/oauth2/code/registrationId
spring.security.oauth2.client.registration.my-client.scope=scope
spring.security.oauth2.client.registration.my-client.client-name=coating-app
spring.security.oauth2.client.registration.my-client.provider=my-oauth-provider
spring.security.oauth2.client.provider.my-oauth-provider.token-uri=http://localhost:8888/oauth/token
spring.security.oauth2.client.provider.my-oauth-provider.authorization-uri=http://localhost:8888/oauth/authorize
spring.security.oauth2.client.provider.my-oauth-provider.user-info-uri=http://localhost:8888/user/me

WebSecurityConfigurerAdapter

import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;

import org.springframework.security.config.annotation.web.builders.WebSecurity;

@EnableWebSecurity
public class WebSecurityConfiguration extends WebSecurityConfigurerAdapter 

  @Override
  public void configure(WebSecurity web) throws Exception 
      web.ignoring()
          .antMatchers("/resources/**", "/VAADIN/**", "/vaadinServlet/**");
  

  @Override
  public void configure(HttpSecurity http) throws Exception 

      http.oauth2Login();
  

更新: 我已经按照http://projects.spring.io/spring-security-oauth/docs/oauth2.html 的文档调整了一些配置文件。我同样更新了上面的代码 sn-ps。

在客户端,我现在看到一个不同的错误: [invalid_token_response] 解析访问令牌响应时出错:HTTP Content-Type 标头必须是 application/json; charset=UTF-8

我相信它与 Spring boot 2 OAuth2 "The HTTP Content-Type header must be application/json"

但是,即使我遵循 Joe Grandja 推荐的解决方案 (@ControllerAdvice),它也不起作用。

您可以在下面找到客户端日志。

21:56:05.908 [http-nio-8080-exec-4] DEBUG o.s.security.web.FilterChainProxy/doFilter /login/oauth2/code/my-client?code=pTZVp5&state=VLnH27p_kKSXAsLoeOYZaC_ZkS5QXgtzQN4M1ug6x4M%3D at position 6 of 13 in additional filter chain; firing Filter: 'OAuth2AuthorizationRequestRedirectFilter'
21:56:05.908 [http-nio-8080-exec-4] DEBUG o.s.s.w.u.m.AntPathRequestMatcher/matches Checking match of request : '/login/oauth2/code/my-client'; against '/oauth2/authorization/registrationId'
21:56:05.909 [http-nio-8080-exec-4] DEBUG o.s.security.web.FilterChainProxy/doFilter /login/oauth2/code/my-client?code=pTZVp5&state=VLnH27p_kKSXAsLoeOYZaC_ZkS5QXgtzQN4M1ug6x4M%3D at position 7 of 13 in additional filter chain; firing Filter: 'OAuth2LoginAuthenticationFilter'
21:56:05.909 [http-nio-8080-exec-4] DEBUG o.s.s.w.u.m.AntPathRequestMatcher/matches Checking match of request : '/login/oauth2/code/my-client'; against '/login/oauth2/code/*'
21:56:05.909 [http-nio-8080-exec-4] DEBUG o.s.s.o.c.w.OAuth2LoginAuthenticationFilter/doFilter Request is to process authentication
21:56:05.914 [http-nio-8080-exec-4] DEBUG o.s.s.authentication.ProviderManager/authenticate Authentication attempt using org.springframework.security.oauth2.client.authentication.OAuth2LoginAuthenticationProvider
21:56:06.661 [http-nio-8080-exec-4] DEBUG o.s.s.authentication.ProviderManager/authenticate Authentication attempt using org.springframework.security.oauth2.client.oidc.authentication.OidcAuthorizationCodeAuthenticationProvider
21:56:06.692 [http-nio-8080-exec-4] DEBUG o.s.s.o.c.w.OAuth2LoginAuthenticationFilter/unsuccessfulAuthentication Authentication request failed: org.springframework.security.oauth2.core.OAuth2AuthenticationException: [invalid_token_response] An error occurred parsing the Access Token response: The HTTP Content-Type header must be application/json; charset=UTF-8
org.springframework.security.oauth2.core.OAuth2AuthenticationException: [invalid_token_response] An error occurred parsing the Access Token response: The HTTP Content-Type header must be application/json; charset=UTF-8
        at org.springframework.security.oauth2.client.endpoint.NimbusAuthorizationCodeTokenResponseClient.getTokenResponse(NimbusAuthorizationCodeTokenResponseClient.java:105)
        at org.springframework.security.oauth2.client.endpoint.NimbusAuthorizationCodeTokenResponseClient.getTokenResponse(NimbusAuthorizationCodeTokenResponseClient.java:67)
        at org.springframework.security.oauth2.client.authentication.OAuth2LoginAuthenticationProvider.authenticate(OAuth2LoginAuthenticationProvider.java:121)
        at org.springframework.security.authentication.ProviderManager.authenticate(ProviderManager.java:174)
        at org.springframework.security.oauth2.client.web.OAuth2LoginAuthenticationFilter.attemptAuthentication(OAuth2LoginAuthenticationFilter.java:159)
        at org.springframework.security.web.authentication.AbstractAuthenticationProcessingFilter.doFilter(AbstractAuthenticationProcessingFilter.java:212)
        at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:334)
        at org.springframework.security.oauth2.client.web.OAuth2AuthorizationRequestRedirectFilter.doFilterInternal(OAuth2AuthorizationRequestRedirectFilter.java:128)
        at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107)
        at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:334)
        at org.springframework.security.web.authentication.logout.LogoutFilter.doFilter(LogoutFilter.java:116)
        at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:334)
        at org.springframework.security.web.csrf.CsrfFilter.doFilterInternal(CsrfFilter.java:100)
        at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107)
        at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:334)
        at org.springframework.security.web.header.HeaderWriterFilter.doFilterInternal(HeaderWriterFilter.java:66)
        at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107)
        at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:334)
        at org.springframework.security.web.context.SecurityContextPersistenceFilter.doFilter(SecurityContextPersistenceFilter.java:105)
        at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:334)
        at org.springframework.security.web.context.request.async.WebAsyncManagerIntegrationFilter.doFilterInternal(WebAsyncManagerIntegrationFilter.java:56)
        at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107)
        at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:334)
        at org.springframework.security.web.FilterChainProxy.doFilterInternal(FilterChainProxy.java:215)
        at org.springframework.security.web.FilterChainProxy.doFilter(FilterChainProxy.java:178)
        at org.springframework.web.filter.DelegatingFilterProxy.invokeDelegate(DelegatingFilterProxy.java:357)
        at org.springframework.web.filter.DelegatingFilterProxy.doFilter(DelegatingFilterProxy.java:270)
        at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193)
        at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)
        at org.springframework.web.filter.HttpPutFormContentFilter.doFilterInternal(HttpPutFormContentFilter.java:109)
        at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107)
        at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193)
        at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)
        at org.springframework.web.filter.HiddenHttpMethodFilter.doFilterInternal(HiddenHttpMethodFilter.java:81)
        at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107)
        at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193)
        at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)
        at org.springframework.web.filter.CharacterEncodingFilter.doFilterInternal(CharacterEncodingFilter.java:200)
        at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107)
        at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193)
        at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)
        at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:199)
        at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:96)
        at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:496)
        at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:140)
        at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:81)
        at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:87)
        at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:342)
        at org.apache.coyote.http11.Http11Processor.service(Http11Processor.java:803)
        at org.apache.coyote.AbstractProcessorLight.process(AbstractProcessorLight.java:66)
        at org.apache.coyote.AbstractProtocol$ConnectionHandler.process(AbstractProtocol.java:790)
        at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1459)
        at org.apache.tomcat.util.net.SocketProcessorBase.run(SocketProcessorBase.java:49)
        at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
        at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
        at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
        at java.lang.Thread.run(Thread.java:745)
Caused by: com.nimbusds.oauth2.sdk.ParseException: The HTTP Content-Type header must be application/json; charset=UTF-8
        at com.nimbusds.oauth2.sdk.util.ContentTypeUtils.ensureContentType(ContentTypeUtils.java:52)
        at com.nimbusds.oauth2.sdk.http.HTTPMessage.ensureContentType(HTTPMessage.java:133)
        at com.nimbusds.oauth2.sdk.http.HTTPResponse.ensureContentType(HTTPResponse.java:1)
        at com.nimbusds.oauth2.sdk.http.HTTPResponse.getContentAsJSONObject(HTTPResponse.java:369)
        at com.nimbusds.oauth2.sdk.AccessTokenResponse.parse(AccessTokenResponse.java:235)
        at com.nimbusds.oauth2.sdk.TokenResponse.parse(TokenResponse.java:95)
        at org.springframework.security.oauth2.client.endpoint.NimbusAuthorizationCodeTokenResponseClient.getTokenResponse(NimbusAuthorizationCodeTokenResponseClient.java:101)
        ... 56 common frames omitted
21:56:06.693 [http-nio-8080-exec-4] DEBUG o.s.s.o.c.w.OAuth2LoginAuthenticationFilter/unsuccessfulAuthentication Updated SecurityContextHolder to contain null Authentication
21:56:06.693 [http-nio-8080-exec-4] DEBUG o.s.s.o.c.w.OAuth2LoginAuthenticationFilter/unsuccessfulAuthentication Delegating to authentication failure handler org.springframework.security.web.authentication.SimpleUrlAuthenticationFailureHandler@fee249a

【问题讨论】:

【参考方案1】:

PasswordEncoder 有一个新的实现。

@Bean
  public PasswordEncoder passwordEncoder() 
  return PasswordEncoderFactories.createDelegatingPasswordEncoder();

您还需要为用户和客户端使用密码编码器。

你可以查看这个仓库https://github.com/dzinot/spring-boot-2-oauth2-authorization-jwt

它使用 Spring Boot 2、JWT 令牌,用户和客户端都存储在数据库中。

【讨论】:

以上是关于Spring Boot 2 和 OAuth2/JWT的主要内容,如果未能解决你的问题,请参考以下文章

Spring Boot项目搭建(Spring Boot 2.2.4 + MyBatis + MySql)

Spring Boot 2.5.2 现已推出,同步推出Spring Boot 2.4.8

Spring Boot 2.5.2 现已推出,同步推出Spring Boot 2.4.8

Spring 5.1.13 和 Spring Boot 2.2.3 发布

Spring Boot系列Spring Boot整合持久层

Spring Boot 2.X(十六):应用监控之 Spring Boot Actuator 使用及配置