package com.trade.client.security.handle;

import java.io.IOException;
import java.io.Serializable;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.AuthenticationEntryPoint;
import org.springframework.stereotype.Component;

import com.alibaba.fastjson2.JSON;
import com.trade.common.constant.HttpStatus;
import com.trade.common.core.domain.ResponseResult;
import com.trade.common.utils.ServletUtils;
import com.trade.common.utils.StringUtils;

/**
 * @description: 认证失败处理类
 * @Author: wanglang
 * @Date: 2023/7/19 10:22
 * @Version: 1.0
 */
@Component
public class AuthenticationEntryPointImpl implements AuthenticationEntryPoint, Serializable {

    public void commence(HttpServletRequest request, HttpServletResponse response,
            AuthenticationException authException) throws IOException, ServletException {
        int code = HttpStatus.UNAUTHORIZED;
        String msg = StringUtils.format("请求访问：{}，认证失败，无法访问系统资源", request.getRequestURI());
        ServletUtils.renderString(response, JSON.toJSONString(ResponseResult.error(code, msg)));
    }
}
