1200字范文,内容丰富有趣,写作的好帮手!
1200字范文 > spring security整合OAuth2.0 搭建认证服务器访问/uaa/login响应返回401解决

spring security整合OAuth2.0 搭建认证服务器访问/uaa/login响应返回401解决

时间:2023-03-04 16:26:57

相关推荐

spring security整合OAuth2.0 搭建认证服务器访问/uaa/login响应返回401解决

一、启动类代码

@SpringBootApplication@EnableResourceServer //删除这个注解//@EnableDiscoveryClient//@EnableGlobalMethodSecurity(prePostEnabled = true)@EnableAuthorizationServerpublic class AuthApplication {public static void main(String[] args) {SpringApplication.run(AuthApplication.class, args);}}

二、继承AuthorizationServerConfigurerAdapter

@Configuration@EnableAuthorizationServerpublic class OAuth2AuthorizationConfig extends AuthorizationServerConfigurerAdapter {@Autowiredprivate AuthorizationCodeServices authorizationCodeServices;@Autowiredprivate AuthorizationServerTokenServices authorizationServerTokenServices;// @Bean// public ClientDetailsService clientDetailsService() {// return new InMemoryClientDetailsService();// }/*** 客户端详情服务* 重写此方法用于声明认证服务器能认证的客户端信息* 相当于再认证服务器中注册那些客户端(包括资源服务器)能访问* @param clients* @throws Exception*/@Overridepublic void configure(ClientDetailsServiceConfigurer clients) throws Exception {// TODO persist clients details//内存配置的方式配置用户信息//内存方式clients.inMemory()//内存模拟client_id.withClient("xql")//客户端 秘钥 以及加密方式BCryptPasswordEncoder.secret(new BCryptPasswordEncoder().encode("xql123"))//客户端拥有的资源列表.resourceIds("res1")//该client允许的授权类型.authorizedGrantTypes("authorization_code","password", "client_credentials", "implicit","refresh_token")//允许的授权范围.scopes("all")//跳转到授权页面.autoApprove(false)//回调地址.redirectUris("");}/*** 配置authenticationManager用于认证的过程* @param endpoints* @throws Exception*/@Overridepublic void configure(AuthorizationServerEndpointsConfigurer endpoints) throws Exception {endpoints.authorizationCodeServices(authorizationCodeServices).tokenServices(authorizationServerTokenServices);}//令牌访问安全策略@Overridepublic void configure(AuthorizationServerSecurityConfigurer oauthServer) throws Exception {oauthServer.tokenKeyAccess("permitAll()").checkTokenAccess("permitAll()").allowFormAuthenticationForClients();}}

最终发现问题主要是启动类添加了@EnableResourceServer注解,删除这个注解。添加这个注解(@EnableResourceServer注解)后资源服务器会对所有的请求进行拦截认证,当然除了oauth相关的请求之外。同时会创建一个拦截器OAuth2AuthenticationProcessingFilter,该拦截器会对请求头Authorization中的值进行相关验证。

三、@EnableResourceServer导入了ResourceServerConfiguration配置类,该配置类继承了WebSecurityConfigurerAdapter,拥有了http security的相关能力。

@Configurationpublic class ResourceServerConfiguration extends WebSecurityConfigurerAdapter implements Ordered {......//请求匹配,对oauth相关请求放行,其他请求拦截private static class NotOAuthRequestMatcher implements RequestMatcher {private FrameworkEndpointHandlerMapping mapping;public NotOAuthRequestMatcher(FrameworkEndpointHandlerMapping mapping) {this.mapping = mapping;}@Overridepublic boolean matches(HttpServletRequest request) {String requestPath = getRequestPath(request);for (String path : mapping.getPaths()) {if (requestPath.startsWith(mapping.getPath(path))) {return false;}}return true;}private String getRequestPath(HttpServletRequest request) {String url = request.getServletPath();if (request.getPathInfo() != null) {url += request.getPathInfo();}return url;}}@Overrideprotected void configure(HttpSecurity http) throws Exception {//资源服务可配置类,添加了OAuth2AuthenticationProcessingFilter过滤器,对请求头Authorization进行验证ResourceServerSecurityConfigurer resources = new ResourceServerSecurityConfigurer();ResourceServerTokenServices services = resolveTokenServices();if (services != null) {resources.tokenServices(services);}else {if (tokenStore != null) {resources.tokenStore(tokenStore);}else if (endpoints != null) {resources.tokenStore(endpoints.getEndpointsConfigurer().getTokenStore());}}if (eventPublisher != null) {resources.eventPublisher(eventPublisher);}for (ResourceServerConfigurer configurer : configurers) {configurer.configure(resources);}// @formatter:offhttp.authenticationProvider(new AnonymousAuthenticationProvider("default"))// N.B. exceptionHandling is duplicated in resources.configure() so that// it works.exceptionHandling().accessDeniedHandler(resources.getAccessDeniedHandler()).and()//访问拒绝处理类.sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS).and().csrf().disable();// @formatter:onhttp.apply(resources);if (endpoints != null) {// Assume we are in an Authorization Serverhttp.requestMatcher(new NotOAuthRequestMatcher(endpoints.oauth2EndpointHandlerMapping()));}for (ResourceServerConfigurer configurer : configurers) {// Delegates can add authorizeRequests() hereconfigurer.configure(http);}if (configurers.isEmpty()) {// Add anyRequest() last as a fall back. Spring Security would// replace an existing anyRequest() matcher with this one, so to// avoid that we only add it if the user hasn't configured anything.http.authorizeRequests().anyRequest().authenticated();}}......}

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。