Когда я указываю доменное имя в accessTokenUri, оно не работает и сообщает об ошибке, но когда я указываю localhost, он работает. Почему?
Сервер авторизации Config.java
@Configuration
@EnableAuthorizationServer
@EnableGlobalMethodSecurity(prePostEnabled = true, securedEnabled = true)
public class AuthorizationServerConfig extends AuthorizationServerConfigurerAdapter {
@Autowired
private AuthenticationManager authenticationManager;
@Override
public void configure(AuthorizationServerSecurityConfigurer security) throws Exception {
security.tokenKeyAccess("permitAll()")
.checkTokenAccess("isAuthenticated()");
}
@Override
public void configure(ClientDetailsServiceConfigurer clients) throws Exception {
clients
.inMemory()
.withClient("QWE123")
.secret("abc")
.authorizedGrantTypes("password")
.scopes("user_info").accessTokenValiditySeconds(0)
.autoApprove(true);
}
@Override
public void configure(AuthorizationServerEndpointsConfigurer endpoints) throws Exception {
endpoints.authenticationManager(authenticationManager);
}
}
@EnableResourceServer
@Configuration
public class ResourceServerConfig extends WebSecurityConfigurerAdapter {
@Override
@Bean
public AuthenticationManager authenticationManagerBean() throws Exception {
return super.authenticationManagerBean();
}
@Autowired
private UserDetailsService customUserDetailsService;
@Override
protected void configure(HttpSecurity http) throws Exception {
http.authorizeRequests()
.antMatchers("/login").permitAll()
.anyRequest()
.authenticated()
.and()
.formLogin()
.permitAll();
}
@Override
public void configure(WebSecurity web) throws Exception {
web.ignoring().antMatchers("/user/**","/swagger-ui.html", "/v2/api-docs", "/swagger-resources/**");
}
@Autowired
public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
auth
.userDetailsService(customUserDetailsService).passwordEncoder(passwordEncoder());
}
@Bean
public BCryptPasswordEncoder passwordEncoder() {
return new BCryptPasswordEncoder();
}
}
App.properties
security:
basic:
enabled: false
oauth2:
resource:
filter-order: 3
ResourceServerConfig.java
@EnableOAuth2Sso
@Configuration
public class OauthConfig extends WebSecurityConfigurerAdapter{
@Override
protected void configure(HttpSecurity http) throws Exception {
http
.authorizeRequests()
.antMatchers("/")
.permitAll()
.anyRequest()
.authenticated();
}
@Override
public void configure(WebSecurity web) throws Exception {
web.ignoring().antMatchers("/swagger-ui.html", "/v2/api-docs", "/swagger-resources/**");
}
}
@Configuration
@EnableResourceServer
@EnableGlobalMethodSecurity(prePostEnabled = true)
public class Oauth2ResourceServerConfig extends GlobalMethodSecurityConfiguration {
@Override
protected MethodSecurityExpressionHandler createExpressionHandler() {
return new OAuth2MethodSecurityExpressionHandler();
}
}
App.properties
security:
basic:
enabled: false
oauth2:
client:
clientId: QWE123
clientSecret: abc
accessTokenUri: https://example.net/auth/oauth/token
userAuthorizationUri: https://example.net/auth/oauth/authorize
resource:
userInfoUri: https://example.net/auth/logged-in/principal
filter-order: 3
Ошибка:
2018-09-14 12:00:13.083 INFO 25836 --- [ main] o.s.j.e.a.AnnotationMBeanExporter : Located managed bean 'environmentManager': registering with JMX server as MBean [org.springframework.cloud.context.environment:name=environmentManager,type=EnvironmentManager] 2018-09-14 12:00:13.095 INFO 25836 --- [ main] o.s.j.e.a.AnnotationMBeanExporter : Located managed bean 'restartEndpoint': registering with JMX server as MBean [org.springframework.cloud.context.restart:name=restartEndpoint,type=RestartEndpoint] 2018-09-14 12:00:13.106 INFO 25836 --- [ main] o.s.j.e.a.AnnotationMBeanExporter : Located managed bean 'refreshScope': registering with JMX server as MBean [org.springframework.cloud.context.scope.refresh:name=refreshScope,type=RefreshScope] 2018-09-14 12:00:13.116 INFO 25836 --- [ main] o.s.j.e.a.AnnotationMBeanExporter : Located managed bean 'configurationPropertiesRebinder': registering with JMX server as MBean [org.springframework.cloud.context.properties:name=configurationPropertiesRebinder,context=35d08e6c,type=ConfigurationPropertiesRebinder] 2018-09-14 12:00:13.123 INFO 25836 --- [ main] o.s.j.e.a.AnnotationMBeanExporter : Located managed bean 'refreshEndpoint': registering with JMX server as MBean [org.springframework.cloud.endpoint:name=refreshEndpoint,type=RefreshEndpoint] 2018-09-14 12:00:13.424 INFO 25836 --- [ main] o.s.c.support.DefaultLifecycleProcessor : Starting beans in phase 0 2018-09-14 12:00:13.482 INFO 25836 --- [ main] o.s.c.support.DefaultLifecycleProcessor : Starting beans in phase 2147483647 2018-09-14 12:00:13.483 INFO 25836 --- [ main] d.s.w.p.DocumentationPluginsBootstrapper : Context refreshed 2018-09-14 12:00:13.509 INFO 25836 --- [ main] d.s.w.p.DocumentationPluginsBootstrapper : Found 1 custom documentation plugin(s) 2018-09-14 12:00:13.530 INFO 25836 --- [
main] s.d.s.w.s.ApiListingReferenceScanner : Scanning for api listing references 2018-09-14 12:00:13.870 INFO 25836 --- [
main] s.b.c.e.t.TomcatEmbeddedServletContainer : Tomcat started on port(s): 8080 (http) 2018-09-14 12:00:13.882 INFO 25836 --- [
main] c.h.dfsc.DfscServiceApplication : Started DfscServiceApplication in 44.8 seconds (JVM running for 45.324) 2018-09-14 12:01:52.271 INFO 25836 --- [nio-8080-exec-1] o.a.c.c.C.[Tomcat].[localhost].[/api] : Initializing Spring FrameworkServlet 'dispatcherServlet' 2018-09-14 12:01:52.271 INFO 25836 --- [nio-8080-exec-1] o.s.web.servlet.DispatcherServlet : FrameworkServlet 'dispatcherServlet': initialization started 2018-09-14 12:01:52.292 INFO 25836 --- [nio-8080-exec-1] o.s.web.servlet.DispatcherServlet : FrameworkServlet 'dispatcherServlet': initialization completed in 21 ms 2018-09-14 12:01:52.990 WARN 25836 --- [nio-8080-exec-1] o.s.b.a.s.o.r.UserInfoTokenServices : Could not fetch user details: class org.springframework.security.oauth2.client.resource.UserRedirectRequiredException, A redirect is required to get the users approval
Я многое нашел по этому поводу, но безуспешно, не могли бы вы мне помочь?




Я нашел решение для этого. Это происходило из-за кластеризации. Было несколько экземпляров серверов, которые аутентифицируют и авторизуют токен. Когда происходит запрос на генерацию токена, он сохраняет токен в одном экземпляре, но когда пришел запрос на авторизацию, он попадает в другие экземпляры. Когда он не обнаруживает токен и генерирует исключение. на localhost у меня был только один сервер, поэтому он работал нормально.
Рекомендуется хранить токены в базе данных памяти, такой как Redis. У Spring есть функция, которая позволяет это сделать.
@EnableRedisHttpSession.