一、前言
之前在团队里边做的项目的基于 session 的登录拦截,属于后端全栈式的开发的模式:
全栈式使用 SpringBoot + SpringSecurity 做登录认证
而公司这边都是前后端分离鲜明的,前端不要接触过多的业务逻辑,都由后端解决,基本思路是这样的:
服务端通过 JSON字符串,告诉前端用户有没有登录、认证,前端根据这些提示跳转对应的登录页、认证页等。
二、代码
代码已经放在github 上了:https://github.com/larger5/SpringBoot_SpringSecurity.git
温馨提示:这些代码都是通用的~~
下面给个示例,该自上述的之前的代码
1.AjaxResponseBody 给前端JSON的格式
返回给前端的数据格式
package com.cun.security3.bean;
import java.io.Serializable;
public class AjaxResponseBody implements Serializable{
private String status;
private String msg;
private Object result;
private String jwtToken;
public String getStatus() {
return status;
}
public void setStatus(String status) {
this.status = status;
}
public String getMsg() {
return msg;
}
public void setMsg(String msg) {
this.msg = msg;
}
public Object getResult() {
return result;
}
public void setResult(Object result) {
this.result = result;
}
public String getJwtToken() {
return jwtToken;
}
public void setJwtToken(String jwtToken) {
this.jwtToken = jwtToken;
}
}
2.AjaxAuthenticationEntryPoint 未登录
用户没有登录时返回给前端的数据
package com.cun.security3.config;
import com.alibaba.fastjson.JSON;
import com.cun.security3.bean.AjaxResponseBody;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.AuthenticationEntryPoint;
import org.springframework.stereotype.Component;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
@Component
public class AjaxAuthenticationEntryPoint implements AuthenticationEntryPoint {
@Override
public void commence(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, AuthenticationException e) throws IOException, ServletException {
AjaxResponseBody responseBody = new AjaxResponseBody();
responseBody.setStatus("000");
responseBody.setMsg("Need Authorities!");
httpServletResponse.getWriter().write(JSON.toJSONString(responseBody));
}
}
3.AjaxAuthenticationFailureHandler 登录失败
用户登录失败时返回给前