LoginUsernamePasswordAuthenticationFilter
處理login API驗證,驗證成功產生JWT,內建只會對/login POST Method API作驗證
驗證帳號密碼
@Override
public Authentication attemptAuthentication(HttpServletRequest request, HttpServletResponse response) throws AuthenticationException {
String account = request.getParameter("account");
String password = request.getParameter("password");
System.out.println("LoginUsernamePasswordAuthenticationFilter account: " + account + ", password: " + password);
try {
return authenticationManager.authenticate(new UsernamePasswordAuthenticationToken(account, password, new ArrayList<>()));
} catch (Exception e) {
throw new RuntimeException(e);
}
}
產生JWT
@Override
protected void successfulAuthentication(HttpServletRequest request, HttpServletResponse response, FilterChain chain, Authentication authResult) throws IOException, ServletException {
String token = Jwts.builder()
.setSubject(((User) authResult.getPrincipal()).getUsername())
.setExpiration(new Date(System.currentTimeMillis() + Config.EXPIRATION_TIME))
.signWith(SignatureAlgorithm.HS512, Config.SECRET.getBytes())
.compact();
response.addHeader(Config.HEADER, Config.TOKEN_PREFIX + token);
chain.doFilter(request, response);
}