SpringBoot integrates shiro to realize WeChat applet login

First of all, because the WeChat applet does not have a session mechanism, we can use the header to pass the token value to simulate login.

First of all, because shiro manages the session through SessionManager, we can control it by overriding the method in SessionManger.

The specific operation is as follows:

public class WeChatSessionManager extends DefaultWebSessionManager {
    
    @Override
    protected Serializable getSessionId(ServletRequest request, ServletResponse response) {
        String authToken = WebUtils.toHttp(request).getHeader(ShiroConst.HEADER_AUTH_TOKEN_NAME);
        if (StringUtils.isEmpty(authToken)) {
            return super.getSessionId(request, response);
        } else {
            request.setAttribute(ShiroHttpServletRequest.REFERENCED_SESSION_ID_SOURCE, ShiroConst.REFERENCED_SESSION_ID_SOURCE);
            request.setAttribute(ShiroHttpServletRequest.REFERENCED_SESSION_ID, authToken);
            request.setAttribute(ShiroHttpServletRequest.REFERENCED_SESSION_ID_IS_VALID, Boolean.TRUE);
            return authToken;
        }
    }
}

Then when you live in SessionManger in shiroConfig, instantiate our rewritten SessionManger.

The specific operation code is as follows:

/**
     * session管理
     *
     * @return WeChatSessionManager
     */
    @Bean(name = "sessionManager")
    public WeChatSessionManager getSessionManage() {
        WeChatSessionManager sessionManager = new WeChatSessionManager();
        sessionManager.setCacheManager(cacheManager());//Shiro的缓存管理
        sessionManager.setSessionIdCookieEnabled(Boolean.TRUE); //是否禁用会话id
        sessionManager.setSessionIdCookie(sessionIdCookie());
        sessionManager.setDeleteInvalidSessions(Boolean.TRUE);
        sessionManager.setGlobalSessionTimeout(ShiroConst.SHIRO_SESSION_SESSION_MAX_AGE);
        sessionManager.setSessionValidationSchedulerEnabled(Boolean.TRUE);
        sessionManager.setSessionValidationScheduler(executorServiceSessionValidationScheduler());
        sessionManager.setSessionIdUrlRewritingEnabled(Boolean.FALSE);
        return sessionManager;
    }

In this way, it can be directly injected into our ShiroConfig.

Guess you like

Origin blog.csdn.net/qq_38821574/article/details/109669092