pom.xml
<dependency>
<groupId>com.auth0</groupId>
<artifactId>java-jwt</artifactId>
<version>3.4.0</version>
</dependency>
注解:PassToken.java
package com.ak1ak1.yycollege.config;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
@Target({ElementType.METHOD, ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
public @interface PassToken {
boolean required() default true;
}
注解:UserLoginToken.java
package com.ak1ak1.yycollege.config;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
@Target({ElementType.METHOD,ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
public @interface UserLoginToken {
boolean required() default true;
}
鉴别中心:AuthenticationInterceptor .java
package com.ak1ak1.yycollege.config.filter;
import com.ak1ak1.yycollege.config.PassToken;
import com.ak1ak1.yycollege.config.UserLoginToken;
import com.ak1ak1.yycollege.pojo.User;
import com.ak1ak1.yycollege.service.UserService;
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 org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.lang.reflect.Method;
/*
* 拦截器
* */
public class AuthenticationInterceptor implements HandlerInterceptor {
@Autowired
private UserService userService;
@Override
public boolean preHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object object) throws Exception {
String token = httpServletRequest.getHeader("token");
//判断是请求方法,还是请求静态资源
if(!(object instanceof HandlerMethod)){
return true;
}
//判断方法上面是否有PassToken注解
HandlerMethod handlerMethod = (HandlerMethod)object;
Method method = handlerMethod.getMethod();
if(method.isAnnotationPresent(PassToken.class)){
PassToken passToken = method.getAnnotation(PassToken.class);
if(passToken.required()){
return true;
}
}
//判断方法上面是否有UserLoginToken注解
if(method.isAnnotationPresent(UserLoginToken.class)){
UserLoginToken userLoginToken = method.getDeclaredAnnotation(UserLoginToken.class);
if(userLoginToken.required()){
//执行认证
if(token==null){
throw new RuntimeException("无token,请重新登录!");
}
String userId;
try {
userId = JWT.decode(token).getAudience().get(0);
}catch (JWTDecodeException e){
throw new RuntimeException("401");
}
User user = userService.findById(userId);//查看用户是否存在
if(user==null){
throw new RuntimeException("用户不存在,请重新登录");
}
//验证token正确性
JWTVerifier jwtVerifier =JWT.require(Algorithm.HMAC256(user.getPassword())).build();
try {
jwtVerifier.verify(token);
}catch (JWTVerificationException e){
throw new RuntimeException("401");
}
return true;
}
}
return true;
}
}
InterceptorConfig.java 拦截所有请求进入拦截器
package com.ak1ak1.yycollege.config;
import com.ak1ak1.yycollege.config.filter.AuthenticationInterceptor;
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("/**");
}
@Bean
public AuthenticationInterceptor authenticationInterceptor() {
return new AuthenticationInterceptor();
}
}
User.java
package com.ak1ak1.yycollege.pojo;
import lombok.Data;
@Data
public class User {
private String userId;
private String password;
}
TokenService.java
package com.ak1ak1.yycollege.service;
import com.ak1ak1.yycollege.pojo.User;
public interface TokenService {
public String getToken(String userId, String password);
}
TokenServiceImpl.java
package com.ak1ak1.yycollege.service.impl;
import com.ak1ak1.yycollege.pojo.User;
import com.ak1ak1.yycollege.service.TokenService;
import com.auth0.jwt.JWT;
import com.auth0.jwt.algorithms.Algorithm;
import org.springframework.stereotype.Service;
import java.io.Serializable;
@Service
public class TokenServiceImpl implements TokenService, Serializable {
@Override
public String getToken(String userId, String password) {
String token = "";
token = JWT.create().withAudience(userId)
.sign(Algorithm.HMAC256(userId));
return token;
}
}
UserService.java
package com.ak1ak1.yycollege.service;
import com.ak1ak1.yycollege.pojo.User;
public interface UserService {
User findById(String userId);
}
UserServiceImpl.java
package com.ak1ak1.yycollege.service.impl;
import com.ak1ak1.yycollege.pojo.User;
import com.ak1ak1.yycollege.service.UserService;
import org.springframework.stereotype.Service;
@Service
public class UserServiceImpl implements UserService {
@Override
public User findById(String userId) {
//实际情况时jpa去数据库拿,测试写死的
User user = new User();
user.setUserId("123456");
user.setPassword("123456");
return user;
}
}
LoginController.java
package com.ak1ak1.yycollege.controller;
import com.ak1ak1.yycollege.config.PassToken;
import com.ak1ak1.yycollege.config.UserLoginToken;
import com.ak1ak1.yycollege.pojo.User;
import com.ak1ak1.yycollege.service.TokenService;
import com.alibaba.fastjson.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;
import javax.validation.Valid;
@RestController
public class LoginController {
@Autowired
private TokenService tokenService;
@GetMapping("/login")
@PassToken
public Object login(String userId, String password){
JSONObject jsonObject = new JSONObject();
String token = tokenService.getToken(userId, password);
jsonObject.put("token", token);
return jsonObject;
}
@GetMapping("/getMessage")
@UserLoginToken
public String getMessage(){
return "你已通过验证!!";
}
}