3

写在前面

  • 在前后端交互过程中,为了保证信息安全,我们往往需要加点用户验证。本文介绍了用springboot简单整合token。实现用户登录验证,若验证不成功,将同样返回json数据,并能很方便地在接口中获取到UserId。
  • springboot版本2.2.0。另外主要用到了jjwt,redis。阅读本文,你大概需要花费7-10分钟时间

整合token

1. 导入相关依赖

pom.xml文件中

<!--        jwt 加密解密工具类-->
        <dependency>
            <groupId>io.jsonwebtoken</groupId>
            <artifactId>jjwt</artifactId>
            <version>0.9.0</version>
        </dependency>
2. 登录拦截器AuthenticationInterceptor,java

注意此处用到的R是我自己写的返回给前端的类

package com.dbc.monitor.utils;


import com.alibaba.fastjson.JSONObject;
import com.dbc.monitor.entity.UserEntity;
import com.dbc.monitor.service.RedisService;
import com.dbc.monitor.service.UserService;
import io.jsonwebtoken.Claims;
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.io.IOException;
import java.io.PrintWriter;
import java.lang.reflect.Method;

//登录拦截器
public class AuthenticationInterceptor implements HandlerInterceptor {
    public final static String ACCESS_TOKEN = "token";

    @Autowired
    private UserService userService;

    @Autowired
    private RedisService redisService;

    // 在业务处理器处理请求之前被调用
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        // 如果不是映射到方法直接通过
        if (!(handler instanceof HandlerMethod)) {
            return true;
        }
        HandlerMethod handlerMethod = (HandlerMethod) handler;
        Method method = handlerMethod.getMethod();
        // 判断接口是否需要登录
        TokenIgnore methodAnnotation = method.getAnnotation(TokenIgnore.class);

        // 没有 @TokenIgnore 注解,需要认证
        if (methodAnnotation == null) {
            // 判断是否存在token信息,如果存在,则允许访问
            String accessToken = request.getHeader(ACCESS_TOKEN);
            if (null == accessToken) {
                response.setStatus(200);
                returnJson(response, JSONObject.toJSONString(R.tokenErr("没有参数"+ACCESS_TOKEN)));
                return false;
            } else {
                // 从Redis 中查看 token 是否过期
                boolean exit = redisService.exists(accessToken);
                if (!exit){
                    //不存在该用户
                    response.setStatus(200);
                    returnJson(response, JSONObject.toJSONString(R.tokenErr("token过期")));
                    return false;
                }
                Claims claims;
                try{
                    claims = TokenUtil.parseJWT(accessToken);
                } catch (Exception e){
                    response.setStatus(200);
                    returnJson(response, JSONObject.toJSONString(R.tokenErr("token过期")));
                    return false;
                }
                // 根据用户id查找用户方法
                UserEntity user = userService.getById(Integer.valueOf(claims.getId()));
                if (user == null) {
                    response.setStatus(200);
                    returnJson(response, JSONObject.toJSONString(R.tokenErr("没有此用户")));
                    return false;
                }

                return true;
            }
        } else {//不需要登录可请求
            return true;
        }
    }

    private void returnJson(HttpServletResponse response, String json) throws Exception{
        PrintWriter writer = null;
        response.setCharacterEncoding("UTF-8");
        response.setContentType("application/json");
        try {
            writer = response.getWriter();
            writer.print(json);

        } catch (IOException e) {
            throw  new Exception("response error");
        } finally {
            if (writer != null)
                writer.close();
        }
    }

    // 请求处理之后进行调用,但是在视图被渲染之前(Controller方法调用之后)
    @Override
    public void postHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, ModelAndView modelAndView) throws Exception {

    }

    // 在整个请求结束之后被调用,也就是在DispatcherServlet 渲染了对应的视图之后执行(主要是用于进行资源清理工作)
    @Override
    public void afterCompletion(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, Exception e) throws Exception {
    }
}
3.WebConfig.java 注册拦截
package com.dbc.monitor.config;

import com.dbc.monitor.utils.AuthenticationInterceptor;
import com.dbc.monitor.utils.R;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

@Configuration
public class WebConfig implements WebMvcConfigurer {

    //解决本地访问跨域问题
    @Override
    public void addCorsMappings(CorsRegistry registry) {
        registry.addMapping("/**")
                .allowedOrigins("http://localhost:8080")
                .allowedMethods("*")
                .allowedHeaders("*");
    }
    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        // addPathPatterns 用于添加拦截规则
        // excludePathPatterns 用户排除拦截
        registry.addInterceptor(authenticationInterceptor())
                .addPathPatterns("/*/*");
    }

    /**
     * 解决 拦截器中注入bean 失败情况出现
     * addArgumentResolvers方法中 添加
     *  argumentResolvers.add(currentUserMethodArgumentResolver());
     * @return
     */
    @Bean
    public HandlerInterceptor authenticationInterceptor() {
        return new AuthenticationInterceptor();
    }
}
4.TokenUtil.java实现生成/解析token
package com.dbc.usermanager.util;

import com.dbc.usermanager.service.RedisService;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.JwtBuilder;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import org.springframework.beans.factory.annotation.Autowired;

import javax.crypto.spec.SecretKeySpec;
import javax.xml.bind.DatatypeConverter;
import java.security.Key;
import java.util.Date;

public class TokenUtil {
    /**
     * 签名秘钥,可以换成 秘钥 注入
     */
    public static final String SECRET = "DaTiBao";//注意:本参数需要长一点,不然后面剪切的时候很可能长度为0,就会报错
    /**
     * 签发地
     */
    public static final String issuer  = "dtb.com";
    /**
     * 过期时间
     */
    public static final long ttlMillis = 3600*1000*60;

    /**
     * 生成token
     *
     * @param id 一般传入userName
     * @return
     */
    public static String createJwtToken(String id,String subject) {
        return createJwtToken(id, issuer, subject, ttlMillis);
    }
    public static String createJwtToken(String id) {
        return createJwtToken(id, issuer, "", ttlMillis);
    }

    /**
     * 生成Token
     *
     * @param id        编号
     * @param issuer    该JWT的签发者,是否使用是可选的
     * @param subject   该JWT所面向的用户,是否使用是可选的;
     * @param ttlMillis 签发时间 (有效时间,过期会报错)
     * @return token String
     */
    public static String createJwtToken(String id, String issuer, String subject, long ttlMillis) {

        // 签名算法 ,将对token进行签名
        SignatureAlgorithm signatureAlgorithm = SignatureAlgorithm.HS256;

        // 生成签发时间
        long nowMillis = System.currentTimeMillis();
        Date now = new Date(nowMillis);

        // 通过秘钥签名JWT
        byte[] apiKeySecretBytes = DatatypeConverter.parseBase64Binary(SECRET);
        String str=signatureAlgorithm.getJcaName();
        Key signingKey = new SecretKeySpec(apiKeySecretBytes, str);

        // 让我们设置JWT声明
        JwtBuilder builder = Jwts.builder().setId(id)
                .setIssuedAt(now)
                .setSubject(subject)
                .setIssuer(issuer)
                .signWith(signatureAlgorithm, signingKey);

        // if it has been specified, let's add the expiration
        if (ttlMillis >= 0) {
            //过期时间
            long expMillis = nowMillis + ttlMillis;
            Date exp = new Date(expMillis);
            builder.setExpiration(exp);
        }

        // 构建JWT并将其序列化为一个紧凑的url安全字符串
        return builder.compact();

    }

    /**
     * Token解析方法
     * @param jwt Token
     * @return
     */
    public static Claims parseJWT(String jwt) {
        // 如果这行代码不是签名的JWS(如预期),那么它将抛出异常
        Claims claims = Jwts.parser()
                .setSigningKey(DatatypeConverter.parseBase64Binary(SECRET))
                .parseClaimsJws(jwt).getBody();
        return claims;
    }
    /**
     * 获取userId
     * @return
     */
public static String getTokenUserId() {
        String token = getRequest().getHeader("token");// 从 http 请求头中取出 token
        Claims claims=TokenUtil.parseJWT(token);
        return claims.getId();
    }
    /**
     * 获取request
     *
     * @return
     */
    public static HttpServletRequest getRequest() {
        ServletRequestAttributes requestAttributes = (ServletRequestAttributes) RequestContextHolder
                .getRequestAttributes();
        return requestAttributes == null ? null : requestAttributes.getRequest();
    }


    public static void main(String[] args) {

        String token = TokenUtil.createJwtToken("2","ltz");

        System.out.println(TokenUtil.createJwtToken("2","ltz"));

        Claims claims = TokenUtil.parseJWT(token);

        System.out.println(claims);

    }
}
5.新增跳过登录验证的注解@TokenIgnore
package com.dbc.usermanager.util;

import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

//加入此注解,就不需要token验证
@Target({ElementType.METHOD, ElementType.TYPE})// 表明此注解可用在方法名上
@Retention(RetentionPolicy.RUNTIME)// 运行时有效
public @interface TokenIgnore {
    boolean required() default true;
}
6.测试
    @PostMapping(value = "test")
    @ApiOperation(value="生成token")
    @TokenIgnore
    @ApiImplicitParams(value = {@ApiImplicitParam(paramType = "header", dataType = "String", name = "token", value = "token标记", required = true)})
    public R test(@RequestBody JSONObject requestJson){
          Map<String,String> token=new HashMap<>();
          token.put("token",this.saveToken(String.valueOf(userEntity.getId())));
          return R.ok(token,"登录成功");
    }
    @GetMapping(value = "getToken")
    @ApiOperation("")
    public R getToken(){
        System.out.println(TokenUtil.getTokenUserId());
        return R.ok(null,"测试成功");
    }
    

public String saveToken(String id){
        String result="";
        try {
            String token= TokenUtil.createJwtToken(id,"monitor");
            redisService.set(token,id);
            result=token;
        }catch (Exception e){
            System.out.println(e.getMessage());
        }
        return result;
    }

最后

  • 实体类User.java等相关文件就不贴出来了,大家可以用自己写好的实体类去编写。
  • 很多步骤与思想都在代码中体现,代码中也加了很多注释,你可以根据自己的需求进行增删查改。
  • 参考链接:csdn,博客

邓奔成
6 声望4 粉丝