懒羊羊
2023-08-30 1ac2bc1590406d9babec036e154d8d08f34a6aa1
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
package cn.stylefeng.guns.sys.core.auth.entrypoint;
 
import cn.stylefeng.guns.base.auth.exception.enums.AuthExceptionEnum;
import cn.stylefeng.roses.kernel.model.response.ErrorResponseData;
import com.alibaba.fastjson.JSON;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.AuthenticationEntryPoint;
import org.springframework.stereotype.Component;
 
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.Serializable;
 
/**
 * 这个端点用在用户访问受保护资源但是不提供任何token的情况下
 * <p>
 * 当前用户没有登录(没有token),访问了系统中的一些需要权限的接口,就会进入这个处理器
 *
 * @author fengshuonan
 * @Date 2019/7/20 17:57
 */
@Component
public class JwtAuthenticationEntryPoint implements AuthenticationEntryPoint, Serializable {
 
    private static final long serialVersionUID = -1L;
 
    @Override
    public void commence(HttpServletRequest request,
                         HttpServletResponse response,
                         AuthenticationException authException) throws IOException {
 
        // GET请求跳转到主页
        if ("get".equalsIgnoreCase(request.getMethod())
                && !request.getHeader("Accept").contains("application/json")) {
 
            response.sendRedirect(request.getContextPath() + "/global/sessionError");
 
        } else {
 
            // POST请求返回json
            response.setCharacterEncoding("utf-8");
            response.setContentType("application/json");
 
            ErrorResponseData errorResponseData = new ErrorResponseData(
                    AuthExceptionEnum.NO_PAGE_ERROR.getCode(), AuthExceptionEnum.NO_PAGE_ERROR.getMessage());
 
            response.getWriter().write(JSON.toJSONString(errorResponseData));
        }
    }
}