Shiro之前后端分离时获取请求头Authorization中的token

package com.boku.www.controller;

import org.apache.shiro.web.servlet.ShiroHttpServletRequest;
import org.apache.shiro.web.session.mgt.DefaultWebSessionManager;
import org.apache.shiro.web.util.WebUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import java.io.Serializable;

/**

  • 〈一句话功能简述〉

  • 〈获取token〉

  • @author dell

  • @create 2018/11/15

  • @since 1.0.0
    */

    @RestController
    @CrossOrigin//解决跨域问题
    public class CustomDefaultWebSessionManager extends DefaultWebSessionManager {

    /**

    • 获取session id
    • 前后端分离将从请求头中获取sesssionid
      */
      @RequestMapping(value = “/getSessionId”,method= RequestMethod.POST)
      @ResponseBody
      @Override
      protected Serializable getSessionId(ServletRequest request, ServletResponse response) {
      // 从请求头中获取token
      String token = WebUtils.toHttp(request).getHeader(“Authorization”);
      // 判断是否有值
      if (token != null && token.length()>0) {
      // 设置当前session状态
      request.setAttribute(ShiroHttpServletRequest.REFERENCED_SESSION_ID_SOURCE, “url”);
      request.setAttribute(ShiroHttpServletRequest.REFERENCED_SESSION_ID, token);
      request.setAttribute(ShiroHttpServletRequest.REFERENCED_SESSION_ID_IS_VALID, Boolean.TRUE);
      return token;
      }
      // 若header获取不到token则尝试从cookie中获取
      return super.getSessionId(request, response);
      }
      }

你可能感兴趣的:(token)