我正在尝试使用spring boot在oauth2实现中创建简单登录。不幸的是它不起作用,因为我是春天的新手 我的配置
ApplicationStarter.java
@SpringBootApplication
@EnableAutoConfiguration
public class ApplicationStarter extends SpringBootServletInitializer {
@Override
protected SpringApplicationBuilder configure(SpringApplicationBuilder application) {
return application.sources(ApplicationStarter.class);
}
public static void main(String[] args) throws Exception {
SpringApplication.run(ApplicationStarter.class, args);
}
}
ResourceServerConfiguration.java
@Configuration
@EnableResourceServer
public class ResourceServerConfiguration extends ResourceServerConfigurerAdapter {
private static final String RESOURCE_ID = "my_rest_api";
@Override
public void configure(ResourceServerSecurityConfigurer resources) {
resources.resourceId(RESOURCE_ID);
}
@Override
public void configure(HttpSecurity http) throws Exception {
System.out.println("Inside ResourceServerConfiguration");
http.
anonymous().disable()
.requestMatchers().antMatchers("/user/**")
.and().authorizeRequests()
.antMatchers("/user/**").access("hasRole('ADMIN')")
.and().exceptionHandling().accessDeniedHandler(new OAuth2AccessDeniedHandler());
}
}
AuthorizationServerConfiguration.java
@Configuration
@EnableAuthorizationServer
public class AuthorizationServerConfiguration extends AuthorizationServerConfigurerAdapter {
private static String REALM="MY_OAUTH_REALM";
@Autowired
private TokenStore tokenStore;
@Autowired
private UserApprovalHandler userApprovalHandler;
@Autowired
@Qualifier("authenticationManagerBean")
private AuthenticationManager authenticationManager;
@Override
public void configure(ClientDetailsServiceConfigurer clients) throws Exception {
System.out.println("Inside AuthorizationServerConfiguration");
clients.inMemory()
.withClient("my-trusted-client")
.authorizedGrantTypes("password", "authorization_code", "refresh_token", "implicit")
.authorities("ROLE_CLIENT", "ROLE_TRUSTED_CLIENT")
.scopes("read", "write", "trust")
.secret("secret")
.accessTokenValiditySeconds(120).//Access token is only valid for 2 minutes.
refreshTokenValiditySeconds(600);//Refresh token is only valid for 10 minutes.
}
@Override
public void configure(AuthorizationServerEndpointsConfigurer endpoints) throws Exception {
endpoints.tokenStore(tokenStore).userApprovalHandler(userApprovalHandler)
.authenticationManager(authenticationManager);
}
@Override
public void configure(AuthorizationServerSecurityConfigurer oauthServer) throws Exception {
oauthServer.realm(REALM+"/client");
}
}
MethodSecurityConfig.java
@Configuration
@EnableGlobalMethodSecurity(prePostEnabled = true, proxyTargetClass = true)
public class MethodSecurityConfig extends GlobalMethodSecurityConfiguration {
@Autowired
private OAuth2SecurityConfiguration securityConfig;
@Override
protected MethodSecurityExpressionHandler createExpressionHandler() {
return new OAuth2MethodSecurityExpressionHandler();
}
}
OAuth2SecurityConfiguration.java
@Configuration
@ComponentScan
@EnableWebSecurity
public class OAuth2SecurityConfiguration extends WebSecurityConfigurerAdapter {
@Autowired
private ClientDetailsService clientDetailsService;
@Autowired
public void globalUserDetails(AuthenticationManagerBuilder auth) throws Exception {
System.out.println("inside OAuth2SecurityConfiguration : globalUserDetails()");
auth.inMemoryAuthentication()
.withUser("bill").password("abc123").roles("ADMIN").and()
.withUser("bob").password("abc123").roles("USER");
}
@Override
protected void configure(HttpSecurity http) throws Exception {
System.out.println("inside OAuth2SecurityConfiguration : configure()");
http
.csrf().disable()
.anonymous().disable()
.authorizeRequests()
.antMatchers("/oauth/token").permitAll();
}
@Override
@Bean
public AuthenticationManager authenticationManagerBean() throws Exception {
System.out.println("inside OAuth2SecurityConfiguration : authenticationManagerBean()");
return super.authenticationManagerBean();
}
@Bean
public TokenStore tokenStore() {
System.out.println("inside OAuth2SecurityConfiguration : tokenStore()");
return new InMemoryTokenStore();
}
@Bean
@Autowired
public TokenStoreUserApprovalHandler userApprovalHandler(TokenStore tokenStore){
System.out.println("inside OAuth2SecurityConfiguration : userApprovalHandler()");
TokenStoreUserApprovalHandler handler = new TokenStoreUserApprovalHandler();
handler.setTokenStore(tokenStore);
handler.setRequestFactory(new DefaultOAuth2RequestFactory(clientDetailsService));
handler.setClientDetailsService(clientDetailsService);
return handler;
}
@Bean
@Autowired
public ApprovalStore approvalStore(TokenStore tokenStore) throws Exception {
System.out.println("inside OAuth2SecurityConfiguration : approvalStore()");
TokenApprovalStore store = new TokenApprovalStore();
store.setTokenStore(tokenStore);
return store;
}
}
请在我出错的地方纠正我?是否需要更多配置?
我按照跟随 http://websystique.com/spring-security/secure-spring-rest-api-using-oauth2/ 作为参考。春季启动日志
2017-10-26 11:15:07.851 DEBUG 21456 --- [nio-8080-exec-5] o.s.b.w.f.OrderedRequestContextFilter:绑定请求上下文 thread:org.apache.catalina.connector.RequestFacade@1f2fcd1 2017-10-26 11:15:07.851 DEBUG 21456 --- [nio-8080-exec-5] o.s.s.web.util.matcher.OrRequestMatcher:尝试使用Ant进行匹配 [pattern =' / css / '] 2017-10-26 11:15:07.851 DEBUG 21456 --- [nio-8080-exec-5] o.s.s.w.u.matcher.AntPathRequestMatcher:正在检查 请求匹配:' / oauth / token&#39 ;;反对' / css / ' 2017年10月26日 11:15:07.851 DEBUG 21456 --- [nio-8080-exec-5] o.s.s.web.util.matcher.OrRequestMatcher:尝试使用Ant进行匹配 [pattern =' / js / '] 2017-10-26 11:15:07.851 DEBUG 21456 --- [nio-8080-exec-5] o.s.s.w.u.matcher.AntPathRequestMatcher:正在检查 请求匹配:' / oauth / token&#39 ;;反对' / js / ' 2017年10月26日 11:15:07.851 DEBUG 21456 --- [nio-8080-exec-5] o.s.s.web.util.matcher.OrRequestMatcher:尝试使用Ant进行匹配 [pattern =' / images / '] 2017-10-26 11:15:07.851 DEBUG 21456 --- [nio-8080-exec-5] o.s.s.w.u.matcher.AntPathRequestMatcher:正在检查 请求匹配:' / oauth / token&#39 ;;反对' / images / ' 2017年10月26日 11:15:07.851 DEBUG 21456 --- [nio-8080-exec-5] o.s.s.web.util.matcher.OrRequestMatcher:尝试使用Ant进行匹配 [pattern =' / webjars / '] 2017-10-26 11:15:07.851 DEBUG 21456 --- [nio-8080-exec-5] o.s.s.w.u.matcher.AntPathRequestMatcher:正在检查 请求匹配:' / oauth / token&#39 ;;反对' / webjars / ' 2017年10月26日 11:15:07.851 DEBUG 21456 --- [nio-8080-exec-5] o.s.s.web.util.matcher.OrRequestMatcher:尝试使用Ant进行匹配 [pattern =' / /favicon.ico'] 2017-10-26 11:15:07.851 DEBUG 21456 --- [nio-8080-exec-5] o.s.s.w.u.matcher.AntPathRequestMatcher:正在检查 请求匹配:' / oauth / token&#39 ;;反对' / /favicon.ico' 2017-10-26 11:15:07.851 DEBUG 21456 --- [nio-8080-exec-5] o.s.s.web.util.matcher.OrRequestMatcher:尝试使用Ant进行匹配 [pattern =' / error'] 2017-10-26 11:15:07.851 DEBUG 21456 --- [nio-8080-exec-5] o.s.s.w.u.matcher.AntPathRequestMatcher:正在检查 请求匹配:' / oauth / token&#39 ;;反对' /错误' 2017年10月26日 11:15:07.851 DEBUG 21456 --- [nio-8080-exec-5] o.s.s.web.util.matcher.OrRequestMatcher:找不到匹配项2017-10-26 11:15:07.851 DEBUG 21456 --- [nio-8080-exec-5] o.s.s.web.util.matcher.OrRequestMatcher:尝试使用Ant进行匹配 [pattern =' / '] 2017-10-26 11:15:07.851 DEBUG 21456 --- [nio-8080-exec-5] o.s.s.w.u.matcher.AntPathRequestMatcher:Request ' /的OAuth /令牌'与通用模式匹配' / ' 2017年10月26日 11:15:07.851 DEBUG 21456 --- [nio-8080-exec-5] o.s.s.web.util.matcher.OrRequestMatcher:匹配2017-10-26 11:15:07.851 DEBUG 21456 --- [nio-8080-exec-5] o.s.security.web.FilterChainProxy: / oauth / token?grant_type = password& username = bill& password = abc123 at 在附加过滤链中的位置1的11;射击过滤器: ' WebAsyncManagerIntegrationFilter' 2017-10-26 11:15:07.851 DEBUG 21456 --- [nio-8080-exec-5] o.s.security.web.FilterChainProxy:/ oauth / token?grant_type = password& username = bill& password = abc123 at 在附加过滤链中的位置2的11;射击过滤器: ' SecurityContextPersistenceFilter' 2017-10-26 11:15:07.852 DEBUG 21456 --- [nio-8080-exec-5] o.s.security.web.FilterChainProxy:/ oauth / token?grant_type = password& username = bill& password = abc123 at 位置3的11位于额外的过滤链中;射击过滤器: ' HeaderWriterFilter' 2017-10-26 11:15:07.852 DEBUG 21456 --- [nio-8080-exec-5] o.s.security.web.FilterChainProxy: / oauth / token?grant_type = password& username = bill& password = abc123 at 位置4的11位于额外的过滤链中;射击过滤器: ' LogoutFilter' 2017-10-26 11:15:07.852 DEBUG 21456 --- [nio-8080-exec-5] o.s.s.web.util.matcher.OrRequestMatcher:试图 使用Ant匹配[pattern =' / logout',GET] 2017-10-26 11:15:07.852 DEBUG 21456 --- [nio-8080-exec-5] o.s.s.w.u.matcher.AntPathRequestMatcher: 请求' POST / oauth / token'没有匹配' GET /注销2017-10-26 11:15:07.852 DEBUG 21456 --- [nio-8080-exec-5] o.s.s.web.util.matcher.OrRequestMatcher:尝试使用Ant进行匹配 [pattern =' / logout',POST] 2017-10-26 11:15:07.852 DEBUG 21456 --- [nio-8080-exec-5] o.s.s.w.u.matcher.AntPathRequestMatcher:正在检查 请求匹配:' / oauth / token&#39 ;;反对' /注销' 2017年10月26日 11:15:07.852 DEBUG 21456 --- [nio-8080-exec-5] o.s.s.web.util.matcher.OrRequestMatcher:尝试使用Ant进行匹配 [pattern =' / logout',PUT] 2017-10-26 11:15:07.869 DEBUG 21456 --- [nio-8080-exec-5] o.s.s.w.u.matcher.AntPathRequestMatcher:Request ' POST / oauth / token'没有匹配' PUT /注销2017-10-26 11:15:07.869 DEBUG 21456 --- [nio-8080-exec-5] o.s.s.web.util.matcher.OrRequestMatcher:尝试使用Ant进行匹配 [pattern =' / logout',DELETE] 2017-10-26 11:15:07.869 DEBUG 21456 --- [nio-8080-exec-5] o.s.s.w.u.matcher.AntPathRequestMatcher:Request ' POST / oauth / token'没有匹配' DELETE / logout 2017-10-26 11:15:07.869 DEBUG 21456 --- [nio-8080-exec-5] o.s.s.web.util.matcher.OrRequestMatcher:找不到匹配项2017-10-26 11:15:07.869 DEBUG 21456 --- [nio-8080-exec-5] o.s.security.web.FilterChainProxy: / oauth / token?grant_type = password& username = bill& password = abc123 at 第5位,共11个在另外的过滤链中;射击过滤器: ' BasicAuthenticationFilter一样' 2017-10-26 11:15:07.869 DEBUG 21456 --- [nio-8080-exec-5] o.s.s.w.a.www.BasicAuthenticationFilter:Basic 为用户“我信任的客户端”找到的身份验证授权标头' 2017-10-26 11:15:07.869 DEBUG 21456 --- [nio-8080-exec-5] o.s.s.authentication.ProviderManager:身份验证尝试 运用 org.springframework.security.authentication.dao.DaoAuthenticationProvider 2017-10-26 11:15:07.869 DEBUG 21456 --- [nio-8080-exec-5] o.s.s.a.dao.DaoAuthenticationProvider:用户' my-trusted-client' 未找到2017-10-26 11:15:07.869 DEBUG 21456 --- [nio-8080-exec-5] o.s.s.w.a.www.BasicAuthenticationFilter:身份验证请求 失败: org.springframework.security.authentication.BadCredentialsException: 不良凭据2017-10-26 11:15:07.869 DEBUG 21456 --- [nio-8080-exec-5] o.s.s.w.header.writers.HstsHeaderWriter:不是 注入HSTS标头,因为它与requestMatcher不匹配 org.springframework.security.web.header.writers.HstsHeaderWriter$SecureRequestMatcher@1ff799 2017-10-26 11:15:07.869 DEBUG 21456 --- [nio-8080-exec-5] s.s.w.c.SecurityContextPersistenceFilter:SecurityContextHolder现在 清除,请求处理完成2017-10-26 11:15:07.869 DEBUG 21456 --- [nio-8080-exec-5] o.s.b.w.f.OrderedRequestContextFilter: 清除线程绑定请求上下文: org.apache.catalina.connector.RequestFacade@1f2fcd1 2017-10-26 11:15:07.870 DEBUG 21456 --- [nio-8080-exec-5] o.s.web.servlet.DispatcherServlet:带名称的DispatcherServlet ' DispatcherServlet的'处理[/ auth / error]的POST请求 2017-10-26 11:15:07.870 DEBUG 21456 --- [nio-8080-exec-5] s.w.s.m.m.a.RequestMappingHandlerMapping:查找处理程序方法 路径/错误2017-10-26 11:15:07.870 DEBUG 21456 --- [nio-8080-exec-5] s.w.s.m.m.a.RequestMappingHandlerMapping:返回 处理方法[公共 org.springframework.http.ResponseEntity> org.springframework.boot.autoconfigure.web.BasicErrorController.error(javax.servlet.http.HttpServletRequest)] 2017-10-26 11:15:07.870 DEBUG 21456 --- [nio-8080-exec-5] o.s.b.f.s.DefaultListableBeanFactory:返回缓存的实例 singleton bean' basicErrorController' 2017-10-26 11:15:07.874调试 21456 --- [nio-8080-exec-5] o.s.w.s.m.m.a.HttpEntityMethodProcessor: 写的[{timestamp =星期四10月26日11:15:07 IST 2017,状态= 401, error = Unauthorized,message = Bad credentials,path = / auth / oauth / token}] as" application / json"运用 [org.springframework.http.converter.json.MappingJackson2HttpMessageConverter@32886a] 2017-10-26 11:15:07.874 DEBUG 21456 --- [nio-8080-exec-5] o.s.web.servlet.DispatcherServlet:返回Null ModelAndView 到DispatcherServlet的名称' dispatcherServlet':假设 HandlerAdapter完成了请求处理2017-10-26 11:15:07.874 DEBUG 21456 --- [nio-8080-exec-5] o.s.web.servlet.DispatcherServlet
:已成功完成请求
gradle.build
> /* * This build file was generated by the Gradle 'init' task. * *
> This generated file contains a sample Java Library project to get you
> started. * For more details take a look at the Java Libraries chapter
> in the Gradle * user guide available at
> https://docs.gradle.org/3.5/userguide/java_library_plugin.html */
> buildscript {
> ext { springBootVersion = '1.5.7.RELEASE' }
> repositories { mavenCentral() }
> dependencies { classpath("org.springframework.boot:spring-boot-gradle-plugin:${springBootVersion}")
> } } // Apply the java-library plugin to add support for Java Library
> apply plugin: 'java' apply plugin: 'eclipse' apply plugin:
> 'org.springframework.boot' apply plugin: 'war'
>
>
> sourceCompatibility = 1.8 // In this section you declare where to find
> the dependencies of your project repositories {
> // Use jcenter for resolving your dependencies.
> // You can declare any Maven/Ivy/file repository here. // jcenter() mavenCentral() }
>
> dependencies {
> // This dependency is exported to consumers, that is to say found on their compile classpath.
> //api 'org.apache.commons:commons-math3:3.6.1'
> //providedRuntime 'org.springframework.boot:spring-boot-starter-tomcat:1.5.2.RELEASE'
> // This dependency is used internally, and not exposed to consumers on their own compile classpath.
> implementation 'com.google.guava:guava:21.0'
>
> // Use JUnit test framework
> testImplementation 'junit:junit:4.12'
>
>
> // compile("org.springframework.boot:spring-boot-starter-security:1.4.1.RELEASE")
> // compile("org.springframework.security.oauth:spring-security-oauth2:2.0.2.RELEASE")
> //
> compile("org.springframework.security:spring-security-config:3.2.0.RELEASE")
> // compile("org.gitlab4j:gitlab4j-api:4.6.0")
> // compile("org.springframework.boot:spring-boot-starter-tomcat:1.5.2.RELEASE")
>
> compile('org.springframework.boot:spring-boot-starter-actuator')
> compile('org.springframework.boot:spring-boot-starter-security')
> compile('org.springframework.security.oauth:spring-security-oauth2')
> compile('org.springframework.security:spring-security-config')
> compile('org.springframework.boot:spring-boot-starter-web')
> providedRuntime("org.springframework.boot:spring-boot-starter-tomcat")
>
> testCompile('org.springframework.boot:spring-boot-starter-test') }
答案 0 :(得分:0)
更改您的授权服务器配置
AuthorizationServerConfiguration.java
@Override
public void configure(ClientDetailsServiceConfigurer clients) throws Exception {
System.out.println("Inside AuthorizationServerConfiguration");
clients.inMemory()
.withClient("my-trusted-client")
.authorizedGrantTypes("password", "authorization_code", "refresh_token", "implicit")
.authorities("ROLE_CLIENT", "ROLE_TRUSTED_CLIENT")
.scopes("read", "write", "trust").resourceIds("my_rest_api")
.secret("secret")
.accessTokenValiditySeconds(120).//Access token is only valid for 2 minutes.
refreshTokenValiditySeconds(600);//Refresh token is only valid for 10 minutes.
}
此处更改是我在范围之后放置了一个resourceId,并且该资源ID与资源服务器的RESOURCE_ID
相同。
您在ResourceServerConfiguration中声明了这样的
private static final String RESOURCE_ID = "my_rest_api";
因此,将字符串放入授权服务器可以解决您的问题 感谢。