在前后端分离项目中,通常是通过json格式数据传递信息,但是SpingSecurity中默认获取登录账号密码方式为通过表单提交的key/value形式过去,具体官方源码处理方式如下:
public Authentication attemptAuthentication(HttpServletRequest request,
HttpServletResponse response) throws AuthenticationException {
if (postOnly && !request.getMethod().equals("POST")) {
throw new AuthenticationServiceException(
"Authentication method not supported: " + request.getMethod());
}
String username = obtainUsername(request);
String password = obtainPassword(request);
if (username == null) {
username = "";
}
if (password == null) {
password = "";
}
username = username.trim();
UsernamePasswordAuthenticationToken authRequest = new UsernamePasswordAuthenticationToken(
username, password);
// Allow subclasses to set the "details" property
setDetails(request, authRequest);
return this.getAuthenticationManager().authenticate(authRequest);
}
但是如果要处理json数据进行登录,我们可以重写UsernamePasswordAuthenticationFilter类中attemptAuthentication方法实现
创建自定义过滤器LoginAuthenticationFilter
public class LoginAuthenticationFilter 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());
}
//如果是application/json类型,做如下处理
if(request.getContentType().equals(MediaType.APPLICATION_JSON_UTF8_VALUE)||request.getContentType().equals(MediaType.APPLICATION_JSON_VALUE)){
//以json形式处理数据
String username = null;
String password = null;
try {
//将请求中的数据转为map
Map<String,String> map = new ObjectMapper().readValue(request.getInputStream(), Map.class);
username = map.get("username");
password = map.get("password");
} catch (IOException e) {
e.printStackTrace();
}
if (username == null) {
username = "";
}
if (password == null) {
password = "";
}
username = username.trim();
UsernamePasswordAuthenticationToken authRequest = new UsernamePasswordAuthenticationToken(
username, password);
// Allow subclasses to set the "details" property
setDetails(request, authRequest);
return this.getAuthenticationManager().authenticate(authRequest);
}
//否则使用官方默认处理方式
return super.attemptAuthentication(request, response);
}
}
编写SpringSecurity配置类
@Configuration
public class SecurityConfig extends WebSecurityConfigurerAdapter {
@Bean
LoginAuthenticationFilter loginAuthenticationFilter() throws Exception {
LoginAuthenticationFilter filter = new LoginAuthenticationFilter();
filter.setFilterProcessesUrl("/doLogin");
filter.setAuthenticationSuccessHandler(new AuthenticationSuccessHandler() {
@Override
public void onAuthenticationSuccess(HttpServletRequest req, HttpServletResponse resp, Authentication authentication) throws IOException, ServletException {
resp.setContentType("application/json;charset=utf-8");
PrintWriter writer = resp.getWriter();
Hr hr = (Hr) authentication.getPrincipal();
hr.setPassword(null);
RespResult result = RespResult.ok("登录成功", hr);
String msg = new ObjectMapper().writeValueAsString(result);
writer.write(msg);
writer.flush();
writer.close();
}
});
filter.setAuthenticationFailureHandler(new AuthenticationFailureHandler() {
@Override
public void onAuthenticationFailure(HttpServletRequest req, HttpServletResponse resp, AuthenticationException e) throws IOException, ServletException {
resp.setContentType("application/json;charset=utf-8");
PrintWriter writer = resp.getWriter();
RespResult result = RespResult.error("登录失败");;
if (e instanceof BadCredentialsException) {
result.setMsg("用户名或密码错误,请检查");
}else if(e instanceof LockedException){
result.setMsg("账户被锁定,请联系管理员");
}else if(e instanceof CredentialsExpiredException){
result.setMsg("密码已过期,请联系管理员");
}else if(e instanceof AccountExpiredException){
result.setMsg("账户已过期,请联系管理员");
}else if(e instanceof DisabledException){
result.setMsg("账户被禁用,请联系管理员");
}
String msg = new ObjectMapper().writeValueAsString(result);
writer.write(msg);
writer.flush();
writer.close();
}
});
filter.setAuthenticationManager(authenticationManagerBean());
return filter;
}
@Override
protected void configure(HttpSecurity http) throws Exception {
http.authorizeRequests().anyRequest().authenticated()
.and()
.formLogin()
.loginPage("/login")
.permitAll()
.and()
.logout()
.logoutSuccessHandler(new LogoutSuccessHandler() {
@Override
public void onLogoutSuccess(HttpServletRequest req, HttpServletResponse resp, Authentication authentication) throws IOException, ServletException {
resp.setContentType("application/json;charset=utf-8");
PrintWriter writer = resp.getWriter();
RespResult result = RespResult.ok("注销退出成功");
String msg = new ObjectMapper().writeValueAsString(result);
writer.write(msg);
writer.flush();
writer.close();
}
})
.permitAll()
.and()
.csrf().disable();
http.addFilterAt(loginAuthenticationFilter(),UsernamePasswordAuthenticationFilter.class);
}
}