Shiro 拓展Session写入Http请求头

前言

Shiro是一个业界常用的java安全框,它默认的管理session的方式,是在客户端请求登录成功后,写入到cookie里面存储起来。

笔者在维护一个前后端不分离的老系统,遇到这样的一个需求,在保留老系统原有的登录功能情况下,拓展PDA终端的登录方式,支持自定义请求头token来登录。

那么着手拓展吧。

代码

  1. 拓展默认的DefaultSessionManager
/**
 * 自定义session管理
 * @author rocky
 */
@Slf4j
public class CustomerSessionManager extends DefaultSessionManager implements WebSessionManager {
   

    private Cookie sessionIdCookie;
    private boolean sessionIdCookieEnabled;
    private boolean sessionIdUrlRewritingEnabled;

    /** 请求头标识 */
    private final String AUTH_TOKEN = "auth-token";

    public CustomerSessionManager() {
   
        Cookie cookie = new SimpleCookie("JSESSIONID");
        cookie.setHttpOnly(true);
        this.sessionIdCookie = cookie;
        this.sessionIdCookieEnabled = true;
        this.sessionIdUrlRewritingEnabled = true;
    }

    public Cookie getSessionIdCookie() {
   
        return this.sessionIdCookie;
    }

    public void setSessionIdCookie(Cookie sessionIdCookie) {
   
        this.sessionIdCookie = sessionIdCookie;
    }

    public boolean isSessionIdCookieEnabled() {
   
        return this.sessionIdCookieEnabled;
    }

    public void setSessionIdCookieEnabled(boolean sessionIdCookieEnabled) {
   
        this.sessionIdCookieEnabled = sessionIdCookieEnabled;
    }

    public boolean isSessionIdUrlRewritingEnabled() {
   
        return this.sessionIdUrlRewritingEnabled;
    }

    public void setSessionIdUrlRewritingEnabled(boolean sessionIdUrlRewritingEnabled) {
   
        this.sessionIdUrlRewritingEnabled = sessionIdUrlRewritingEnabled;
    }

    private void storeSessionId(Serializable currentId, HttpServletRequest request, HttpServletResponse response) {
   
        if (currentId == null) {
   
            String msg = "sessionId cannot be null when persisting for subsequent requests.";
            throw new IllegalArgumentException(msg);
        } else {
   
            Cookie template = this.getSessionIdCookie();
            Cookie cookie = new SimpleCookie(template);
            String idString = currentId.toString();
            cookie.setValue(idString);
            cookie.saveTo(request, response);
            log.trace("Set session ID cookie for session with id {}", idString);
            // 设置请求头
            response.setHeader(this.AUTH_TOKEN, idString);
        }
    }

    private void removeSessionIdCookie(HttpServletRequest request, HttpServletResponse response) {
   
        this.getSessionIdCookie().removeFrom(request, response);
    }

    private String getSessionIdCookieValue(ServletRequest request, ServletResponse response) {
   
        if (!this.isSessionIdCookieEnabled()) {
   
            log.debug("Session ID cookie is disabled - session id will not be acquired from a request cookie.");
            return null;
        } else if (!(request instanceof HttpServletRequest)) {
   
            log.

你可能感兴趣的:(开发笔记,Java,http,servlet,java)