近来针对微服务框架开发,其中oauth2.0默认返回XML形式的token失效,不符合我们实际的开发需求,于是我参考网上一些博客重写了它,使其符合我们开发的需求。
核心主要涉及两个类:
import com.eqics.common.security.utils.ResultJsonUtil;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;@Componentpublic class AuthExceptionEntryPoint implements AuthenticationEntryPoint { @OverrIDe voID commence(httpServletRequest request,httpServletResponse response,AuthenticationException authException) throws servletexception { Map<String,Object> map = new HashMap<String,Object>(); Throwable cause = authException.getCause(); response.setStatus(httpStatus.OK.value()); response.setheader("Content-Type",application/Json;charset=UTF-8"); try { if (cause instanceof InvalIDTokenException) { response.getWriter().write(ResultJsonUtil.build( 222222,token失效 )); } } catch (IOException e) { e.printstacktrace(); } }}
ResourceServerConfig.java类中补充如下(找到主要方法):
@OverrIDe configure(ResourceServerSecurityConfigurer resources) { resources.tokenServices(tokenServices()); resources.authenticationEntryPoint(new AuthExceptionEntryPoint());}
还有一个工具类ResultJsonUtil.java,内容如下:
import java.util.List;import java.util.Map;class ResultJsonUtil<T> { private int code; statusCode; private String msg; T data; static final int DEFAulT_STATUS_CODE = 0; /** * construction * * @param code 请求状态码 * @param statusCode 信息状态码 * @param msg 信息 * @param data 数据 */ public ResultJsonUtil(int code, statusCode,String msg,T data) { this.code = code; this.statusCode = statusCode; this.msg = msg; this.data = data; } static String build(new ResultJsonUtil<>(code,statusCode,msg,1)">""return resultJsonUtil.getResultJson(); } code,String msg) { ResultJsonUtil.build(code,ResultJsonUtil.DEFAulT_STATUS_CODE,msg); } new ResultJsonUtil<>(code,data); JsONObject.parSEObject(JsON.toJsONString(data)); ResultJsonUtil<JsONObject> resultJsonUtil = JsONArray.parseArray(JsON.toJsONString(data)); String getResultJson() { JsONObject JsonObject = JsONObject(); JsonObject.put(codethis.code); JsonObject.put(msg.msg); JsON.toJsONString(JsonObject,SerializerFeature.disableCircularReferenceDetect); }}
本文主要参考了这篇文章:
Spring Cloud:Security OAuth2 自定义异常响应
以上是内存溢出为你收集整理的springboot+oauth2.0异常重写处理(针对token失效)全部内容,希望文章能够帮你解决springboot+oauth2.0异常重写处理(针对token失效)所遇到的程序开发问题。
如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)