我在设置Spring Oauth2服务器时遇到问题。当我将客户端指向FB时,它可以正常登录,将其定向到Oauth2服务器时,它无法正常工作。用户可以成功登录并获得承载令牌。我从客户端得到“ BadCredentialsException:无法获取访问令牌”的信息。
服务器日志:
o.s.s.w.FilterChainProxy : /login at position 1 of 12 in additional filter chain; firing Filter: 'WebAsyncManagerIntegrationFilter'
o.s.s.w.FilterChainProxy : /login at position 2 of 12 in additional filter chain; firing Filter: 'SecurityContextPersistenceFilter'
w.c.HttpSessionSecurityContextRepository : HttpSession returned null object for SPRING_SECURITY_CONTEXT
w.c.HttpSessionSecurityContextRepository : No SecurityContext was available from the HttpSession: org.apache.catalina.session.StandardSessionFacade@4f2698f7. A new one will be created.
o.s.s.w.FilterChainProxy : /login at position 3 of 12 in additional filter chain; firing Filter: 'HeaderWriterFilter'
o.s.s.w.header.writers.HstsHeaderWriter : Not injecting HSTS header since it did not match the requestMatcher o.s.security.web.header.writers.HstsHeaderWriter$SecureRequestMatcher@5b5aeff5
o.s.s.w.FilterChainProxy : /login at position 4 of 12 in additional filter chain; firing Filter: 'LogoutFilter'
o.s.s.w.u.matcher.AntPathRequestMatcher : Checking match of request : '/login'; against '/logout'
o.s.s.w.FilterChainProxy : /login at position 5 of 12 in additional filter chain; firing Filter: 'UsernamePasswordAuthenticationFilter'
o.s.s.w.u.matcher.AntPathRequestMatcher : Checking match of request : '/login'; against '/login'
w.a.UsernamePasswordAuthenticationFilter : Request is to process authentication
o.s.s.authentication.ProviderManager : Authentication attempt using o.s.security.authentication.dao.DaoAuthenticationProvider
s.CompositeSessionAuthenticationStrategy : Delegating to o.s.security.web.authentication.session.ChangeSessionIdAuthenticationStrategy@1b8f3b15
w.a.UsernamePasswordAuthenticationFilter : Authentication success. Updating SecurityContextHolder to contain: o.s.security.authentication.UsernamePasswordAuthenticationToken@4bc9b896: Principal: o.s.security.core.userdetails.User@f02988d6: Username: username; Password: [PROTECTED]; Enabled: true; AccountNonExpired: true; credentialsNonExpired: true; AccountNonLocked: true; Granted Authorities: ROLE_USER; Credentials: [PROTECTED]; Authenticated: true; Details: o.s.security.web.authentication.WebAuthenticationDetails@fffd3270: RemoteIpAddress: 0:0:0:0:0:0:0:1; SessionId: A5769D3F7BE48CDCE28246573B9CF1D9; Granted Authorities: ROLE_USER
RequestAwareAuthenticationSuccessHandler : Redirecting to DefaultSavedRequest Url: http://localhost:8081/oauth/authorize?client_id=clientId&redirect_uri=http://127.0.0.1:8080/client/login&response_type=code&state=CIjAxa
o.s.s.web.DefaultRedirectStrategy : Redirecting to 'http://localhost:8081/oauth/authorize?client_id=clientId&redirect_uri=http://127.0.0.1:8080/client/login&response_type=code&state=CIjAxa'
w.c.HttpSessionSecurityContextRepository : SecurityContext 'o.s.security.core.context.SecurityContextImpl@4bc9b896: Authentication: o.s.security.authentication.UsernamePasswordAuthenticationToken@4bc9b896: Principal: o.s.security.core.userdetails.User@f02988d6: Username: username; Password: [PROTECTED]; Enabled: true; AccountNonExpired: true; credentialsNonExpired: true; AccountNonLocked: true; Granted Authorities: ROLE_USER; Credentials: [PROTECTED]; Authenticated: true; Details: o.s.security.web.authentication.WebAuthenticationDetails@fffd3270: RemoteIpAddress: 0:0:0:0:0:0:0:1; SessionId: A5769D3F7BE48CDCE28246573B9CF1D9; Granted Authorities: ROLE_USER' stored to HttpSession: 'org.apache.catalina.session.StandardSessionFacade@4f2698f7
s.s.w.c.SecurityContextPersistenceFilter : SecurityContextHolder now cleared, as request processing completed
o.s.s.w.FilterChainProxy : /oauth/authorize?client_id=clientId&redirect_uri=http://127.0.0.1:8080/client/login&response_type=code&state=CIjAxa at position 1 of 12 in additional filter chain; firing Filter: 'WebAsyncManagerIntegrationFilter'
o.s.s.w.FilterChainProxy : /oauth/authorize?client_id=clientId&redirect_uri=http://127.0.0.1:8080/client/login&response_type=code&state=CIjAxa at position 2 of 12 in additional filter chain; firing Filter: 'SecurityContextPersistenceFilter'
w.c.HttpSessionSecurityContextRepository : Obtained a valid SecurityContext from SPRING_SECURITY_CONTEXT: 'o.s.security.core.context.SecurityContextImpl@4bc9b896: Authentication: o.s.security.authentication.UsernamePasswordAuthenticationToken@4bc9b896: Principal: o.s.security.core.userdetails.User@f02988d6: Username: username; Password: [PROTECTED]; Enabled: true; AccountNonExpired: true; credentialsNonExpired: true; AccountNonLocked: true; Granted Authorities: ROLE_USER; Credentials: [PROTECTED]; Authenticated: true; Details: o.s.security.web.authentication.WebAuthenticationDetails@fffd3270: RemoteIpAddress: 0:0:0:0:0:0:0:1; SessionId: A5769D3F7BE48CDCE28246573B9CF1D9; Granted Authorities: ROLE_USER'
o.s.s.w.FilterChainProxy : /oauth/authorize?client_id=clientId&redirect_uri=http://127.0.0.1:8080/client/login&response_type=code&state=CIjAxa at position 3 of 12 in additional filter chain; firing Filter: 'HeaderWriterFilter'
o.s.s.w.header.writers.HstsHeaderWriter : Not injecting HSTS header since it did not match the requestMatcher o.s.security.web.header.writers.HstsHeaderWriter$SecureRequestMatcher@5b5aeff5
o.s.s.w.FilterChainProxy : /oauth/authorize?client_id=clientId&redirect_uri=http://127.0.0.1:8080/client/login&response_type=code&state=CIjAxa at position 4 of 12 in additional filter chain; firing Filter: 'LogoutFilter'
o.s.s.w.u.matcher.AntPathRequestMatcher : Checking match of request : '/oauth/authorize'; against '/logout'
o.s.s.w.FilterChainProxy : /oauth/authorize?client_id=clientId&redirect_uri=http://127.0.0.1:8080/client/login&response_type=code&state=CIjAxa at position 5 of 12 in additional filter chain; firing Filter: 'UsernamePasswordAuthenticationFilter'
o.s.s.w.u.matcher.AntPathRequestMatcher : Request 'GET /oauth/authorize' doesn't match 'POST /login
o.s.s.w.FilterChainProxy : /oauth/authorize?client_id=clientId&redirect_uri=http://127.0.0.1:8080/client/login&response_type=code&state=CIjAxa at position 6 of 12 in additional filter chain; firing Filter: 'DefaultLoginPageGeneratingFilter'
o.s.s.w.FilterChainProxy : /oauth/authorize?client_id=clientId&redirect_uri=http://127.0.0.1:8080/client/login&response_type=code&state=CIjAxa at position 7 of 12 in additional filter chain; firing Filter: 'RequestCacheAwareFilter'
o.s.s.w.s.DefaultSavedRequest : pathInfo: both null (property equals)
o.s.s.w.s.DefaultSavedRequest : queryString: arg1=client_id=clientId&redirect_uri=http://127.0.0.1:8080/client/login&response_type=code&state=CIjAxa; arg2=client_id=clientId&redirect_uri=http://127.0.0.1:8080/client/login&response_type=code&state=CIjAxa (property equals)
o.s.s.w.s.DefaultSavedRequest : requestURI: arg1=/oauth/authorize; arg2=/oauth/authorize (property equals)
o.s.s.w.s.DefaultSavedRequest : serverPort: arg1=8081; arg2=8081 (property equals)
o.s.s.w.s.DefaultSavedRequest : requestURL: arg1=http://localhost:8081/oauth/authorize; arg2=http://localhost:8081/oauth/authorize (property equals)
o.s.s.w.s.DefaultSavedRequest : scheme: arg1=http; arg2=http (property equals)
o.s.s.w.s.DefaultSavedRequest : serverName: arg1=localhost; arg2=localhost (property equals)
o.s.s.w.s.DefaultSavedRequest : contextPath: arg1=; arg2= (property equals)
o.s.s.w.s.DefaultSavedRequest : servletPath: arg1=/oauth/authorize; arg2=/oauth/authorize (property equals)
o.s.s.w.s.HttpSessionRequestCache : Removing DefaultSavedRequest from session if present
o.s.s.w.FilterChainProxy : /oauth/authorize?client_id=clientId&redirect_uri=http://127.0.0.1:8080/client/login&response_type=code&state=CIjAxa at position 8 of 12 in additional filter chain; firing Filter: 'SecurityContextHolderAwareRequestFilter'
o.s.s.w.FilterChainProxy : /oauth/authorize?client_id=clientId&redirect_uri=http://127.0.0.1:8080/client/login&response_type=code&state=CIjAxa at position 9 of 12 in additional filter chain; firing Filter: 'AnonymousAuthenticationFilter'
o.s.s.w.a.AnonymousAuthenticationFilter : SecurityContextHolder not populated with anonymous token, as it already contained: 'o.s.security.authentication.UsernamePasswordAuthenticationToken@4bc9b896: Principal: o.s.security.core.userdetails.User@f02988d6: Username: username; Password: [PROTECTED]; Enabled: true; AccountNonExpired: true; credentialsNonExpired: true; AccountNonLocked: true; Granted Authorities: ROLE_USER; Credentials: [PROTECTED]; Authenticated: true; Details: o.s.security.web.authentication.WebAuthenticationDetails@fffd3270: RemoteIpAddress: 0:0:0:0:0:0:0:1; SessionId: A5769D3F7BE48CDCE28246573B9CF1D9; Granted Authorities: ROLE_USER'
o.s.s.w.FilterChainProxy : /oauth/authorize?client_id=clientId&redirect_uri=http://127.0.0.1:8080/client/login&response_type=code&state=CIjAxa at position 10 of 12 in additional filter chain; firing Filter: 'SessionManagementFilter'
o.s.s.w.FilterChainProxy : /oauth/authorize?client_id=clientId&redirect_uri=http://127.0.0.1:8080/client/login&response_type=code&state=CIjAxa at position 11 of 12 in additional filter chain; firing Filter: 'ExceptionTranslationFilter'
o.s.s.w.FilterChainProxy : /oauth/authorize?client_id=clientId&redirect_uri=http://127.0.0.1:8080/client/login&response_type=code&state=CIjAxa at position 12 of 12 in additional filter chain; firing Filter: 'FilterSecurityInterceptor'
o.s.s.w.a.i.FilterSecurityInterceptor : Secure object: FilterInvocation: URL: /oauth/authorize?client_id=clientId&redirect_uri=http://127.0.0.1:8080/client/login&response_type=code&state=CIjAxa; Attributes: [permitAll]
o.s.s.w.a.i.FilterSecurityInterceptor : Previously Authenticated: o.s.security.authentication.UsernamePasswordAuthenticationToken@4bc9b896: Principal: o.s.security.core.userdetails.User@f02988d6: Username: username; Password: [PROTECTED]; Enabled: true; AccountNonExpired: true; credentialsNonExpired: true; AccountNonLocked: true; Granted Authorities: ROLE_USER; Credentials: [PROTECTED]; Authenticated: true; Details: o.s.security.web.authentication.WebAuthenticationDetails@fffd3270: RemoteIpAddress: 0:0:0:0:0:0:0:1; SessionId: A5769D3F7BE48CDCE28246573B9CF1D9; Granted Authorities: ROLE_USER
o.s.s.access.vote.AffirmativeBased : Voter: o.s.security.web.access.expression.WebExpressionVoter@38a2b5af, returned: 1
o.s.s.w.a.i.FilterSecurityInterceptor : Authorization successful
o.s.s.w.a.i.FilterSecurityInterceptor : RunAsManager did not change Authentication object
o.s.s.w.FilterChainProxy : /oauth/authorize?client_id=clientId&redirect_uri=http://127.0.0.1:8080/client/login&response_type=code&state=CIjAxa reached end of additional filter chain; proceeding with original chain
.s.o.p.e.FrameworkEndpointHandlerMapping : Looking up handler method for path /oauth/authorize
.s.o.p.e.FrameworkEndpointHandlerMapping : Returning handler method [public o.s.web.servlet.ModelAndView o.s.security.oauth2.provider.endpoint.AuthorizationEndpoint.authorize(java.util.Map<java.lang.String, java.lang.Object>,java.util.Map<java.lang.String, java.lang.String>,o.s.web.bind.support.SessionStatus,java.security.Principal)]
o.s.s.w.a.ExceptionTranslationFilter : Chain processed normally
s.s.w.c.SecurityContextPersistenceFilter : SecurityContextHolder now cleared, as request processing completed
o.s.s.web.util.matcher.OrRequestMatcher : Trying to match using Ant [pattern='/css/**']
o.s.s.w.u.matcher.AntPathRequestMatcher : Checking match of request : '/oauth/token'; against '/css/**'
o.s.s.web.util.matcher.OrRequestMatcher : Trying to match using Ant [pattern='/js/**']
o.s.s.w.u.matcher.AntPathRequestMatcher : Checking match of request : '/oauth/token'; against '/js/**'
o.s.s.web.util.matcher.OrRequestMatcher : Trying to match using Ant [pattern='/images/**']
o.s.s.w.u.matcher.AntPathRequestMatcher : Checking match of request : '/oauth/token'; against '/images/**'
o.s.s.web.util.matcher.OrRequestMatcher : Trying to match using Ant [pattern='/**/favicon.ico']
o.s.s.w.u.matcher.AntPathRequestMatcher : Checking match of request : '/oauth/token'; against '/**/favicon.ico'
o.s.s.web.util.matcher.OrRequestMatcher : Trying to match using Ant [pattern='/error']
o.s.s.w.u.matcher.AntPathRequestMatcher : Checking match of request : '/oauth/token'; against '/error'
o.s.s.web.util.matcher.OrRequestMatcher : No matches found
o.s.s.web.util.matcher.OrRequestMatcher : Trying to match using Ant [pattern='/oauth/token']
o.s.s.w.u.matcher.AntPathRequestMatcher : Checking match of request : '/oauth/token'; against '/oauth/token'
o.s.s.web.util.matcher.OrRequestMatcher : matched
o.s.s.w.FilterChainProxy : /oauth/token at position 1 of 11 in additional filter chain; firing Filter: 'WebAsyncManagerIntegrationFilter'
o.s.s.w.FilterChainProxy : /oauth/token at position 2 of 11 in additional filter chain; firing Filter: 'SecurityContextPersistenceFilter'
o.s.s.w.FilterChainProxy : /oauth/token at position 3 of 11 in additional filter chain; firing Filter: 'HeaderWriterFilter'
o.s.s.w.header.writers.HstsHeaderWriter : Not injecting HSTS header since it did not match the requestMatcher o.s.security.web.header.writers.HstsHeaderWriter$SecureRequestMatcher@460f0137
o.s.s.w.FilterChainProxy : /oauth/token at position 4 of 11 in additional filter chain; firing Filter: 'LogoutFilter'
o.s.s.w.u.matcher.AntPathRequestMatcher : Checking match of request : '/oauth/token'; against '/logout'
o.s.s.w.FilterChainProxy : /oauth/token at position 5 of 11 in additional filter chain; firing Filter: 'BasicAuthenticationFilter'
o.s.s.w.FilterChainProxy : /oauth/token at position 6 of 11 in additional filter chain; firing Filter: 'RequestCacheAwareFilter'
o.s.s.w.FilterChainProxy : /oauth/token at position 7 of 11 in additional filter chain; firing Filter: 'SecurityContextHolderAwareRequestFilter'
o.s.s.w.FilterChainProxy : /oauth/token at position 8 of 11 in additional filter chain; firing Filter: 'AnonymousAuthenticationFilter'
o.s.s.w.a.AnonymousAuthenticationFilter : Populated SecurityContextHolder with anonymous token: 'o.s.security.authentication.AnonymousAuthenticationToken@9055e4a6: Principal: anonymousUser; Credentials: [PROTECTED]; Authenticated: true; Details: o.s.security.web.authentication.WebAuthenticationDetails@957e: RemoteIpAddress: 127.0.0.1; SessionId: null; Granted Authorities: ROLE_ANONYMOUS'
o.s.s.w.FilterChainProxy : /oauth/token at position 9 of 11 in additional filter chain; firing Filter: 'SessionManagementFilter'
o.s.s.w.FilterChainProxy : /oauth/token at position 10 of 11 in additional filter chain; firing Filter: 'ExceptionTranslationFilter'
o.s.s.w.FilterChainProxy : /oauth/token at position 11 of 11 in additional filter chain; firing Filter: 'FilterSecurityInterceptor'
o.s.s.w.u.matcher.AntPathRequestMatcher : Checking match of request : '/oauth/token'; against '/oauth/token'
o.s.s.w.a.i.FilterSecurityInterceptor : Secure object: FilterInvocation: URL: /oauth/token; Attributes: [fullyAuthenticated]
o.s.s.w.a.i.FilterSecurityInterceptor : Previously Authenticated: o.s.security.authentication.AnonymousAuthenticationToken@9055e4a6: Principal: anonymousUser; Credentials: [PROTECTED]; Authenticated: true; Details: o.s.security.web.authentication.WebAuthenticationDetails@957e: RemoteIpAddress: 127.0.0.1; SessionId: null; Granted Authorities: ROLE_ANONYMOUS
o.s.s.access.vote.AffirmativeBased : Voter: o.s.security.web.access.expression.WebExpressionVoter@30d9792, returned: -1
o.s.s.w.a.ExceptionTranslationFilter : Access is denied (user is anonymous); redirecting to authentication entry point
o.s.security.access.AccessDeniedException: Access is denied
at o.s.security.access.vote.AffirmativeBased.decide(AffirmativeBased.java:83) ~[spring-security-core-4.0.4.RELEASE.jar:4.0.4.RELEASE]
at o.s.security.access.intercept.AbstractSecurityInterceptor.beforeInvocation(AbstractSecurityInterceptor.java:232) ~[spring-security-core-4.0.4.RELEASE.jar:4.0.4.RELEASE]
at o.s.security.web.access.intercept.FilterSecurityInterceptor.invoke(FilterSecurityInterceptor.java:123) ~[spring-security-web-4.0.4.RELEASE.jar:4.0.4.RELEASE]
at o.s.security.web.access.intercept.FilterSecurityInterceptor.doFilter(FilterSecurityInterceptor.java:90) ~[spring-security-web-4.0.4.RELEASE.jar:4.0.4.RELEASE]
...
at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1502) [tomcat-embed-core-8.0.33.jar:8.0.33]
at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.run(NioEndpoint.java:1458) [tomcat-embed-core-8.0.33.jar:8.0.33]
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142) [na:1.8.0_66]
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617) [na:1.8.0_66]
at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61) [tomcat-embed-core-8.0.33.jar:8.0.33]
at java.lang.Thread.run(Thread.java:745) [na:1.8.0_66]
o.s.s.w.util.matcher.AndRequestMatcher : Trying to match using Ant [pattern='/**', GET]
o.s.s.w.u.matcher.AntPathRequestMatcher : Request 'POST /oauth/token' doesn't match 'GET /**
o.s.s.w.util.matcher.AndRequestMatcher : Did not match
o.s.s.w.s.HttpSessionRequestCache : Request not saved as configured RequestMatcher did not match
o.s.s.w.a.ExceptionTranslationFilter : Calling Authentication entry point.
s.w.a.DelegatingAuthenticationEntryPoint : Trying to match using MediaTypeRequestMatcher [contentNegotiationStrategy=o.s.web.accept.ContentNegotiationManager@244013bc, matchingMediaTypes=[application/atom+xml, application/x-www-form-urlencoded, application/json, application/octet-stream, application/xml, multipart/form-data, text/xml], useEquals=false, ignoredMediaTypes=[*/*]]
o.s.s.w.u.m.MediaTypeRequestMatcher : httpRequestMediaTypes=[application/json, application/x-www-form-urlencoded]
o.s.s.w.u.m.MediaTypeRequestMatcher : Processing application/json
o.s.s.w.u.m.MediaTypeRequestMatcher : application/atom+xml .isCompatibleWith application/json = false
o.s.s.w.u.m.MediaTypeRequestMatcher : application/x-www-form-urlencoded .isCompatibleWith application/json = false
o.s.s.w.u.m.MediaTypeRequestMatcher : application/json .isCompatibleWith application/json = true
s.w.a.DelegatingAuthenticationEntryPoint : Match found! Executing o.s.security.oauth2.provider.error.OAuth2AuthenticationEntryPoint@33884c2a
s.s.o.p.e.DefaultOAuth2ExceptionRenderer : Written [error="unauthorized", error_description="Full authentication is required to access this resource"] as "application/json" using [o.s.http.converter.json.MappingJackson2HttpMessageConverter@71d92e6a]
s.s.w.c.SecurityContextPersistenceFilter : SecurityContextHolder now cleared, as request processing completed
相关文件:
pom.xml:
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.example</groupId>
<artifactId>oauth-server-test</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>jar</packaging>
<name>oauth-server-test</name>
<description>Demo project for Spring Boot</description>
<parent>
<groupId>o.s.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>1.3.5.RELEASE</version>
<relativePath/>
</parent>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<java.version>1.8</java.version>
</properties>
<dependencies>
<dependency>
<groupId>o.s.cloud</groupId>
<artifactId>spring-cloud-starter-oauth2</artifactId>
</dependency>
<dependency>
<groupId>o.s.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
</dependency>
<dependency>
<groupId>o.s.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>o.s.boot</groupId>
<artifactId>spring-boot-starter-jdbc</artifactId>
</dependency>
<dependency>
<groupId>com.h2database</groupId>
<artifactId>h2</artifactId>
</dependency>
<dependency>
<groupId>o.s.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
<dependencyManagement>
<dependencies>
<dependency>
<groupId>o.s.cloud</groupId>
<artifactId>spring-cloud-dependencies</artifactId>
<version>Brixton.RELEASE</version>
<type>pom</type>
<scope>import</scope>
</dependency>
</dependencies>
</dependencyManagement>
<build>
<plugins>
<plugin>
<groupId>o.s.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
application.yml
spring:
application:
name: oauth-server-test
resources:
chain:
enabled: true
management:
context_path: /admin
logging:
level:
org.springframework.security: DEBUG
server:
port: 8081
WebSecurityConfiguration.java:
package com.example;
import ...
@Configuration
public class WebSecurityConfiguration extends WebSecurityConfigurerAdapter {
@Autowired DataSource dataSource;
@Override
@Bean
public AuthenticationManager authenticationManagerBean() throws Exception {
return super.authenticationManagerBean();
}
@Autowired
public void init(AuthenticationManagerBuilder auth) throws Exception {
auth.jdbcAuthentication().dataSource(dataSource).withUser("username")
.password("password").roles("USER");
}
@Override
protected void configure(HttpSecurity http) throws Exception {
http
.csrf().disable()
.authorizeRequests()
.anyRequest().permitAll()
.and()
.formLogin().permitAll();
}
}
OAuth2AuthorizationConfig.java:
package com.example;
import ...
@Configuration
@EnableAuthorizationServer
public class OAuth2AuthorizationConfig extends AuthorizationServerConfigurerAdapter {
@Autowired private DataSource dataSource;
@Autowired private AuthenticationManager authenticationManager;
private BCryptPasswordEncoder passwordEncoder = new BCryptPasswordEncoder();
@Bean
public JdbcTokenStore tokenStore() {
return new JdbcTokenStore(dataSource);
}
@Bean
protected AuthorizationCodeServices authorizationCodeServices() {
return new JdbcAuthorizationCodeServices(dataSource);
}
@Override
public void configure(AuthorizationServerSecurityConfigurer security)
throws Exception {
security.tokenKeyAccess("permitAll()").checkTokenAccess("isAuthenticated()");
security.passwordEncoder(passwordEncoder);
}
@Override
public void configure(AuthorizationServerEndpointsConfigurer endpoints)
throws Exception {
endpoints.authorizationCodeServices(authorizationCodeServices())
.authenticationManager(authenticationManager).tokenStore(tokenStore())
.approvalStoreDisabled();
}
@Override
public void configure(ClientDetailsServiceConfigurer clients) throws Exception {
clients.jdbc(dataSource)
.withClient("clientId")
.authorizedGrantTypes("implicit", "password")//, "authorization_code")
.scopes("read")
.autoApprove(true)
.and()
.withClient("clientIdPassword")
.secret("secret")
.authorizedGrantTypes("password", "authorization_code", "refresh_token")
.scopes("read");
}
}
OauthServerTestApplication.java:
package com.example;
import ...
@SpringBootApplication
@RestController
public class OauthServerTestApplication {
@Autowired private DataSource dataSource;
public static void main(String[] args) {
SpringApplication.run(OauthServerTestApplication.class, args);
}
@RequestMapping({ "/user", "/me" })
public Map<String, String> user(Principal principal) {
Map<String, String> map = new LinkedHashMap<>();
map.put("name", principal.getName());
return map;
}
}
客户端记录:
o.s.s.w.u.matcher.AntPathRequestMatcher : Request '/login' matched by universal pattern '/**'
o.s.s.w.FilterChainProxy : /login?code=N2L54X&state=7hQn1L at position 1 of 12 in additional filter chain; firing Filter: 'WebAsyncManagerIntegrationFilter'
o.s.s.w.FilterChainProxy : /login?code=N2L54X&state=7hQn1L at position 2 of 12 in additional filter chain; firing Filter: 'SecurityContextPersistenceFilter'
w.c.HttpSessionSecurityContextRepository : HttpSession returned null object for SPRING_SECURITY_CONTEXT
w.c.HttpSessionSecurityContextRepository : No SecurityContext was available from the HttpSession: org.apache.catalina.session.StandardSessionFacade@1e0a5c49. A new one will be created.
o.s.s.w.FilterChainProxy : /login?code=N2L54X&state=7hQn1L at position 3 of 12 in additional filter chain; firing Filter: 'HeaderWriterFilter'
o.s.s.w.header.writers.HstsHeaderWriter : Not injecting HSTS header since it did not match the requestMatcher o.s.security.web.header.writers.HstsHeaderWriter$SecureRequestMatcher@463f1d5c
o.s.s.w.FilterChainProxy : /login?code=N2L54X&state=7hQn1L at position 4 of 12 in additional filter chain; firing Filter: 'CsrfFilter'
o.s.s.w.FilterChainProxy : /login?code=N2L54X&state=7hQn1L at position 5 of 12 in additional filter chain; firing Filter: 'LogoutFilter'
o.s.s.w.u.matcher.AntPathRequestMatcher : Request 'GET /login' doesn't match 'POST /logout
o.s.s.w.FilterChainProxy : /login?code=N2L54X&state=7hQn1L at position 6 of 12 in additional filter chain; firing Filter: 'OAuth2ClientAuthenticationProcessingFilter'
o.s.s.w.u.matcher.AntPathRequestMatcher : Checking match of request : '/login'; against '/login'
uth2ClientAuthenticationProcessingFilter : Request is to process authentication
g.c.AuthorizationCodeAccessTokenProvider : Retrieving token from http://localhost:8081/oauth/token
g.c.AuthorizationCodeAccessTokenProvider : Encoding and sending form: {grant_type=[authorization_code], code=[N2L54X], redirect_uri=[http://127.0.0.1:8080/client/login], client_id=[clientId], client_secret=[secret]}
uth2ClientAuthenticationProcessingFilter : Authentication request failed: o.s.security.authentication.BadCredentialsException: Could not obtain access token
uth2ClientAuthenticationProcessingFilter : Updated SecurityContextHolder to contain null Authentication
uth2ClientAuthenticationProcessingFilter : Delegating to authentication failure handler o.s.security.web.authentication.SimpleUrlAuthenticationFailureHandler@55e17d56
.a.SimpleUrlAuthenticationFailureHandler : No failure URL set, sending 401 Unauthorized error
w.c.HttpSessionSecurityContextRepository : SecurityContext is empty or contents are anonymous - context will not be stored in HttpSession.
s.s.w.c.SecurityContextPersistenceFilter : SecurityContextHolder now cleared, as request processing completed
application.yml:
security:
oauth2:
client:
clientId: clientId
clientSecret: secret
accessTokenUri: http://localhost:8081/oauth/token
userAuthorizationUri: http://localhost:8081/oauth/authorize
tokenName: oauth_token
authenticationScheme: query
clientAuthenticationScheme: form
resource:
userInfoUri: http://localhost:8081/user
spring:
resources:
chain:
enabled: true
server:
port: 8080
context_path: /client
logging:
level:
org.springframework.security: DEBUG
最佳答案
我认为您需要更改clientId和secret,它与facebook和oauth2服务器不同。
关于java - Spring Oauth2无法获得访问 token 问题,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/37524781/