package com.example.jz.auth; import cn.hutool.json.JSONUtil; import com.example.jz.modle.R; import com.example.jz.modle.entity.SecurityUser; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.security.authentication.AuthenticationManager; import org.springframework.security.authentication.UsernamePasswordAuthenticationToken; import org.springframework.security.core.Authentication; import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter; import org.springframework.security.web.util.matcher.AntPathRequestMatcher; import javax.servlet.FilterChain; import javax.servlet.ServletException; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.IOException; import java.io.PrintWriter; import java.util.ArrayList; /** * @author 安瑾然 * @data 2022/7/18 - 10:57 AM * @description */ public class TokenLoginFilter extends UsernamePasswordAuthenticationFilter { private TokenJwtManager tokenJwtManager; private AuthenticationManager authenticationManager; public TokenLoginFilter(TokenJwtManager tokenJwtManager, AuthenticationManager authenticationManager) { this.tokenJwtManager = tokenJwtManager; this.authenticationManager = authenticationManager; this.setPostOnly(false); // 关闭登录只允许 post // 设置登陆路径,并且post请求 this.setRequiresAuthenticationRequestMatcher(new AntPathRequestMatcher("/login", "POST")); } // 1、获取登录页传递来的账户和密码信息 @Override public Authentication attemptAuthentication(HttpServletRequest request, HttpServletResponse response) { String username = request.getParameter("username"); String password = request.getParameter("password"); // 登录接口 /login 调用请求时触发 // UsernamePasswordAuthenticationToken 封装登录时传递来的数据信息 // 交给 AuthenticationManager 进行登录认证校验 return authenticationManager.authenticate(new UsernamePasswordAuthenticationToken(username, password, new ArrayList<>())); } // 2、认证成功调用 @Autowired protected void successfulAuthentication(HttpServletRequest request, HttpServletResponse response, FilterChain chain, Authentication authResult) throws IOException, ServletException { // 认证成功之后,获取认证后的用户基本信息 SecurityUser securityUser = (SecurityUser) authResult.getPrincipal(); // 根据用户名生成对应的token String token = tokenJwtManager.createToken(securityUser.getUsername()); // token信息存于redis、数据库、缓存等 // 设置返回消息类型 response.setHeader("Content-type", "text/html;charset=UTF-8"); response.setCharacterEncoding("utf-8"); response.setContentType("application/json;charset=UTF-8"); // 返回给请求端 PrintWriter writer = response.getWriter(); writer.write(JSONUtil.toJsonStr(R.ok(token, "登录成功"))); writer.flush(); writer.close(); } }