Spring Security OAuth formatted token output

Personalized token background

As mentioned in the previous article "Spring Security OAuth Personalized Token (1)" , the default message format returned by the oauth2.0 interface is as follows:

{  
    "access_token": "e6669cdf-b6cd-43fe-af5c-f91a65041382",  
    "token_type": "bearer",  
    "refresh_token": "da91294d-446c-4a89-bdcf-88aee15a75e8",  
    "expires_in": 43199,   
    "scope": "server"  
}  复制代码

Through the last article we have been able to expand and add some business fields.

{  
    "access_token":"a6f3b6d6-93e6-4eb8-a97d-3ae72240a7b0",  
    "token_type":"bearer",  
    "refresh_token":"710ab162-a482-41cd-8bad-26456af38e4f",  
    "expires_in":42396,  
    "scope":"server",  
    "tenant_id":1,  
    "license":"made by pigx",  
    "dept_id":1,  
    "user_id":1,  
    "username":"admin"  
}  复制代码

"In some scenarios, we need to customize the format of the returned message. For example, pig uses the R object to return, and all contain code service code information."

{  
    "code":1,  
    "msg":"",  
    "data":{  
        "access_token":"e6669cdf-b6cd-43fe-af5c-f91a65041382",  
        "token_type":"bearer",  
        "refresh_token":"da91294d-446c-4a89-bdcf-88aee15a75e8",  
        "expires_in":43199,  
        "scope":"server"  
    }  
}  复制代码

Method 1: HandlerMethodReturnValueHandler

  • As the name suggests, this is the interface that Spring MVC provides us to modify the method return value
public class FormatterToken implements HandlerMethodReturnValueHandler {  

 private static final String POST_ACCESS_TOKEN = "postAccessToken";  

 @Override  
 public boolean supportsReturnType(MethodParameter returnType) {  
     // 判断方法名是否是 oauth2 的token 接口,是就处理  
  return POST_ACCESS_TOKEN.equals(Objects  
    .requireNonNull(returnType.getMethod()).getName());  
 }  
    
  // 获取到返回值然后使用 R对象统一包装  
 @Override  
 public void handleReturnValue(Object returnValue, MethodParameter returnType, ModelAndViewContainer container, NativeWebRequest request) throws Exception {  
  ResponseEntity<OAuth2AccessToken> responseEntity = (ResponseEntity) returnValue;  
  OAuth2AccessToken body = responseEntity.getBody();  

  HttpServletResponse response = request.getNativeResponse(HttpServletResponse.class);  
  assert response != null;  
  WebUtils.renderJson(response, R.ok(body));  
 }  
}  复制代码
  • Inject FormatterToken, you must do this, do not directly use MVCconfig injection, to ensure that this Handler is executed earlier than SpringMVC by default.
public class FormatterTokenAutoConfiguration implements ApplicationContextAware, InitializingBean {  
 private ApplicationContext applicationContext;  

 @Override  
 public void afterPropertiesSet() {  
  RequestMappingHandlerAdapter handlerAdapter = applicationContext.getBean(RequestMappingHandlerAdapter.class);  
  List<HandlerMethodReturnValueHandler> returnValueHandlers = handlerAdapter.getReturnValueHandlers();  

  List<HandlerMethodReturnValueHandler> newHandlers = new ArrayList<>();  
  newHandlers.add(new FormatterToken());  
  assert returnValueHandlers != null;  
  newHandlers.addAll(returnValueHandlers);  
  handlerAdapter.setReturnValueHandlers(newHandlers);  
 }  

 @Override  
 public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {  
  this.applicationContext = applicationContext;  
 }  
}  复制代码

Method 2: AOP interception enhanced / oauth / token interface

@Around("execution(* org.springframework.security.oauth2.provider.endpoint.TokenEndpoint.postAccessToken(..))")  
public Object handlePostAccessTokenMethod(ProceedingJoinPoint joinPoint) throws Throwable {  
   // 获取原有值,进行包装返回  
      Object proceed = joinPoint.proceed();  

      ResponseEntity<OAuth2AccessToken> responseEntity = (ResponseEntity<OAuth2AccessToken>) proceed;  
        OAuth2AccessToken body = responseEntity.getBody();  
        return ResponseEntity  
                  .status(HttpStatus.OK)  
                  .body(R.ok(body));  
        }  
}  复制代码

to sum up

It is not recommended to modify the access format of this interface in the actual project. Incompatibility with the oauth2 protocol results in other components not being used normally

  • swagger comes with authentication and authorization

  • Oauth2 that comes with other gateway components

docs.konghq.com/hub/kong-in…

  • spring security oauth2 comes with sso function

All will invalidate the overall to weigh the harm outweigh the benefits image

Guess you like

Origin juejin.im/post/5e9e3f78e51d4546c423566c