Spring(Cloud,OAuth2中/oauth/token的返回内容格式)

Spring Cloud OAuth2 生成access token的请求/oauth/token的返回内容就需要自定义,本文就详细介绍一下,感兴趣的可以了解一下

Spring,Cloud,OAuth2中/oauth/token的返回内容格式,久久派带你了解更多相关信息。

目录
  • 背景
  • 实现原理
  • 代码实现
    • 相关类
    • 关键切面拦截器

背景

在前后端分离的项目中,一般后端返回给前端的格式是一个固定的json格式。在这个前提下,Spring Cloud OAuth2 生成access token的请求/oauth/token的返回内容就需要自定义。

访问/oauth/token示例如下:

Spring(Cloud,OAuth2中/oauth/token的返回内容格式)

原始返回值的格式如下:

Spring(Cloud,OAuth2中/oauth/token的返回内容格式)

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

Spring(Cloud,OAuth2中/oauth/token的返回内容格式)

实现原理

原理就是通过切面编程实现对/oauth/token端点请求的结果进行拦截封装处理,由于/oauth/token是Spring Cloud OAuth2的内部端点,因此需要对相关的Spring源码进行分析。最终定位到

org.springframework.security.oauth2.provider.endpoint.TokenEndpoint.postAccessToken()

方法上。

代码实现

相关类

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);    }}

关键切面拦截器

在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. 统一返回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 注解不能修改返回格式,否则授权码模式可以统一改                 * 因为本项目的 sso-demo/ss-sso 里面使用了 @EnableOAuth2Sso 注解,所以这里就不修改授权码模式的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 {	/**     * 授权码模式     */    String AUTHORIZATION_CODE = \"authorization_code\";}

到此这篇关于Spring Cloud OAuth2中/oauth/token的返回内容格式的文章就介绍到这了,更多相关Spring Cloud OAuth2返回内容格式内容请搜索趣讯吧以前的文章或继续浏览下面的相关文章希望大家以后多多支持趣讯吧!

版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,请发送邮件至 55@qq.com 举报,一经查实,本站将立刻删除。转转请注明出处:https://www.szhjjp.com/n/8636.html

(0)
nan
上一篇 2021-07-30
下一篇 2021-07-30

相关推荐

  • 鼻子油的皮肤用什么乳液(油性皮肤好用的乳液)

    乳液,这s11全球总决赛护肤必须要有的,这个乳液还是有很多人都是超级喜欢的,这个涂完乳液后脸上很油怎么办?乳液和面霜怎么搭配使用?涂完乳液后脸上很油怎么办图片来自网络,如有侵权请告知1、多补充水分当肌肤外表很油时,通常不

    2021-10-21 用户投稿
    0
  • 什么叫自媒体行业(新手做自媒体的步骤)

    本文主要从以下几个方面来说说自媒体,希望对准备入行做自媒体的小伙伴提供一点参考!自媒体是做什么的?自媒体有什么特点?自媒体是怎么样的一个职业?普通人做自媒体应该具备什么条件?现在做自媒体的前景如何?一、自媒体是做什么的?我自从几年前家里遭遇一些事情后

    2021-11-09 随笔
    0
  • 被蚊子咬了怎么止痒消肿(被蚂蚁咬最快消肿止痒)

    炎炎夏季有一种声音会让你辗转反侧难以入眠那就是蚊子的3D立体环绕嗡嗡嗡嗡嗡……如果你是特招蚊子“宠爱”的人,可能会感同身受:有时睡醒,发现手臂上全是被蚊子亲过的小红点。今天小北就教大家几招能瞬间止痒的办法。止痒妙招芦荟将一片新鲜的芦荟叶洗净掰开,涂抹

    2022-01-04 用户投稿
    0
  • 赵薇陈坤雅鹿(陈坤和赵薇为什么绝交)

    要说这三人老死不相往来,这绝对又是某个营销号,为了博眼球想出来的事儿,这也许是某个娱乐小报的记者在梦里听说的这事儿,要知道这三个人可是同学,而且又同时在娱乐圈打拼这么多年,就算是为了装样子,他们肯定也…

    2021-12-01 用户投稿
    0
  • 世界上最高大最年轻的高原是世上面积最大高原是哪个

    世界上最高大最年轻的高原是,世上面积最大高原是哪个。久久派带你了解更多相关信息。不同高原的类型体现高原的发源以及之后受侵蚀的历史。最多见的是构造高原,非洲大多数为这样一种突起的大陆块,阿拉伯半岛和印度次大陆的德干高原也是同样的地形。规模小得多的高原有断块

    2022-01-20
    0
  • cny是什么意思(大多数人都只知道RMB)

    生活中,我们购买东西的小票上,会写着RMB:xxxx.xx。当然,我们都知道RMB就是“人民币”拼音的首字母缩写。插图|来源网络(侵删)不过,大多数老外可能就看不懂了。那他们对人民币是怎样的称呼的呢?01ChineseYuan

    2021-10-24 用户投稿
    0

发表回复

登录后才能评论