springboot Oauth2配置OAuth2AuthenticationProcessingFilter

工作中遇到一个比较蛋疼的情况,Oauth2人家的jar包封装的好好的,当access_token超时的时候,返回的是OAuth2Exception,格式是{"error":"invalid_request","error_description":"code:'401','msg'='Invalid access token'"}。可是公司其他和我对接的同事非要我统一所有的返回为code,msg。这就头疼了,不得不涉及到学习源码,然后重写掉人家封装好的response处理模块。于是经过一天的研究,终于实现了,当然,代码比较挫,大家看看就好。

源码里就是通过一个fiter去拦截请求,然后通过查询数据库调用Oauth2AuthenticationManager验证token是否有效。其实下面写的白话文配置就是整个源码的内容了。结果集封装的时候,我重写的方法里把原有泛型去掉了,不然别想code+msg了。

		@Configuration
		@EnableResourceServer
		protected class ResourceServerConfiguration extends ResourceServerConfigurerAdapter {
			@Override
			public void configure(HttpSecurity http) throws Exception {
				OAuth2AuthenticationProcessingFilter f = new OAuth2AuthenticationProcessingFilter();
				OAuth2AuthenticationEntryPoint oAuth2AuthenticationEntryPoint = new OAuth2AuthenticationEntryPoint();
				oAuth2AuthenticationEntryPoint.setExceptionTranslator(webResponseExceptionTranslator());
				f.setAuthenticationEntryPoint(oAuth2AuthenticationEntryPoint);
				OAuth2AuthenticationManager o = new OAuth2AuthenticationManager();
				DefaultTokenServices dt = new DefaultTokenServices();
				dt.setTokenStore(tokenStore());
				o.setTokenServices(dt);
				f.setAuthenticationManager(o);

				http.antMatcher("/api/**/**").authorizeRequests().anyRequest().authenticated().and().addFilterBefore(f,
						AbstractPreAuthenticatedProcessingFilter.class);
			}
		}

		@Bean
		public WebResponseExceptionTranslator webResponseExceptionTranslator() {
			return new DefaultWebResponseExceptionTranslator() {
				@Override
				public ResponseEntity translate(Exception e) throws Exception {
					ResponseEntity responseEntity = super.translate(e);
					OAuth2Exception body = (OAuth2Exception) responseEntity.getBody();
					HttpHeaders headers = new HttpHeaders();
					headers.setAll(responseEntity.getHeaders().toSingleValueMap());
					// do something with header or response
					if(401==responseEntity.getStatusCode().value()){	
						Response r=new Response();
						r.setCodeAndMsg(401, "Invalid access token");
						return new ResponseEntity(JacksonUtil.beanToJson(r), headers, responseEntity.getStatusCode());
					}else{
						return new ResponseEntity(body, headers, responseEntity.getStatusCode());
					}
					
				}
			};
		}
	

你可能感兴趣的:(java,springboot,oauth)