12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667 |
- package com.fdkankan.sale.controller;
- import com.auth0.jwt.JWT;
- import com.auth0.jwt.interfaces.DecodedJWT;
- import com.baomidou.mybatisplus.core.toolkit.StringUtils;
- import com.fdkankan.sale.common.ResultCode;
- import com.fdkankan.sale.entity.SysUser;
- import com.fdkankan.sale.exception.BusinessException;
- import com.fdkankan.sale.service.ISysUserService;
- import org.springframework.beans.factory.annotation.Autowired;
- import org.springframework.stereotype.Component;
- import javax.servlet.http.HttpServletRequest;
- import javax.servlet.http.HttpServletResponse;
- import static com.baomidou.mybatisplus.core.toolkit.IdWorker.getId;
- @Component
- public class BaseController {
- @Autowired
- protected HttpServletRequest request;
- @Autowired
- ISysUserService sysUserService;
- @Autowired
- protected HttpServletResponse response;
- protected String getToken(){
- return request.getHeader("token");
- }
- protected Long getUserId(){
- String token = request.getHeader("token");
- if(StringUtils.isBlank(token)){
- return null;
- }
- try {
- DecodedJWT jwt = JWT.decode(token);
- Long userId = jwt.getClaim("userId").asLong();
- return sysUserService.getByManageId(userId).getId();
- }catch (Exception e){
- return null;
- }
- }
- protected SysUser getUser(){
- String token = request.getHeader("token");
- if(StringUtils.isBlank(token)){
- return null;
- }
- try {
- DecodedJWT jwt = JWT.decode(token);
- Long userId = jwt.getClaim("userId").asLong();
- return sysUserService.getByManageId(userId);
- }catch (Exception e){
- return null;
- }
- }
- public static void main(String[] args) {
- String token = "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJsb2dpblR5cGUiOiJsb2dpbiIsImxvZ2luSWQiOjEsImRldmljZSI6ImRlZmF1bHQtZGV2aWNlIiwiZWZmIjotMSwicm5TdHIiOiJ5TUJRdkdDQzk2OURZNDJOaGVueEhuYzI4VUp4Q3MxYSIsInVzZXJJZCI6MSwiaXNBZG1pbiI6MSwidXNlck5hbWUiOiJzdXBlci1hZG1pbiIsIm5pY2tOYW1lIjoi6LaF57qn566h55CG5ZGYIn0.hnLrJoVWLwkWIwWdlUoBoWn2-ETepyI9l5AiLx3ji8M";
- DecodedJWT jwt = JWT.decode(token);
- Long userId = jwt.getClaim("userId").asLong();
- System.out.println(userId);
- }
- }
|