OAuth2登录接口返回自定义参数,并对异常翻译捕获

自定义通用返回类

import lombok.Data;

/**
 * 通用返回类
 *
 * @author 向振华
 * @date 2020/11/10 10:43
 */
@Data
public class DataResult<T> {

    /**
     * 状态码(0:成功,1:失败)
     */
    private int code;

    private String message;

    private T data;

    private DataResult(int code, String message, T data) {
        this.code = code;
        this.message = message;
        this.data = data;
    }

    public static <T> DataResult<T> success(T data) {
        return new DataResult<>(0, "success", data);
    }

    public static DataResult<Object> fail(String message) {
        return new DataResult<>(1, message, null);
    }
}

自定义登录Controller层(实际是对TokenEndpoint包装了一层Controller)


import com.xzh.sso.common.DataResult;
import com.xzh.sso.exception.CustomWebResponseExceptionTranslator;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.security.oauth2.common.exceptions.OAuth2Exception;
import org.springframework.security.oauth2.provider.endpoint.CheckTokenEndpoint;
import org.springframework.security.oauth2.provider.endpoint.TokenEndpoint;
import org.springframework.security.oauth2.provider.error.WebResponseExceptionTranslator;
import org.springframework.web.HttpRequestMethodNotSupportedException;
import org.springframework.web.bind.annotation.*;

import java.security.Principal;
import java.util.Map;

/**
 * OAuth2认证
 *
 * @author 向振华
 * @date 2020/11/13 16:11
 */
@RestController
@RequestMapping("/oauth")
public class OAuth2Controller {

    private final WebResponseExceptionTranslator<OAuth2Exception> exceptionTranslator = new CustomWebResponseExceptionTranslator();

    @Autowired
    private TokenEndpoint tokenEndpoint;

    @Autowired
    private CheckTokenEndpoint checkTokenEndpoint;

    @GetMapping("/token")
    public DataResult<Object> getAccessToken(Principal principal, @RequestParam Map<String, String> parameters) throws HttpRequestMethodNotSupportedException {
        return DataResult.success(tokenEndpoint.getAccessToken(principal, parameters).getBody());
    }

    @PostMapping("/token")
    public DataResult<Object> postAccessToken(Principal principal, @RequestParam Map<String, String> parameters) throws HttpRequestMethodNotSupportedException {
        return DataResult.success(tokenEndpoint.postAccessToken(principal, parameters).getBody());
    }

    @GetMapping("/check_token")
    public DataResult<Object> checkToken(@RequestParam("token") String value) {
        return DataResult.success(checkTokenEndpoint.checkToken(value));
    }

    //这里是异常翻译,如果这里不设置,则需要在全局异常处处理
    @ExceptionHandler({Exception.class})
    public ResponseEntity<OAuth2Exception> handleException(Exception e) throws Exception {
        return this.exceptionTranslator.translate(e);
    }
}

异常类和异常翻译类,在没有自定义登录控制层时,异常翻译是在AuthorizationServerConfig中使用

import lombok.Data;

/**
 * OAuth2认证异常
 *
 * @author 向振华
 * @date 2020/11/10 10:43
 */
@Data
public class AuthException extends RuntimeException {

    private int code;

    private String msg;

    public AuthException(String msg) {
        super(msg);
        this.code = 1;
        this.msg = msg;
    }

    public AuthException(int code, String msg) {
        super(msg);
        this.code = code;
        this.msg = msg;
    }
}
import com.xzh.sso.common.DataResult;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.ResponseEntity;
import org.springframework.security.authentication.InternalAuthenticationServiceException;
import org.springframework.security.oauth2.common.exceptions.InvalidGrantException;
import org.springframework.security.oauth2.common.exceptions.InvalidTokenException;
import org.springframework.security.oauth2.common.exceptions.OAuth2Exception;
import org.springframework.security.oauth2.common.exceptions.UnsupportedGrantTypeException;
import org.springframework.security.oauth2.provider.error.WebResponseExceptionTranslator;

/**
 * oauth2 自定义异常处理
 *
 * @author 向振华
 * @date 2020/11/10 10:43
 */
@Slf4j
public class CustomWebResponseExceptionTranslator implements WebResponseExceptionTranslator<OAuth2Exception> {

    @Override
    public ResponseEntity translate(Exception e) {
        log.warn("登录失败: ", e);
        String message;
        if (e instanceof AuthException || e.getCause() instanceof AuthException) {
            message = e.getMessage();
        } else if (e instanceof InternalAuthenticationServiceException) {
            message = "身份验证失败";
        } else if (e instanceof InvalidGrantException) {
            message = "用户名或密码错误";
        } else if (e instanceof InvalidTokenException) {
            message = "Token无效或过期";
        } else if (e instanceof UnsupportedGrantTypeException) {
            message = "不支持的授予类型";
        } else {
            message = "登录失败";
        }
        return ResponseEntity.ok(DataResult.fail(message));
    }
}

 

  • 1
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值