MyAuthenticationEntryPoint.java 1.1 KB
Newer Older
1 2 3 4 5
package com.youlai.common.security.exception;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.youlai.common.result.Result;
import com.youlai.common.result.ResultCode;
6 7
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
8 9 10 11 12 13 14
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.AuthenticationEntryPoint;
import org.springframework.stereotype.Component;

import java.io.IOException;

/**
R
Ray Hao 已提交
15
 * 自定义 token 无效异常
16 17
 *
 * @author haoxr
18
 * @since 2022/11/13
19 20 21 22 23
 */
@Component
public class MyAuthenticationEntryPoint implements AuthenticationEntryPoint {
    @Override
    public void commence(HttpServletRequest request, HttpServletResponse response, AuthenticationException authException)
H
haoxr 已提交
24
            throws IOException {
25 26
        response.setContentType("application/json");
        ObjectMapper mapper = new ObjectMapper();
27 28
        response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
        mapper.writeValue(response.getOutputStream(), Result.failed(ResultCode.TOKEN_INVALID));
29 30
    }
}