当前位置:   article > 正文

springboot集成oauth2报错_org.springframework.security.oauth2.provider.token

org.springframework.security.oauth2.provider.tokengranter' that could not b

参照官方文档https://spring.io/guides/tutorials/spring-boot-oauth2/#_social_login_simple

引入的项目依赖:

  1. <parent>
  2. <groupId>org.springframework.boot</groupId>
  3. <artifactId>spring-boot-starter-parent</artifactId>
  4. <version>2.1.4.RELEASE</version>
  5. <relativePath />
  6. </parent>
  7. <dependencies>
  8. <dependency>
  9. <groupId>org.springframework.boot</groupId>
  10. <artifactId>spring-boot-starter-web</artifactId>
  11. </dependency>
  12. <dependency>
  13. <groupId>org.springframework.boot</groupId>
  14. <artifactId>spring-boot-starter-security</artifactId>
  15. </dependency>
  16. <dependency>
  17. <groupId>org.springframework.security.oauth.boot</groupId>
  18. <artifactId>spring-security-oauth2-autoconfigure</artifactId>
  19. <version>2.1.4.RELEASE</version>
  20. </dependency>
  21. <dependency>
  22. <groupId>org.webjars</groupId>
  23. <artifactId>jquery</artifactId>
  24. <version>2.1.1</version>
  25. </dependency>
  26. <dependency>
  27. <groupId>org.webjars</groupId>
  28. <artifactId>bootstrap</artifactId>
  29. <version>3.2.0</version>
  30. </dependency>
  31. <dependency>
  32. <groupId>org.webjars</groupId>
  33. <artifactId>webjars-locator-core</artifactId>
  34. </dependency>
  35. <dependency>
  36. <groupId>org.springframework.boot</groupId>
  37. <artifactId>spring-boot-configuration-processor</artifactId>
  38. <optional>true</optional>
  39. </dependency>
  40. </dependencies>

问题出现:引入一下代码,启动程序报错:The bean 'oauth2ClientFilterRegistration', defined in class path resource [org/springframework/boot/autoconfigure/security/oauth2/client/OAuth2RestOperationsConfiguration$SessionScopedConfiguration.class], could not be registered. A bean with that name has already been defined in com.hegret.SocialApplication and overriding is disabled.

  1. @Bean
  2. public FilterRegistrationBean<OAuth2ClientContextFilter> oauth2ClientFilterRegistration(OAuth2ClientContextFilter filter) {
  3. FilterRegistrationBean<OAuth2ClientContextFilter> registration = new FilterRegistrationBean<OAuth2ClientContextFilter>();
  4. registration.setFilter(filter);
  5. registration.setOrder(-100);
  6. return registration;
  7. }
  1. . ____ _ __ _ _
  2. /\\ / ___'_ __ _ _(_)_ __ __ _ \ \ \ \
  3. ( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \
  4. \\/ ___)| |_)| | | | | || (_| | ) ) ) )
  5. ' |____| .__|_| |_|_| |_\__, | / / / /
  6. =========|_|==============|___/=/_/_/_/
  7. :: Spring Boot :: (v2.1.4.RELEASE)
  8. 2019-06-05 14:42:20.603 INFO 8560 --- [ main] com.hegret.SocialApplication : Starting SocialApplication on zsx with PID 8560 (F:\workspace-test\spring-oauth2-server\target\classes started by zhang in F:\workspace-test\spring-oauth2-server)
  9. 2019-06-05 14:42:20.605 INFO 8560 --- [ main] com.hegret.SocialApplication : No active profile set, falling back to default profiles: default
  10. 2019-06-05 14:42:20.877 WARN 8560 --- [ main] ConfigServletWebServerApplicationContext : Exception encountered during context initialization - cancelling refresh attempt: org.springframework.beans.factory.support.BeanDefinitionOverrideException: Invalid bean definition with name 'oauth2ClientFilterRegistration' defined in class path resource [org/springframework/boot/autoconfigure/security/oauth2/client/OAuth2RestOperationsConfiguration$SessionScopedConfiguration.class]: Cannot register bean definition [Root bean: class [null]; scope=; abstract=false; lazyInit=false; autowireMode=3; dependencyCheck=0; autowireCandidate=true; primary=false; factoryBeanName=org.springframework.boot.autoconfigure.security.oauth2.client.OAuth2RestOperationsConfiguration$SessionScopedConfiguration; factoryMethodName=oauth2ClientFilterRegistration; initMethodName=null; destroyMethodName=(inferred); defined in class path resource [org/springframework/boot/autoconfigure/security/oauth2/client/OAuth2RestOperationsConfiguration$SessionScopedConfiguration.class]] for bean 'oauth2ClientFilterRegistration': There is already [Root bean: class [null]; scope=; abstract=false; lazyInit=false; autowireMode=3; dependencyCheck=0; autowireCandidate=true; primary=false; factoryBeanName=socialApplication; factoryMethodName=oauth2ClientFilterRegistration; initMethodName=null; destroyMethodName=(inferred); defined in com.hegret.SocialApplication] bound.
  11. 2019-06-05 14:42:20.883 INFO 8560 --- [ main] ConditionEvaluationReportLoggingListener :
  12. Error starting ApplicationContext. To display the conditions report re-run your application with 'debug' enabled.
  13. 2019-06-05 14:42:20.884 ERROR 8560 --- [ main] o.s.b.d.LoggingFailureAnalysisReporter :
  14. ***************************
  15. APPLICATION FAILED TO START
  16. ***************************
  17. Description:
  18. The bean 'oauth2ClientFilterRegistration', defined in class path resource [org/springframework/boot/autoconfigure/security/oauth2/client/OAuth2RestOperationsConfiguration$SessionScopedConfiguration.class], could not be registered. A bean with that name has already been defined in com.hegret.SocialApplication and overriding is disabled.
  19. Action:
  20. Consider renaming one of the beans or enabling overriding by setting spring.main.allow-bean-definition-overriding=true

问题分析:跟踪源码,在OAuth2RestOperationsConfiguration类中已经定义过该bean对象了

  1. /*
  2. * Copyright 2012-2017 the original author or authors.
  3. *
  4. * Licensed under the Apache License, Version 2.0 (the "License");
  5. * you may not use this file except in compliance with the License.
  6. * You may obtain a copy of the License at
  7. *
  8. * https://www.apache.org/licenses/LICENSE-2.0
  9. *
  10. * Unless required by applicable law or agreed to in writing, software
  11. * distributed under the License is distributed on an "AS IS" BASIS,
  12. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13. * See the License for the specific language governing permissions and
  14. * limitations under the License.
  15. */
  16. package org.springframework.boot.autoconfigure.security.oauth2.client;
  17. import org.springframework.beans.factory.ObjectProvider;
  18. import org.springframework.beans.factory.annotation.Qualifier;
  19. import org.springframework.boot.autoconfigure.condition.AnyNestedCondition;
  20. import org.springframework.boot.autoconfigure.condition.ConditionMessage;
  21. import org.springframework.boot.autoconfigure.condition.ConditionOutcome;
  22. import org.springframework.boot.autoconfigure.condition.ConditionalOnBean;
  23. import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
  24. import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
  25. import org.springframework.boot.autoconfigure.condition.ConditionalOnNotWebApplication;
  26. import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
  27. import org.springframework.boot.autoconfigure.condition.NoneNestedConditions;
  28. import org.springframework.boot.autoconfigure.condition.SpringBootCondition;
  29. import org.springframework.boot.autoconfigure.security.SecurityProperties;
  30. import org.springframework.boot.context.properties.ConfigurationProperties;
  31. import org.springframework.boot.web.servlet.FilterRegistrationBean;
  32. import org.springframework.context.annotation.Bean;
  33. import org.springframework.context.annotation.ConditionContext;
  34. import org.springframework.context.annotation.Conditional;
  35. import org.springframework.context.annotation.Configuration;
  36. import org.springframework.context.annotation.Import;
  37. import org.springframework.context.annotation.Primary;
  38. import org.springframework.context.annotation.Scope;
  39. import org.springframework.context.annotation.ScopedProxyMode;
  40. import org.springframework.core.type.AnnotatedTypeMetadata;
  41. import org.springframework.security.core.Authentication;
  42. import org.springframework.security.core.context.SecurityContextHolder;
  43. import org.springframework.security.oauth2.client.DefaultOAuth2ClientContext;
  44. import org.springframework.security.oauth2.client.OAuth2ClientContext;
  45. import org.springframework.security.oauth2.client.filter.OAuth2ClientContextFilter;
  46. import org.springframework.security.oauth2.client.token.AccessTokenRequest;
  47. import org.springframework.security.oauth2.client.token.DefaultAccessTokenRequest;
  48. import org.springframework.security.oauth2.client.token.grant.client.ClientCredentialsResourceDetails;
  49. import org.springframework.security.oauth2.common.DefaultOAuth2AccessToken;
  50. import org.springframework.security.oauth2.config.annotation.web.configuration.EnableOAuth2Client;
  51. import org.springframework.security.oauth2.config.annotation.web.configuration.OAuth2ClientConfiguration;
  52. import org.springframework.security.oauth2.provider.OAuth2Authentication;
  53. import org.springframework.security.oauth2.provider.authentication.OAuth2AuthenticationDetails;
  54. import org.springframework.util.StringUtils;
  55. /**
  56. * Configuration for OAuth2 Single Sign On REST operations.
  57. *
  58. * @author Dave Syer
  59. * @author Madhura Bhave
  60. * @since 1.3.0
  61. */
  62. @Configuration
  63. @ConditionalOnClass(EnableOAuth2Client.class)
  64. public class OAuth2RestOperationsConfiguration {
  65. @Configuration
  66. @Conditional(ClientCredentialsCondition.class)
  67. protected static class SingletonScopedConfiguration {
  68. @Bean
  69. @ConfigurationProperties(prefix = "security.oauth2.client")
  70. @Primary
  71. public ClientCredentialsResourceDetails oauth2RemoteResource() {
  72. ClientCredentialsResourceDetails details = new ClientCredentialsResourceDetails();
  73. return details;
  74. }
  75. @Bean
  76. public DefaultOAuth2ClientContext oauth2ClientContext() {
  77. return new DefaultOAuth2ClientContext(new DefaultAccessTokenRequest());
  78. }
  79. }
  80. @Configuration
  81. @ConditionalOnBean(OAuth2ClientConfiguration.class)
  82. @Conditional({ OAuth2ClientIdCondition.class, NoClientCredentialsCondition.class })
  83. @Import(OAuth2ProtectedResourceDetailsConfiguration.class)
  84. protected static class SessionScopedConfiguration {
  85. @Bean
  86. public FilterRegistrationBean<OAuth2ClientContextFilter> oauth2ClientFilterRegistration(
  87. OAuth2ClientContextFilter filter, SecurityProperties security) {
  88. FilterRegistrationBean<OAuth2ClientContextFilter> registration = new FilterRegistrationBean<>();
  89. registration.setFilter(filter);
  90. registration.setOrder(security.getFilter().getOrder() - 10);
  91. return registration;
  92. }
  93. }
  94. // When the authentication is per cookie but the stored token is an oauth2 one, we can
  95. // pass that on to a client that wants to call downstream. We don't even need an
  96. // OAuth2ClientContextFilter until we need to refresh the access token. To handle
  97. // refresh tokens you need to @EnableOAuth2Client
  98. @Configuration
  99. @ConditionalOnMissingBean(OAuth2ClientConfiguration.class)
  100. @Conditional({ OAuth2ClientIdCondition.class, NoClientCredentialsCondition.class })
  101. @Import(OAuth2ProtectedResourceDetailsConfiguration.class)
  102. protected static class RequestScopedConfiguration {
  103. @Bean
  104. @Scope(value = "request", proxyMode = ScopedProxyMode.INTERFACES)
  105. public DefaultOAuth2ClientContext oauth2ClientContext() {
  106. DefaultOAuth2ClientContext context = new DefaultOAuth2ClientContext(
  107. new DefaultAccessTokenRequest());
  108. Authentication principal = SecurityContextHolder.getContext()
  109. .getAuthentication();
  110. if (principal instanceof OAuth2Authentication) {
  111. OAuth2Authentication authentication = (OAuth2Authentication) principal;
  112. Object details = authentication.getDetails();
  113. if (details instanceof OAuth2AuthenticationDetails) {
  114. OAuth2AuthenticationDetails oauthsDetails = (OAuth2AuthenticationDetails) details;
  115. String token = oauthsDetails.getTokenValue();
  116. context.setAccessToken(new DefaultOAuth2AccessToken(token));
  117. }
  118. }
  119. return context;
  120. }
  121. }
  122. /**
  123. * Condition to check if a {@code security.oauth2.client.client-id} is specified.
  124. */
  125. static class OAuth2ClientIdCondition extends SpringBootCondition {
  126. @Override
  127. public ConditionOutcome getMatchOutcome(ConditionContext context,
  128. AnnotatedTypeMetadata metadata) {
  129. String clientId = context.getEnvironment()
  130. .getProperty("security.oauth2.client.client-id");
  131. ConditionMessage.Builder message = ConditionMessage
  132. .forCondition("OAuth Client ID");
  133. if (StringUtils.hasLength(clientId)) {
  134. return ConditionOutcome.match(message
  135. .foundExactly("security.oauth2.client.client-id property"));
  136. }
  137. return ConditionOutcome.noMatch(message
  138. .didNotFind("security.oauth2.client.client-id property").atAll());
  139. }
  140. }
  141. /**
  142. * Condition to check for no client credentials.
  143. */
  144. static class NoClientCredentialsCondition extends NoneNestedConditions {
  145. NoClientCredentialsCondition() {
  146. super(ConfigurationPhase.PARSE_CONFIGURATION);
  147. }
  148. @Conditional(ClientCredentialsCondition.class)
  149. static class ClientCredentialsActivated {
  150. }
  151. }
  152. /**
  153. * Condition to check for client credentials.
  154. */
  155. static class ClientCredentialsCondition extends AnyNestedCondition {
  156. ClientCredentialsCondition() {
  157. super(ConfigurationPhase.PARSE_CONFIGURATION);
  158. }
  159. @ConditionalOnProperty(prefix = "security.oauth2.client", name = "grant-type", havingValue = "client_credentials", matchIfMissing = false)
  160. static class ClientCredentialsConfigured {
  161. }
  162. @ConditionalOnNotWebApplication
  163. static class NoWebApplication {
  164. }
  165. }
  166. }

解决方法:

在application.yml文件中添加配置,对bean进行重新定义覆盖

  1. spring:
  2. main:
  3. allow-bean-definition-overriding: true

重新启动,运行正常

  1. . ____ _ __ _ _
  2. /\\ / ___'_ __ _ _(_)_ __ __ _ \ \ \ \
  3. ( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \
  4. \\/ ___)| |_)| | | | | || (_| | ) ) ) )
  5. ' |____| .__|_| |_|_| |_\__, | / / / /
  6. =========|_|==============|___/=/_/_/_/
  7. :: Spring Boot :: (v2.1.4.RELEASE)
  8. 2019-06-05 15:34:51.519 INFO 724 --- [ main] com.hegret.SocialApplication : Starting SocialApplication on zsx with PID 724 (F:\workspace-test\spring-oauth2-server\target\classes started by zhang in F:\workspace-test\spring-oauth2-server)
  9. 2019-06-05 15:34:51.521 INFO 724 --- [ main] com.hegret.SocialApplication : No active profile set, falling back to default profiles: default
  10. 2019-06-05 15:34:52.069 INFO 724 --- [ main] o.s.b.w.embedded.tomcat.TomcatWebServer : Tomcat initialized with port(s): 8080 (http)
  11. 2019-06-05 15:34:52.081 INFO 724 --- [ main] o.apache.catalina.core.StandardService : Starting service [Tomcat]
  12. 2019-06-05 15:34:52.081 INFO 724 --- [ main] org.apache.catalina.core.StandardEngine : Starting Servlet engine: [Apache Tomcat/9.0.17]
  13. 2019-06-05 15:34:52.147 INFO 724 --- [ main] o.a.c.c.C.[Tomcat].[localhost].[/] : Initializing Spring embedded WebApplicationContext
  14. 2019-06-05 15:34:52.147 INFO 724 --- [ main] o.s.web.context.ContextLoader : Root WebApplicationContext: initialization completed in 606 ms
  15. 2019-06-05 15:34:52.312 INFO 724 --- [ main] o.s.s.concurrent.ThreadPoolTaskExecutor : Initializing ExecutorService 'applicationTaskExecutor'
  16. 2019-06-05 15:34:52.358 INFO 724 --- [ main] o.s.b.a.w.s.WelcomePageHandlerMapping : Adding welcome page: class path resource [static/index.html]
  17. 2019-06-05 15:34:52.398 INFO 724 --- [ main] .s.s.UserDetailsServiceAutoConfiguration :
  18. Using generated security password: d8670419-1986-4c55-a811-e147c18f0174
  19. 2019-06-05 15:34:52.444 INFO 724 --- [ main] o.s.s.web.DefaultSecurityFilterChain : Creating filter chain: Ant [pattern='/**'], [org.springframework.security.web.context.request.async.WebAsyncManagerIntegrationFilter@1cb19dba, org.springframework.security.web.context.SecurityContextPersistenceFilter@6e106680, org.springframework.security.web.header.HeaderWriterFilter@16c8b7bd, org.springframework.security.web.csrf.CsrfFilter@4dafba3e, org.springframework.security.web.authentication.logout.LogoutFilter@2f5c1332, org.springframework.security.oauth2.client.filter.OAuth2ClientAuthenticationProcessingFilter@7c3ebc6b, org.springframework.security.web.savedrequest.RequestCacheAwareFilter@55ecbafe, org.springframework.security.web.servletapi.SecurityContextHolderAwareRequestFilter@205b132e, org.springframework.security.web.authentication.AnonymousAuthenticationFilter@1931d99, org.springframework.security.web.session.SessionManagementFilter@65bcf7c2, org.springframework.security.web.access.ExceptionTranslationFilter@476a736d, org.springframework.security.web.access.intercept.FilterSecurityInterceptor@5bca7664]
  20. 2019-06-05 15:34:52.479 INFO 724 --- [ main] o.s.b.w.embedded.tomcat.TomcatWebServer : Tomcat started on port(s): 8080 (http) with context path ''
  21. 2019-06-05 15:34:52.481 INFO 724 --- [ main] com.hegret.SocialApplication : Started SocialApplication in 1.146 seconds (JVM running for 1.472)

 

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/我家自动化/article/detail/83426
推荐阅读
相关标签
  

闽ICP备14008679号