当前位置:   article > 正文

使用jwt方式的接口访问_jwt接口调用

jwt接口调用

要使用jwt必须有相应jar包

maven项目加入依赖

  1. <dependency>
  2. <groupId>com.auth0</groupId>
  3. <artifactId>java-jwt</artifactId>
  4. <version>3.4.0</version>
  5. </dependency>

普通web项目  将

java-jwt-3.4.0.jar

导入即可

说一下jwt的作用。可以使服务端和客户端之间的信息传递是无状态的。

进入正题:

1.准备好注解类

  1. import java.lang.annotation.ElementType;
  2. import java.lang.annotation.Retention;
  3. import java.lang.annotation.RetentionPolicy;
  4. import java.lang.annotation.Target;
  5. /**
  6. * 免验证注解
  7. * @author 少时诵诗书
  8. *
  9. */
  10. @Target({ElementType.METHOD, ElementType.TYPE})
  11. @Retention(RetentionPolicy.RUNTIME)
  12. public @interface PassToken {
  13. boolean required() default true;
  14. }

这个注解是在登录和注册等不需要验证token的时候在接口方法加的

  1. import java.lang.annotation.ElementType;
  2. import java.lang.annotation.Retention;
  3. import java.lang.annotation.RetentionPolicy;
  4. import java.lang.annotation.Target;
  5. /**
  6. * token验证
  7. * @author 少时诵诗书
  8. *
  9. */
  10. @Target({ElementType.METHOD, ElementType.TYPE})
  11. @Retention(RetentionPolicy.RUNTIME)
  12. public @interface UserLoginToken {
  13. boolean required() default true;
  14. }

这个注解是需要验证token信息

注解解析:从上面我们新建的两个类上我们可以看到主要的等学习到的就四点

第一:如何创建一个注解

第二:在我们自定义注解上新增@Target注解(注解解释:这个注解标注我们定义的注解是可以作用在类上还是方法上还是属性上面)

第三:在我们自定义注解上新增@Retention注解(注解解释:作用是定义被它所注解的注解保留多久,一共有三种策略,SOURCE 被编译器忽略,CLASS  注解将会被保留在Class文件中,但在运行时并不会被VM保留。这是默认行为,所有没有用Retention注解的注解,都会采用这种策略。RUNTIME  保留至运行时。所以我们可以通过反射去获取注解信息。

第四:boolean required() default true;  默认required() 属性为true

 

2.准备拦截器验证token

在spring-mvc.xml里面配置

  1. <mvc:interceptors>
  2. <mvc:interceptor>
  3. <mvc:mapping path="${adminPath}/**" />
  4. <mvc:exclude-mapping path="${adminPath}/"/>
  5. <mvc:exclude-mapping path="${adminPath}/login"/>
  6. <mvc:exclude-mapping path="${adminPath}/sys/menu/tree"/>
  7. <mvc:exclude-mapping path="${adminPath}/sys/menu/treeData"/>
  8. <mvc:exclude-mapping path="${adminPath}/oa/oaNotify/self/count"/>
  9. <bean class="com.xxx.modules.sys.interceptor.LogInterceptor" />
  10. </mvc:interceptor>
  11. <!-- 接口token验证 -->
  12. <mvc:interceptor>
  13. <mvc:mapping path="${frontPath}/**" />
  14. <bean class="com.xxx.modules.sys.interceptor.TokenIntercetor" />
  15. </mvc:interceptor>
  16. <!-- 手机视图拦截器 -->
  17. <mvc:interceptor>
  18. <mvc:mapping path="/**" />
  19. <bean class="com.xxx.modules.sys.interceptor.MobileInterceptor" />
  20. </mvc:interceptor>
  21. </mvc:interceptors>

拦截器类

  1. import java.lang.reflect.Method;
  2. import javax.servlet.http.HttpServletRequest;
  3. import javax.servlet.http.HttpServletResponse;
  4. import org.springframework.beans.factory.annotation.Autowired;
  5. import org.springframework.web.method.HandlerMethod;
  6. import org.springframework.web.servlet.HandlerInterceptor;
  7. import org.springframework.web.servlet.ModelAndView;
  8. import com.auth0.jwt.JWT;
  9. import com.auth0.jwt.JWTVerifier;
  10. import com.auth0.jwt.algorithms.Algorithm;
  11. import com.auth0.jwt.exceptions.JWTDecodeException;
  12. import com.auth0.jwt.exceptions.JWTVerificationException;
  13. import com.jeeplus.modules.sys.annotation.PassToken;
  14. import com.jeeplus.modules.sys.annotation.UserLoginToken;
  15. import com.jeeplus.modules.sys.service.TokenService;
  16. public class TokenIntercetor implements HandlerInterceptor{
  17. @Autowired
  18. private TokenService tokenService;
  19. @Override
  20. public void afterCompletion(HttpServletRequest arg0, HttpServletResponse arg1, Object arg2, Exception arg3)
  21. throws Exception {
  22. // TODO Auto-generated method stub
  23. }
  24. @Override
  25. public void postHandle(HttpServletRequest arg0, HttpServletResponse arg1, Object arg2, ModelAndView arg3)
  26. throws Exception {
  27. // TODO Auto-generated method stub
  28. }
  29. @Override
  30. public boolean preHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object object) throws Exception {
  31. //取出token
  32. String token=httpServletRequest.getHeader("token");
  33. System.out.println(token);
  34. //如果不是映射方法直接返回
  35. if(!(object instanceof HandlerMethod)){
  36. return true;
  37. }
  38. HandlerMethod handlermethod=(HandlerMethod)object;
  39. Method method=handlermethod.getMethod();
  40. //如果方法注解了passtoken直接跳过
  41. if(method.isAnnotationPresent(PassToken.class)){
  42. PassToken passToken=method.getAnnotation(PassToken.class);
  43. if(passToken.required()){
  44. return true;
  45. }
  46. }
  47. //如果注解了userLoginToken需要验证
  48. if(method.isAnnotationPresent(UserLoginToken.class)){
  49. UserLoginToken userLoginToken=method.getAnnotation(UserLoginToken.class);
  50. //验证
  51. if(userLoginToken.required()){
  52. if(token==null){
  53. throw new RuntimeException("无token信息,请重新登录");
  54. }
  55. //获取token 信息中userid
  56. String userid;
  57. try {
  58. userid=JWT.decode(token).getAudience().get(0);
  59. } catch (JWTDecodeException e) {
  60. throw new RuntimeException("401");
  61. }
  62. //查询用户是否存在
  63. if(!userid.equals("123")){//测试用123代替
  64. throw new RuntimeException("没有该用户");
  65. }
  66. //验证密码是否正确
  67. JWTVerifier jwtVerifier=JWT.require(Algorithm.HMAC256("456")).build();
  68. try {
  69. jwtVerifier.verify(token);
  70. } catch (JWTVerificationException e) {
  71. throw new RuntimeException("401");
  72. }
  73. return true;
  74. }
  75. }
  76. return false;
  77. }
  78. }

3.准备一个生成token的工具类或者service

  1. import org.springframework.stereotype.Service;
  2. import com.auth0.jwt.JWT;
  3. import com.auth0.jwt.algorithms.Algorithm;
  4. /**
  5. * 生成token的业务层
  6. * @author 少时诵诗书
  7. *
  8. */
  9. @Service
  10. public class TokenService {
  11. public String getToken(String userid,String password){
  12. String token="";
  13. token=JWT.create().withAudience(userid).sign(Algorithm.HMAC256(password));
  14. System.out.println(token);
  15. return token;
  16. }
  17. }

5.测试

准备一个登录接口和获取用户信息的接口

  1. import java.util.HashMap;
  2. import org.springframework.beans.factory.annotation.Autowired;
  3. import org.springframework.stereotype.Controller;
  4. import org.springframework.web.bind.annotation.RequestMapping;
  5. import org.springframework.web.bind.annotation.ResponseBody;
  6. import com.jeeplus.common.web.BaseController;
  7. import com.jeeplus.modules.sys.annotation.PassToken;
  8. import com.jeeplus.modules.sys.annotation.UserLoginToken;
  9. import com.jeeplus.modules.sys.service.TokenService;
  10. @Controller
  11. @RequestMapping("${frontPath}")
  12. public class TestController extends BaseController{
  13. @Autowired
  14. private TokenService tokenService;
  15. /**
  16. * 登录
  17. * @return
  18. */
  19. @RequestMapping("login")
  20. @ResponseBody
  21. @PassToken
  22. public HashMap<String, Object> login(){
  23. HashMap<String, Object> m=new HashMap<String, Object>();
  24. String token="";
  25. token=tokenService.getToken("123", "456");
  26. m.put("status", 200);
  27. m.put("token", token);
  28. return m;
  29. }
  30. @RequestMapping("getUserInfo")
  31. @ResponseBody
  32. @UserLoginToken
  33. public String getUserInfo(){
  34. return "用户信息以获取";
  35. }
  36. }

用postman测试、

登录并获取token

测试请求不加token的访问

服务器抛出异常

加上token的访问

可以了。

以上就是使用jwt方式的接口访问

 

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/一键难忘520/article/detail/840747
推荐阅读
相关标签
  

闽ICP备14008679号