特别注意:以下内容如果有疑问,可先学习: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<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 (Objects.isNull(cause)) {
R<Object> r = R.failed("认证失败,请传递token");
response.getWriter().write(JSONObject.toJSONString(r));
return;
}
if(cause instanceof InvalidTokenException) {
R<Object> r = R.failed("认证失败,token无效或已过期");
response.getWriter().write(JSONObject.toJSONString(r));
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
修改ResourceServiceConfig.java类,如下:
![](https://i-blog.csdnimg.cn/blog_migrate/2ad01f3d254e62b56632694cc83fd7b7.png)
访问接口:
![](https://i-blog.csdnimg.cn/blog_migrate/2f872a2a967b548fc086f4fe6bc3d36d.png)
ok,集成完毕......................