Spring Cloud OAuth2中/oauth/token的返回內(nèi)容格式
在前后端分離的項目中,一般后端返回給前端的格式是一個固定的json格式。在這個前提下,Spring Cloud OAuth2 生成access token的請求/oauth/token的返回內(nèi)容就需要自定義。
訪問/oauth/token示例如下:

原始返回值的格式如下:

我們希望使用我們自己固定的json格式,如下:

原理就是通過切面編程實現(xiàn)對/oauth/token端點請求的結(jié)果進行攔截封裝處理,由于/oauth/token是Spring Cloud OAuth2的內(nèi)部端點,因此需要對相關(guān)的Spring源碼進行分析。最終定位到
org.springframework.security.oauth2.provider.endpoint.TokenEndpoint.postAccessToken()
方法上。
代碼實現(xiàn)相關(guān)類CodeEnum.java
package com.wongoing.common.model;/** * @description: 代碼枚舉 * @author: zheng * @date: Created in 2021/1/26 11:18 * @version: 0.0.1 * @modified By: */public enum CodeEnum { SUCCESS(0), ERROR(1); private Integer code; CodeEnum(Integer code) {this.code = code; } public Integer getCode() {return this.code; }}
Result.java
package com.wongoing.common.model;import lombok.AllArgsConstructor;import lombok.Data;import lombok.NoArgsConstructor;import java.io.Serializable;/** * @description: Rest API 接口方法返回類型定義 * @author: zheng * @date: Created in 2021/1/26 13:25 * @version: 0.0.1 * @modified By: */@Data@NoArgsConstructor@AllArgsConstructorpublic class Result<T> implements Serializable { private T data; private Integer code; private String msg; public static <T> Result<T> of(T data, Integer code, String msg) {return new Result<>(data, code, msg); } public static <T> Result<T> succeed(String msg) {return of(null, CodeEnum.SUCCESS.getCode(), msg); } public static <T> Result<T> succeed(T model, String msg) {return of(model, CodeEnum.SUCCESS.getCode(), msg); } public static <T> Result<T> succeed(T model) {return of(model, CodeEnum.SUCCESS.getCode(), ''); } public static <T> Result<T> failed(String msg) {return of(null, CodeEnum.ERROR.getCode(), msg); } public static <T> Result<T> failed(T model, String msg) {return of(model, CodeEnum.ERROR.getCode(), msg); }}關(guān)鍵切面攔截器
在uaa項目中定義OauthTokenAspect.java
package com.wongoing.oauth2.filter;import com.wongoing.common.constant.SecurityConstants;import com.wongoing.common.context.TenantContextHolder;import com.wongoing.common.model.Result;import lombok.extern.slf4j.Slf4j;import org.aspectj.lang.ProceedingJoinPoint;import org.aspectj.lang.annotation.Around;import org.aspectj.lang.annotation.Aspect;import org.springframework.http.HttpStatus;import org.springframework.http.ResponseEntity;import org.springframework.security.authentication.InsufficientAuthenticationException;import org.springframework.security.core.Authentication;import org.springframework.security.oauth2.common.OAuth2AccessToken;import org.springframework.security.oauth2.common.util.OAuth2Utils;import org.springframework.security.oauth2.provider.OAuth2Authentication;import org.springframework.stereotype.Component;import java.security.Principal;import java.util.Map;/** * @description: oauth-token攔截器 * 1. 賦值租戶 * 2. 統(tǒng)一返回token格式 * * @author: zheng * @date: Created in 2021/7/12 16:25 * @version: 0.0.1 * @modified By: */@Slf4j@Component@Aspectpublic class OauthTokenAspect { @Around('execution(* org.springframework.security.oauth2.provider.endpoint.TokenEndpoint.postAccessToken(..))') public Object handleControllerMethod(ProceedingJoinPoint joinPoint) throws Throwable {try { Object[] args = joinPoint.getArgs(); Principal principal = (Principal) args[0]; if (!(principal instanceof Authentication)) {throw new InsufficientAuthenticationException('There is no client authentication. Try adding an appropriate authentication filter.'); } String clientId = this.getClientId(principal); Map<String, String> parameters = (Map<String, String>) args[1]; String grantType = parameters.get(OAuth2Utils.GRANT_TYPE); //保存租戶id TenantContextHolder.setTenant(clientId); Object proceed = joinPoint.proceed(); if (SecurityConstants.AUTHORIZATION_CODE.equals(grantType)) {/** * 如果使用 @EnableOAuth2Sso 注解不能修改返回格式,否則授權(quán)碼模式可以統(tǒng)一改 * 因為本項目的 sso-demo/ss-sso 里面使用了 @EnableOAuth2Sso 注解,所以這里就不修改授權(quán)碼模式的token返回值了 */return proceed; } else {ResponseEntity<OAuth2AccessToken> responseEntity = (ResponseEntity<OAuth2AccessToken>) proceed;OAuth2AccessToken body = responseEntity.getBody();return ResponseEntity.status(HttpStatus.OK).body(Result.succeed(body)); }} finally { TenantContextHolder.clear();} } private String getClientId(Principal principal) {Authentication client = (Authentication) principal;if (!client.isAuthenticated()) { throw new InsufficientAuthenticationException('The client is not authenticated.');}String clientId = client.getName();if (client instanceof OAuth2Authentication) { clientId = ((OAuth2Authentication) client).getOAuth2Request().getClientId();}return clientId; }}
其中的常量值:
public abstract class OAuth2Utils {public static final String GRANT_TYPE = 'grant_type';}
public interface SecurityConstants {/** * 授權(quán)碼模式 */ String AUTHORIZATION_CODE = 'authorization_code';}
到此這篇關(guān)于Spring Cloud OAuth2中/oauth/token的返回內(nèi)容格式的文章就介紹到這了,更多相關(guān)Spring Cloud OAuth2返回內(nèi)容格式內(nèi)容請搜索好吧啦網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持好吧啦網(wǎng)!
相關(guān)文章:
1. ASP動態(tài)網(wǎng)頁制作技術(shù)經(jīng)驗分享2. vue項目登錄成功拿到令牌跳轉(zhuǎn)失敗401無登錄信息的解決3. php使用正則驗證密碼字段的復(fù)雜強度原理詳細講解 原創(chuàng)4. JSP+Servlet實現(xiàn)文件上傳到服務(wù)器功能5. 淺談由position屬性引申的css進階討論6. ASP 信息提示函數(shù)并作返回或者轉(zhuǎn)向7. 基于javaweb+jsp實現(xiàn)企業(yè)財務(wù)記賬管理系統(tǒng)8. CSS可以做的幾個令你嘆為觀止的實例分享9. vue前端RSA加密java后端解密的方法實現(xiàn)10. asp批量添加修改刪除操作示例代碼

網(wǎng)公網(wǎng)安備