• JwtAuthenticationTokenFilter 实现shiro 利用 token 信息完成令牌登录


    package net.filter.jwt;
    
    import java.io.IOException;
    
    import javax.servlet.FilterChain;
    import javax.servlet.ServletException;
    import javax.servlet.http.HttpServletRequest;
    import javax.servlet.http.HttpServletResponse;
    
    import org.apache.commons.lang.StringUtils;
    import org.apache.shiro.subject.PrincipalCollection;
    import org.apache.shiro.subject.SimplePrincipalCollection;
    import org.apache.shiro.util.ThreadContext;
    import org.apache.shiro.web.subject.WebSubject;
    import org.apache.shiro.web.subject.WebSubject.Builder;
    import org.slf4j.Logger;
    import org.slf4j.LoggerFactory;
    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.web.filter.OncePerRequestFilter;
    
    import net.entity.User;
    import net.service.UserService;
    
    /**
     * 过滤请求头部信息,如果有,就自动登录 http://blog.csdn.net/qi923701/article/details/75007813
     * 
     * @author wutao
     * @date 2017年11月11日 下午3:09:51
     */
    public class JwtAuthenticationTokenFilter extends OncePerRequestFilter {
    
        private static final Logger logger = LoggerFactory.getLogger(JwtAuthenticationTokenFilter.class);
    
        @Autowired
        private UserService userService;
    
        @Override
        protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain chain)
                throws ServletException, IOException {
            String tokenHeader = request.getHeader(JwtTokenUtil.AUTH_TOKEN);
            if (StringUtils.isNotBlank(tokenHeader)) {
                Long userId = JwtTokenUtil.getUserIdFromToken(tokenHeader);
                if (userId != null) {
                    if (logger.isDebugEnabled()) {
                        logger.debug("getUserIdFromToken userId {}", userId);
                    }
    
                    User auser = userService.find(userId);
                    if (auser != null) {
                        PrincipalCollection principals = new SimplePrincipalCollection(auser, "authorizingRealm");
                        Builder builder = new WebSubject.Builder(request, response);
                        builder.principals(principals);
                        builder.authenticated(true);
                        WebSubject subject = builder.buildWebSubject();
                        ThreadContext.bind(subject);
                    }
    
                }
            }
            chain.doFilter(request, response);
        }
    
    }
  • 相关阅读:
    Flask(7)- request 对象
    2021暑假训练赛1 基于Codeforce#479(div3)
    AtCoder ARC 115 E
    C++11 noexcept 关键字用法学习
    AtCoder ABC 049 C
    【算法学习笔记】块状数据结构:分块思想
    「Codeforces 1131D」Gourmet Choice
    AtCoder Beginner Contest 172 (C题前缀和 + 二分,D题筛因子,E题容斥定理)
    第 45 届国际大学生程序设计竞赛(ICPC)亚洲区域赛(沈阳)补题记录
    泛型动态数组
  • 原文地址:https://www.cnblogs.com/nanahome/p/7894880.html
Copyright © 2020-2023  润新知