zoukankan      html  css  js  c++  java
  • springboot+JWT

    1、生成JWT验证字符串

    /**
     * 生成token
     * @param admin Object
     * @return String
     */
    public String getToken(Admin admin){
       String token = "";
       //JWT.create()创建token withAudience保存在token中的信息   Algorithm.HMAC256()使用HS256生成token,密钥是用户密码
       token = JWT.create().withAudience(admin.getId()).sign(Algorithm.HMAC256(admin.getPassword()));
       return token;
    }

    2、设置接口验证

    /**
    * 给需要验证的接口添加注解 不添加默认不验证
    */
    @Target({ElementType.METHOD, ElementType.TYPE})
    @Retention(RetentionPolicy.RUNTIME)
    public @interface UserLoginToken {
       boolean required() default true;
    }

    3、获取请求token并验证

    package com.example.demo.unity;

    import com.auth0.jwt.JWT;
    import com.auth0.jwt.JWTVerifier;
    import com.auth0.jwt.algorithms.Algorithm;
    import com.auth0.jwt.exceptions.JWTDecodeException;
    import com.auth0.jwt.exceptions.JWTVerificationException;
    import com.example.demo.dao.Admin;
    import com.example.demo.mapper.AdminMapper;
    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.web.method.HandlerMethod;
    import org.springframework.web.servlet.HandlerInterceptor;
    import org.springframework.web.servlet.ModelAndView;

    import javax.servlet.http.HttpServletRequest;
    import javax.servlet.http.HttpServletResponse;
    import java.lang.reflect.Method;

    /**
    * 获取token并验证
    */
    public class AuthenticationInterceptor implements HandlerInterceptor {
       @Autowired
       AdminMapper adminMapper;

       @Override
       public boolean preHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object object) throws Exception {
           String token = httpServletRequest.getHeader("token");// 从 http 请求头中取出 token
           // 如果不是映射到方法直接通过
           if (!(object instanceof HandlerMethod)) {
               return true;
          }
           HandlerMethod handlerMethod = (HandlerMethod) object;
           Method method = handlerMethod.getMethod();
           //检查是否有passtoken注释,有则跳过认证
           if (method.isAnnotationPresent(PassToken.class)) {
               PassToken passToken = method.getAnnotation(PassToken.class);
               if (passToken.required()) {
                   return true;
              }
          }
           //检查有没有需要用户权限的注解
           if (method.isAnnotationPresent(UserLoginToken.class)) {
               UserLoginToken userLoginToken = method.getAnnotation(UserLoginToken.class);
               if (userLoginToken.required()) {
                   // 执行认证
                   if (token == null) {
                       throw new RuntimeException("无token,请重新登录");
                  }
                   // 获取 token 中的 user id
                   String userId;
                   try {
                       userId = JWT.decode(token).getAudience().get(0);
                  } catch (JWTDecodeException j) {
                       throw new RuntimeException("401");
                  }
                   Admin admin = adminMapper.getAdminById(userId);
                   if (admin == null) {
                       throw new RuntimeException("用户不存在,请重新登录");
                  }
                   // 验证 token
                   JWTVerifier jwtVerifier = JWT.require(Algorithm.HMAC256(admin.getPassword())).build();
                   try {
                       jwtVerifier.verify(token);
                  } catch (JWTVerificationException e) {
                       throw new RuntimeException("401");
                  }
                   return true;
              }
          }
           return true;
      }

       @Override
       public void postHandle(HttpServletRequest httpServletRequest,
                              HttpServletResponse httpServletResponse,
                              Object o, ModelAndView modelAndView) throws Exception {

      }

       @Override
       public void afterCompletion(HttpServletRequest httpServletRequest,
                                   HttpServletResponse httpServletResponse,
                                   Object o, Exception e) throws Exception {
      }
    }

    4、设置拦截器

    package com.example.demo.unity;

    import org.springframework.context.annotation.Bean;
    import org.springframework.context.annotation.Configuration;
    import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
    import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

    @Configuration
    public class InterceptorConfig implements WebMvcConfigurer {
       @Override
       public void addInterceptors(InterceptorRegistry registry) {
           registry.addInterceptor(authenticationInterceptor())
                  .addPathPatterns("/**");//拦截所有请求
      }
       
       //token验证
       @Bean
       public AuthenticationInterceptor authenticationInterceptor() {
           return new AuthenticationInterceptor();
      }
    }

    5、响应封装+jwt验证使用

    @UserLoginToken//开启验证
    @RequestMapping("")
    public ResponseEntity<Base> login(@RequestBody Map<String,String> person) {
       Base res = new Base(200,"登录成功");
       String name = person.get("name");
       String password = person.get("password");
       Admin admin = adminService.getAdminByName(name);
       if (admin != null){
           String adminPassword = admin.getPassword();
           if (password.equals(adminPassword)){
               Map<String ,String> map = new HashMap<>();
               map.put("name",admin.getName());
               map.put("admin_id",admin.getId());
               String token = res.getToken(admin);
               res.putData("token",token);
               res.putData("data",map);
          }else{
               res.setCode(500);
               res.setMsg("密码错误!");
          }
      }else{
           res.setCode(500);
           res.setMsg("用户不存在!");
      }
       return ResponseEntity.ok(res);
    }

     

  • 相关阅读:
    C#使用Xamarin开发可移植移动应用(5.进阶篇显示弹出窗口与通讯中心)附源码
    C#使用Xamarin开发可移植移动应用(4.进阶篇MVVM双向绑定和命令绑定)附源码
    C#使用Xamarin开发可移植移动应用(3.Xamarin.Views控件)附源码
    C#使用Xamarin开发可移植移动应用(2.Xamarin.Forms布局,本篇很长,注意)附源码
    C#使用Xamarin开发可移植移动应用(1.入门与Xamarin.Forms页面),附源码
    ASP.NET Core之跨平台的实时性能监控(2.健康检查)
    Android Studio 快捷键:重载与重写、try catch代码块、导包 快捷键
    新版本jQuery对动态添加元素绑定点击事件实例
    ssm框架中,mybatis的sql语句日志输出
    maven环境下的ssm框架上传excel 案例
  • 原文地址:https://www.cnblogs.com/ljkltt/p/14424246.html
Copyright © 2011-2022 走看看