SpringBoot使用JWT实现api接口身份认证

为什么使用JWT?
JWT实际上就是一个字符串,它由三部分组成,头部、载荷与签名。JWT不仅可用于认证,还可用于信息交换。善用JWT有助于减少服务器请求数据库的次数。本文主要介绍使用JWT进行接口身份认证。

一.导入jwt依赖

        <!-- jwt -->
        <dependency>
            <groupId>io.jsonwebtoken</groupId>
            <artifactId>jjwt</artifactId>
            <version>0.9.1</version>
        </dependency>

二.JwtHelper
这是jwt帮助类,用于创建token、验证token、根据token获取用户信息

import com.alibaba.fastjson.JSONException;
import com.example.springbootmybatis.commons.tools.StringUtil;
import com.example.springbootmybatis.vo.CurrentUser;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
 /**
 * @author liucheng
 * @since 2020/01/15
 * JwtHelper
 */
@Component
public class JwtHelper {

    @Value("${jwtSecret}")
    private String SECRET;

    @Value("${jwtExpire}")
    private Long EXPIRATION_TIME;

    private final String TOKEN_PREFIX = "Bearer";
    
     //创建token
    public JwtTokenResult generateToken(LoginUserModel customClaims) throws JSONException {
        Map<String, Object> claims = new HashMap<String, Object>();
        claims.put("userName", customClaims.getUserName());
        claims.put("userId", customClaims.getUserId());
        claims.put("normalPermissions", customClaims.getNormalPermissions());
        claims.put("permissions", customClaims.getPermissions());
        claims.put("realName", customClaims.getRealName());
        claims.put("role", customClaims.getRole());
        Calendar c = Calendar.getInstance();
        c.setTime(new Date());
        c.add(Calendar.SECOND, EXPIRATION_TIME.intValue());
        Date d = c.getTime();
        String jwt = Jwts.builder()
                .setClaims(claims)
                .setExpiration(d)
                .signWith(SignatureAlgorithm.HS512, SECRET)
                .compact();
        JwtTokenResult json = new JwtTokenResult();
        json.setAccess_token(TOKEN_PREFIX + " " + jwt);
        json.setExpire_time(new SimpleDateFormat("yyyy-MM-dd HH:ss:mm").format(d));
        json.setToken_type(TOKEN_PREFIX);
        json.setLoginUser(customClaims);
        return json;
    }

    //验证token
    public Boolean validateTokenAndGetClaims(String token) {
        try {
            if (StringUtil.isEmpty(token)) {
                return false;
            }
            Map<String, Object> body = Jwts.parser()
                    .setSigningKey(SECRET)
                    .parseClaimsJws(token.replace(TOKEN_PREFIX, ""))
                    .getBody();
            return true;
        } catch (Exception e) {
            return false;
        }
    }

    //根据token获取用户信息
    public CurrentUser getJwtTokenResult(String token) {
        try {
            if (StringUtil.isEmpty(token)) {
                return null;
            }
            Map<String, Object> body = Jwts.parser()
                    .setSigningKey(SECRET)
                    .parseClaimsJws(token.replace(TOKEN_PREFIX, ""))
                    .getBody();
            CurrentUser currentUser=new CurrentUser();
            currentUser.setId(body.get("userId").toString());
            currentUser.setUsername(body.get("userName").toString());
            currentUser.setPermissions(StringUtil.toString(body.get("permissions")));
            currentUser.setRole(StringUtil.toString(body.get("role")));
            return currentUser;
        } catch (Exception e) {
            return null;
        }
    }  
}

三.JwtTokenResult
登录成功生成jwt返回给前端的model,LoginUserModel是用户信息model,我这里携带是为了避免前端解析token。

@Setter
@Getter
@ApiModel(value="jwt返回的实体")
public class JwtTokenResult {
    @ApiModelProperty(value="access_token")
    private String access_token;

    @ApiModelProperty(value="刷新token")
    private String refresh_token;

    @ApiModelProperty(value="过期时间")
    private String expire_time;

    @ApiModelProperty(value="token_type")
    private String token_type;

    @ApiModelProperty(value="登录用户信息")
    private LoginUserModel loginUser;
}

四.LoginUserModel
用户信息model

@Setter
@Getter
@ApiModel(value = "LoginUserModel")
public class LoginUserModel {
    private String UserId;
    private String UserName;
    private String RealName;
    private String Permissions;
    private String NormalPermissions;
    private String Role;

    public LoginUserModel() {

    }

    public LoginUserModel(String userId, String userName, String realName, String permissions, String normalPermissions,String role) {
        UserId = userId;
        UserName = userName;
        RealName = realName;
        Permissions = permissions;
        NormalPermissions = normalPermissions;
        Role = role;
    }
}```

五.application.yml配置

jwtSecret: A0B1C2D3E4F5G6H7I8J9KALBMCNDOEPFQ0R1S2T3U4V5W6X7Y8Z9
jwtExpire: 30

六.登录接口生成jwt(部分代码)
这里需要注意,将refreshToken存入redis 设置15天过期

 LoginUserModel loginUserModel = new LoginUserModel(
                    userdto.getId(), userdto.getUserName(), userdto.getRealName(), StringUtils.join(permissions, ";"), "", StringUtils.join(roles, ";")
            );
            //生成jwt Token
            var jwtTokenResult = jwtHelper.generateToken(loginUserModel);
            String refresh_token = UUID.randomUUID().toString();
            jwtTokenResult.setRefresh_token(refresh_token);
            //将refreshToken存入redis 设置15天过期
            redisHelper.writeString(refresh_token, JsonUtil.Object2String(loginUserModel), 60 * 60 * 24 * 15);

七.刷新token
设置的token有效期为30min,前端拿到token后需要定时刷新token(在token失效临界点刷新)。
根据refreshToken获取新的token,首先验证在redis中能否找到refreshToken,找不到则证明登录已过期,找到后则生成新的token。

    @UncheckToken
    @ApiOperation(value = "刷新token")
    @RequestMapping(value = "/refreshToken", method = {RequestMethod.GET})
    public JsonResult refreshToken(String refreshToken) {
        if (StringUtil.isEmpty(refreshToken))
            return new JsonResult(HttpStatus.BAD_REQUEST, "refreshToken不能为空", null);
        var claims = redisHelper.readValue(refreshToken, LoginUserModel.class);
        LoginUserModel loginUserModel = new LoginUserModel();
        loginUserModel = (LoginUserModel) dataTransfer.getObjectFromObject(loginUserModel, claims);
        if (loginUserModel == null)
            return new JsonResult(HttpStatus.FORBIDDEN, "登录已过期", null);
        var jwtTokenResult = jwtHelper.generateToken(loginUserModel);
        jwtTokenResult.setRefresh_token(refreshToken);
        return new JsonResult(HttpStatus.OK, "成功", jwtTokenResult);
    }

八.拦截器中进行jwt身份认证

    //jwt用户身份认证
    private void interceptorHandler(HttpServletRequest request, Object handler) throws Exception {
        jwtAuthorization(request, handler);   
    }

    private void jwtAuthorization(HttpServletRequest request, Object handle) {
        if (!request.getMethod().toString().equals("OPTIONS")) {
            //排除UncheckToken注解的接口
            if (((HandlerMethod) handle).getMethod().isAnnotationPresent(UncheckToken.class)) {
                return;
            }
            String token = request.getHeader(Constants.HEADER_STRING);
            if (StringUtils.isEmpty(token)) {
                throw new ServiceException(ExceptionCode.AUTH_ERROR.getCode(), "token缺失");
            }
            //检验token是否有效
            var flag = jwtHelper.validateTokenAndGetClaims(token);
            if (flag == false) {
                throw new ServiceException(ExceptionCode.AUTH_ERROR.getCode(), "未授权或授权已过期");
            }
        }
    }

你可能感兴趣的:(springboot,jwt,token认证)