广告
返回顶部
首页 > 资讯 > 后端开发 > Python >Spring Cloud OAuth2中/oauth/token的返回内容格式
  • 924
分享到

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

2024-04-02 19:04:59 924人浏览 薄情痞子

Python 官方文档:入门教程 => 点击学习

摘要

目录背景实现原理代码实现相关类关键切面拦截器背景 在前后端分离的项目中,一般后端返回给前端的格式是一个固定的JSON格式。在这个前提下,spring cloud OAuth2 生成a

背景

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

访问/oauth/token示例如下:

在这里插入图片描述

原始返回值的格式如下:

在这里插入图片描述

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

在这里插入图片描述

实现原理

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


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

方法上。

代码实现

相关类

CodeEnum.java


package com.wonGoing.common.model;


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;


@Data
@NoArgsConstructor
@AllArgsConstructor
public 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;


@Slf4j
@Component
@Aspect
public 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)) {
                
                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返回内容格式内容请搜索编程网以前的文章或继续浏览下面的相关文章希望大家以后多多支持编程网!

--结束END--

本文标题: Spring Cloud OAuth2中/oauth/token的返回内容格式

本文链接: https://www.lsjlt.com/news/131532.html(转载时请注明来源链接)

有问题或投稿请发送至: 邮箱/279061341@qq.com    QQ/279061341

本篇文章演示代码以及资料文档资料下载

下载Word文档到电脑,方便收藏和打印~

下载Word文档
猜你喜欢
  • Spring Cloud OAuth2中/oauth/token的返回内容格式
    目录背景实现原理代码实现相关类关键切面拦截器背景 在前后端分离的项目中,一般后端返回给前端的格式是一个固定的json格式。在这个前提下,Spring Cloud OAuth2 生成a...
    99+
    2022-11-12
  • Spring Cloud OAuth2中/oauth/token返回的内容格式是什么
    本篇内容介绍了“Spring Cloud OAuth2中/oauth/token返回的内容格式是什么”的有关知识,在实际案例的操作过程中,不少人都会遇到这样的困境,接下来就让小编带领大家学习一下如何处理这些情况吧!希望大家仔细阅读,能够学有...
    99+
    2023-06-20
  • Spring Cloud OAuth2实现自定义token返回格式
    目录问题描述解决方案总结最近读者朋友针对Spring Security OAuth2.0 想要陈某补充一些知识,如下: 今天这篇文章就来回答其中一个问题:如何自定义token的返回...
    99+
    2022-11-13
  • Spring Cloud OAuth2怎么实现自定义token返回格式
    这篇“Spring Cloud OAuth2怎么实现自定义token返回格式”文章的知识点大部分人都不太理解,所以小编给大家总结了以下内容,内容详细,步骤清晰,具有一定的借鉴价值,希望大家阅读完这篇文章能有所收获,下面我...
    99+
    2023-07-02
软考高级职称资格查询
编程网,编程工程师的家园,是目前国内优秀的开源技术社区之一,形成了由开源软件库、代码分享、资讯、协作翻译、讨论区和博客等几大频道内容,为IT开发者提供了一个发现、使用、并交流开源技术的平台。
  • 官方手机版

  • 微信公众号

  • 商务合作