前言:还记得上一章中WebSecurityConfigurerAdapter 配置注释掉的
//认证成功的返回处理下章再讲
// .successHandler()
//认证失败的返回处理
// .failureHandler()
在项目开发中一般是前后分离的,前后端统一达成一定规格的请求返回的数据规格。
成功认证处理:
package com.wyb.seurity;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.http.HttpStatus;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.HashMap;
/**
* 成功返回处理
*/
public class WebAuthenticationSuccessHandler implements AuthenticationSuccessHandler {
@Override
public void onAuthenticationSuccess(HttpServletRequest httpServletRequest,
HttpServletResponse httpServletResponse,
Authentication authentication) throws IOException, ServletException {
httpServletResponse.setContentType("application/json;charset=UTF-8");
HashMap<String, Object> hashMap = new HashMap<>();
hashMap.put("msg","登录成功");
hashMap.put("authentication",authentication);
System.out.println(authentication.getDetails());
//spring提供的状态码
httpServletResponse.setStatus(HttpStatus.OK.value());
String s = new ObjectMapper().writeValueAsString(hashMap);
httpServletResponse.getWriter().println(s);
}
}
认证成功的返回:
上期密码配置
spring:
application:
name: wyb-admin-security-resourceapi
security:
user:
name: user
password: 123456
roles: admin,super
失败的返回处理:
package com.wyb.seurity;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.http.HttpStatus;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.authentication.AuthenticationFailureHandler;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.HashMap;
/**
* 认证失败
*/
public class WebAuthenticationFailureHandler implements AuthenticationFailureHandler {
@Override
public void onAuthenticationFailure(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, AuthenticationException e) throws IOException, ServletException {
httpServletResponse.setContentType("application/json;charset=UTF-8");
HashMap<String, Object> hashMap = new HashMap<>();
hashMap.put("msg","登录失败");
hashMap.put("e",e.getMessage());
//spring提供的状态码
httpServletResponse.setStatus(HttpStatus.INTERNAL_SERVER_ERROR.value());
String s = new ObjectMapper().writeValueAsString(hashMap);
httpServletResponse.getWriter().println(s);
}
}