通过jwt token替换session实现用户登录与鉴权

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/shenzhen_zsw/article/details/89473049

通过jwt token替换session实现用户登录与鉴权

AuthInterceptor

/**
 * 
 */
package com.mooc.house.api.inteceptor;

import java.util.Map;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.util.WebUtils;

import com.google.common.base.Joiner;
import com.mooc.house.api.common.CommonConstants;
import com.mooc.house.api.common.UserContext;
import com.mooc.house.api.dao.UserDao;
import com.mooc.house.api.model.User;
import com.netflix.hystrix.contrib.javanica.annotation.DefaultProperties;

/**
 *
 */
@Component
public class AuthInterceptor implements HandlerInterceptor {
  
  private static final String TOKEN_COOKIE = "token";
  
  
  @Autowired
  private UserDao userDao;


    /**
     * 从cookie中获取token;
     * 在根据token获取用户信息,并设置到UserContext中;
     * @param req
     * @param res
     * @param handler
     * @return
     * @throws Exception
     */
  @Override
  public boolean preHandle(HttpServletRequest req, HttpServletResponse res, Object handler) throws Exception {
    Map<String, String[]> map = req.getParameterMap();
    map.forEach((k,v) ->req.setAttribute(k, Joiner.on(",").join(v)));
    String requestURI = req.getRequestURI();
    if (requestURI.startsWith("/static") || requestURI.startsWith("/error")) {
      return true;
    }
    Cookie cookie = WebUtils.getCookie(req, TOKEN_COOKIE);
    if (cookie != null && StringUtils.isNoneBlank(cookie.getValue())) {
        User user = userDao.getUserByToken(cookie.getValue());
        if (user != null) {
          req.setAttribute(CommonConstants.LOGIN_USER_ATTRIBUTE, user);
          //req.setAttribute(CommonConstants.USER_ATTRIBUTE, user);
          UserContext.setUser(user);
        }
    }
    return true;
  }


    /**
     * 获取用户信息中的token并设置到cookie中
     * @param req
     * @param res
     * @param handler
     * @param modelAndView
     * @throws Exception
     */
  @Override
  public void postHandle(HttpServletRequest req, HttpServletResponse res, Object handler, ModelAndView modelAndView) throws Exception {
    String requestURI = req.getRequestURI();
    if (requestURI.startsWith("/static") || requestURI.startsWith("/error")) {
      return ;
    }
    User user = UserContext.getUser();
    if (user != null && StringUtils.isNoneBlank(user.getToken())) {
       String token = requestURI.startsWith("logout")? "" : user.getToken();
       Cookie cookie = new Cookie(TOKEN_COOKIE, token);
       cookie.setPath("/");
       cookie.setHttpOnly(false);
       res.addCookie(cookie);
    }
    
  }
  
  

  @Override
  public void afterCompletion(HttpServletRequest req, HttpServletResponse response, Object handler, Exception ex)
          throws Exception {
    UserContext.remove();
  }
}

说明:

     1)preHandle:从cookie中获取token,再根据token获取用户信息,并设置到UserContext中;

     2)postHandle:获取用户信息中的token并设置到cookie中;

AuthActionInterceptor 

/**
 * 
 */
package com.mooc.house.api.inteceptor;

import java.net.URLEncoder;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import com.mooc.house.api.common.UserContext;
import com.mooc.house.api.model.User;


@Component
public class AuthActionInterceptor implements HandlerInterceptor {
  

  @Override
  public boolean preHandle(HttpServletRequest req, HttpServletResponse res, Object handler) throws Exception {
    User user = UserContext.getUser();
    if (user == null) {
       String msg =  URLEncoder.encode("请先登录", "utf-8");
       StringBuffer sb = req.getRequestURL();
       String   target = URLEncoder.encode(sb.toString(), "utf-8");
       if ("GET".equalsIgnoreCase(req.getMethod())) {
         res.sendRedirect("/accounts/signin?errorMsg=" + msg + "&target=" + target);
       }else {
         res.sendRedirect("/accounts/signin?errorMsg=" + msg);
       }
       return false;
    }
    return true;
  }

  @Override
  public void postHandle(HttpServletRequest req, HttpServletResponse res, Object handler, ModelAndView modelAndView) throws Exception {
     
  }

  @Override
  public void afterCompletion(HttpServletRequest req, HttpServletResponse response, Object handler, Exception ex) throws Exception {
  }
}

说明:

    1)判断用户是否登录

WebMvcConf 

package com.mooc.house.api.inteceptor;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;

@Configuration
public class WebMvcConf extends WebMvcConfigurerAdapter {

  @Autowired
  private AuthInterceptor authInterceptor;
  
  @Autowired
  private AuthActionInterceptor authActionInterceptor;
  
  @Override
  public void addInterceptors(InterceptorRegistry registry) {
    registry.addInterceptor(authInterceptor).excludePathPatterns("/static").addPathPatterns("/**");
    registry
        .addInterceptor(authActionInterceptor)
         .addPathPatterns("/house/toAdd")
        .addPathPatterns("/accounts/profile").addPathPatterns("/accounts/profileSubmit")
        .addPathPatterns("/house/bookmarked").addPathPatterns("/house/del")
        .addPathPatterns("/house/ownlist").addPathPatterns("/house/add")
        .addPathPatterns("/house/toAdd").addPathPatterns("/agency/agentMsg")
        .addPathPatterns("/comment/leaveComment").addPathPatterns("/comment/leaveBlogComment");
    
    super.addInterceptors(registry);
  }
  
  @Override
  public void addCorsMappings(CorsRegistry registry) {
    registry.addMapping("/**")  // 拦截所有的url
        .allowedOrigins("*")    // 放行哪些原始域,比如"http://domain1.com,https://domain2.com"
        .allowCredentials(true) // 是否发送Cookie信息
        .allowedMethods("GET", "POST", "PUT", "DELETE") // 放行哪些原始域(请求方式)
        .allowedHeaders("*");   // 放行哪些原始域(头部信息)
    super.addCorsMappings(registry);
  }
  

}

说明:

    1)配置拦截器AuthInterceptor和AuthActionInterceptor;

    2)以及他们拦截所对应的路径;


==============================
QQ群:143522604
群里有相关资源
欢迎和大家一起学习、交流、提升!
==============================

猜你喜欢

转载自blog.csdn.net/shenzhen_zsw/article/details/89473049