UsernamePasswordAuthenticationFilter
负责处理登录逻辑,我们可以通过继承该方法,重写登录逻辑
public class LoginFilter extends UsernamePasswordAuthenticationFilter {
@Override
public Authentication attemptAuthentication(HttpServletRequest request, HttpServletResponse response) throws AuthenticationException {
if (!request.getMethod().equals("POST")) {
throw new AuthenticationServiceException("Authentication method not supported: " + request.getMethod());
}
String contentType = request.getContentType();
if (contentType.contains(MediaType.APPLICATION_JSON_VALUE)) {
Map<String, String> map;
try {
map = new ObjectMapper().readValue(request.getInputStream(), Map.class);
} catch (IOException e) {
throw new AuthenticationServiceException("系统异常,请稍后重试!");
}
String username = map.get(getUsernameParameter());
username = (username != null) ? username : "";
username = username.trim();
String password = map.get(getPasswordParameter());
password = (password != null) ? password : "";
UsernamePasswordAuthenticationToken authRequest = new UsernamePasswordAuthenticationToken(username, password);
setDetails(request, authRequest);
return getAuthenticationManager().authenticate(authRequest);
} else {
return super.attemptAuthentication(request, response);
}
}
}
- 在 WebSecurity 的配置类中添加如下代码
@Configuration
public class MySecurityConfig extends WebSecurityConfigurerAdapter {
@Override
protected void configure(HttpSecurity http) throws Exception {
http.authorizeRequests()
.anyRequest().authenticated()
.and()
.formLogin()
.permitAll()
.and()
.logout()
.permitAll()
.and()
.csrf().disable()
.addFilterAt(loginFilter(), UsernamePasswordAuthenticationFilter.class);
}
LoginFilter loginFilter() throws Exception {
LoginFilter filter = new LoginFilter();
filter.setAuthenticationSuccessHandler((request, response, authentication) -> {
User user = (User)authentication.getPrincipal();
Map<String, Object> map = new HashMap<>();
response.setContentType("application/json;charset=utf-8");
PrintWriter out = response.getWriter();
map.put("msg", "登录成功");
user.setPassword(null);
map.put("obj", user);
out.write(new ObjectMapper().writeValueAsString(map));
out.flush();
out.close();
});
filter.setAuthenticationFailureHandler((request, response, exception) -> {
Map<String, String> map = new HashMap<>();
response.setContentType("application/json;charset=utf-8");
PrintWriter out = response.getWriter();
if (exception instanceof LockedException) {
map.put("msg", "账户被锁定");
} else if (exception instanceof AccountExpiredException) {
map.put("msg", "账户已过期");
} else if (exception instanceof BadCredentialsException) {
map.put("msg", "用户或密码错误");
} else if (exception instanceof DisabledException) {
map.put("msg", "账户被禁用");
} else if (exception instanceof UsernameNotFoundException) {
map.put("msg", "该账户不存在");
} else {
map.put("msg", exception.getMessage());
}
out.write(new ObjectMapper().writeValueAsString(map));
out.flush();
out.close();
});
filter.setAuthenticationManager(authenticationManagerBean());
filter.setUsernameParameter("name");
filter.setPasswordParameter("passwd");
filter.setFilterProcessesUrl("/login");
return filter;
}
}