package com.freedom.admin.config; import com.alibaba.fastjson.JSON; import com.freedom.admin.common.Result; import com.freedom.admin.utils.JwtUtils; import lombok.extern.slf4j.Slf4j; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.security.core.Authentication; import org.springframework.security.core.userdetails.UserDetails; import org.springframework.security.web.authentication.AuthenticationSuccessHandler; import org.springframework.stereotype.Component; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.IOException; /** * @author zhangjiaxun * @date 2021/1/5 17:40 * @description 对安全验证成功的请求进行响应处理 */ @Component @Slf4j public class MyAuthenticationSuccessHandler implements AuthenticationSuccessHandler { @Autowired private JwtUtils jwtUtils; @Override public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException { UserDetails userDetails = (UserDetails)authentication.getPrincipal(); // 生成token String token = jwtUtils.generateToken(userDetails.getUsername()); Result result = Result.ok().message("登录成功").token(token); // 修改编码格式 response.setCharacterEncoding("utf-8"); response.setContentType("application/json"); // 输出结果 response.getWriter().write(JSON.toJSONString(result)); } }