SpringSecurity +oauth2自定义异常(三)

特别注意:以下内容如果有疑问,可先学习:SpringSecurity +oauth2获取当前登录用户(二)

1 对token无效或不传递的处理,原始报错如下:

{
    "error": "unauthorized",
    "error_description": "Full authentication is required to access this resource"
}

对此,显然不满足开发需求,整改如下;

新建AuthExceptionEntryPoint.java类,实现AuthenticationEntryPoint类,代码如下:

package com.yty.system.oauth.config.exception;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.extension.api.R;
import org.springframework.http.HttpStatus;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.oauth2.common.exceptions.InvalidTokenException;
import org.springframework.security.web.AuthenticationEntryPoint;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.Objects;

/**
 * 无效 token 异常类重写
 */

@Component
public class AuthExceptionEntryPoint implements AuthenticationEntryPoint {

    @Override
    public void commence(HttpServletRequest request, HttpServletResponse response, AuthenticationException authException) throws IOException, ServletException {
        Map map = new HashMap();
        Throwable cause = authException.getCause();

        response.setStatus(HttpStatus.OK.value());
        response.setHeader("Content-Type", "application/json;charset=UTF-8");
        try {
            if (Objects.isNull(cause)) {
                R r = R.failed("认证失败,请传递token");
                response.getWriter().write(JSONObject.toJSONString(r));
                return;
            }
            if(cause instanceof InvalidTokenException) {
                R r = R.failed("认证失败,token无效或已过期");
                response.getWriter().write(JSONObject.toJSONString(r));
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
 
   

修改ResourceServiceConfig.java类,如下:

SpringSecurity +oauth2自定义异常(三)_第1张图片

访问接口:

SpringSecurity +oauth2自定义异常(三)_第2张图片

ok,集成完毕......................


你可能感兴趣的:(spring,java,服务器,servlet)