spring boot集成shiro之前后端分離

前后端分離之后,接口跨域無(wú)法鑒權(quán),所以這里需要人工配置token,做法很簡(jiǎn)單
繼承DefaultWebSessionManager重寫getSessionId方法

package com.sansence.redwine.config;

import org.apache.shiro.web.servlet.ShiroHttpServletRequest;
import org.apache.shiro.web.session.mgt.DefaultWebSessionManager;
import org.apache.shiro.web.util.WebUtils;
import org.slf4j.LoggerFactory;
import org.springframework.util.StringUtils;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import java.io.Serializable;
 
/**
 * 自定義sessionId獲取
 */
public class MySessionManager extends DefaultWebSessionManager {
 
    private static final String AUTHORIZATION = "authorization";
 
    private static final String REFERENCED_SESSION_ID_SOURCE = "cookie";
 
    public MySessionManager() {
        super();
    }
 
    @Override
    protected Serializable getSessionId(ServletRequest request, ServletResponse response) {
        String id = WebUtils.toHttp(request).getHeader(AUTHORIZATION);
        //如果請(qǐng)求頭中有 Authorization 則其值為sessionId
        if (!StringUtils.isEmpty(id)) {
            request.setAttribute(ShiroHttpServletRequest.REFERENCED_SESSION_ID_SOURCE, REFERENCED_SESSION_ID_SOURCE);
            request.setAttribute(ShiroHttpServletRequest.REFERENCED_SESSION_ID, id);
            request.setAttribute(ShiroHttpServletRequest.REFERENCED_SESSION_ID_IS_VALID, Boolean.TRUE);
            return id;
        } else {
            //否則按默認(rèn)規(guī)則從cookie取sessionId
            return super.getSessionId(request, response);
        }
    }
}

然后再配置下

@Bean("sessionManager")
    public SessionManager sessionManager(){
        //將我們繼承后重寫的shiro session 注冊(cè)
        MySessionManager shiroSession = new MySessionManager();
        //如果后續(xù)考慮多tomcat部署應(yīng)用,可以使用shiro-redis開(kāi)源插件來(lái)做session 的控制,或者nginx 的負(fù)載均衡
        shiroSession.setSessionDAO(new EnterpriseCacheSessionDAO());
        //單位為毫秒,600000毫秒為1個(gè)小時(shí)
        shiroSession.setSessionValidationInterval(3600000*12);
        //3600000 milliseconds = 1 hour
        shiroSession.setGlobalSessionTimeout(3600000*12);
        //是否刪除無(wú)效的,默認(rèn)也是開(kāi)啟
        shiroSession.setDeleteInvalidSessions(true);
        return shiroSession;
    }

 /**
     * 注入權(quán)限管理
     * @return
     */
    @Bean
    public SecurityManager securityManager(@Qualifier("sessionManager")SessionManager sessionManager){
        DefaultWebSecurityManager securityManager=new DefaultWebSecurityManager();
        securityManager.setRealm(customRealm());
        securityManager.setSessionManager(sessionManager);
        return securityManager;
    }

參考文章:https://blog.csdn.net/wmy_0707/article/details/100118329

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書(shū)系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

推薦閱讀更多精彩內(nèi)容