IT俱乐部 Java Springboot集成JWT实现登录注册的示例代码

Springboot集成JWT实现登录注册的示例代码

记录一下使用Springboot集成JWT实现登录注册,以后有用到直接copy即可。

整体流程

依赖

com.auth0java-jwt3.4.0commons-codeccommons-codec

工具类

import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.exceptions.JWTVerificationException;
import com.auth0.jwt.interfaces.DecodedJWT;
import com.huishi.entity.MapUser;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.codec.digest.DigestUtils;
import javax.servlet.http.HttpServletRequest;
import java.util.Date;

@Slf4j
public class SecurityUtils {

    public static String md5(String src) {
        return DigestUtils.md5Hex(src);
    }

    //密钥盐
    private static final String salt = "1a2b3c4d";


    /**
     * 密码加密
     * @param inputPass
     * @return
     */
    public static String inputPassToFormPass(String inputPass) {
        String str = "" + salt.charAt(0) + salt.charAt(2) + inputPass + salt.charAt(5) + salt.charAt(4);
        System.out.println(str);
        return md5(str);
    }

    public static String formPassToDBPass(String formPass, String salt) {
        String str = "" + salt.charAt(0) + salt.charAt(2) + formPass + salt.charAt(5) + salt.charAt(4);
        return md5(str);
    }

    public static String inputPassToDbPass(String inputPass, String saltDB) {
        String formPass = inputPassToFormPass(inputPass);
        String dbPass = formPassToDBPass(formPass, saltDB);
        return dbPass;
    }

    /**
     * 生成token
     *
     * @param mapUser
     * @param tokenExpireTime
     * @param tokenSecret
     * @return
     */
    public static String genToken(MapUser mapUser, Integer tokenExpireTime, String tokenSecret) {
        Date expireAt = new Date(System.currentTimeMillis() + tokenExpireTime * 60 * 1000);

        return JWT.create()
                //发行人
                .withIssuer("auth0")
                //存放数据
                .withClaim("userId", mapUser.getId())
                .withClaim("username", mapUser.getUserName())
                .withClaim("password", mapUser.getPassword())
                //过期时间
                .withExpiresAt(expireAt)
                .sign(Algorithm.HMAC256(tokenSecret));
    }

    /**
     * 对token进行验证
     *
     * @param token
     * @param tokenSecret
     * @return
     */
    public static Boolean verifyToken(String token, String tokenSecret) {
        DecodedJWT decodedJWT = null;
        try {
            //创建token验证器
            JWTVerifier jwtVerifier = JWT.require(Algorithm.HMAC256(tokenSecret)).withIssuer("auth0").build();
            decodedJWT = jwtVerifier.verify(token);
            log.info("token认证通过,用户:{},过期时间:{}", getUserName(token), decodedJWT.getExpiresAt());
        } catch (IllegalArgumentException | JWTVerificationException e) {
            //抛出错误即为验证不通过
            log.error("token认证失败,用户:{}", getUserName(token));
            return false;
        }
        return true;
    }

    public static String getUserName(String token) {
        return JWT.decode(token).getClaims().get("username").asString();
    }

    public static Long getUserId(String token) {
        if (token == null) return null;
        return JWT.decode(token).getClaims().get("userId").asLong();
    }

    public static String getToken(HttpServletRequest request) {
        String authHeader = request.getHeader("Authorization");
        if (authHeader != null && authHeader.startsWith("Bearer ")) {
            return authHeader.replace("Bearer ", "");
        }
        return null;
    }

}

注册和登录

@Override
public ResponseResult register(MapUser mapUser) {
    mapUser.setPassword(SecurityUtils.inputPassToFormPass(mapUser.getPassword()));
    return ResponseResult.success(mapUserMapper.insert(mapUser));
}

@Override
public ResponseResult login(MapUser mapUser) {

    String password = SecurityUtils.inputPassToFormPass(mapUser.getPassword());
    MapUser user = mapUserMapper.findByName(mapUser.getUserName());

    if (user == null) throw new ServiceException("用户不存在");
    if (!password.equals(user.getPassword())) throw new ServiceException("密码错误");


    String token = SecurityUtils.genToken(user, tokenExpireTime, tokenSecret);
    MapConfig mapConfig = mapConfigMapper.getByUserId(user.getId());
    Map result = new HashMap();
    result.put("token", token);
    result.put("mapConfig", mapConfig.conventEntity());
    return ResponseResult.success(result);
}

拦截器

import com.alibaba.fastjson.JSONObject;
import com.huishi.util.SecurityUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * token拦截器
 */
@Component
@Slf4j
public class TokenInterceptor implements HandlerInterceptor {

    @Value("${token.header}")
    private String tokenHeader;

    @Value("${token.prefix}")
    private String tokenPrefix;

    @Value("${token.secret}")
    private String tokenSecret;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String authHeader = request.getHeader(tokenHeader);
        if (authHeader != null && authHeader.startsWith(tokenPrefix)) {
            String token = authHeader.replace(tokenPrefix + " ", "");
            if (SecurityUtils.verifyToken(token, tokenSecret)) return true;
        }
        String requestURI = request.getRequestURI();
        JSONObject json = new JSONObject();
        json.put("msg", "请求:" + requestURI + ",认证失败,无法访问资源");
        json.put("code", "401");
        response.setContentType("application/json;charset=UTF-8");
        response.getWriter().append(json.toString());
        return false;
    }

}

配置拦截器

import com.huishi.server.interceptor.TokenInterceptor;
import org.springframework.beans.factory.annotation.Autowired;
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 WebConfig implements WebMvcConfigurer {
    @Autowired
    private TokenInterceptor tokenInterceptor;

    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        registry.addInterceptor(tokenInterceptor)
                .addPathPatterns("/**")
                .excludePathPatterns("/map/user/register", "/map/user/login", "/map/plane/getNewest", "/map/plane/tracePlaneInfo",
                        "/map/config/get/**",

                        "/swagger-ui.html",
                        "/webjars/**",
                        "/swagger-resources/**");
    }
}

到此这篇关于Springboot集成JWT实现登录注册的示例代码的文章就介绍到这了,更多相关Springboot JWT登录注册内容请搜索IT俱乐部以前的文章或继续浏览下面的相关文章希望大家以后多多支持IT俱乐部! 

本文收集自网络,不代表IT俱乐部立场,转载请注明出处。https://www.2it.club/code/java/12418.html
上一篇
下一篇
联系我们

联系我们

在线咨询: QQ交谈

邮箱: 1120393934@qq.com

工作时间:周一至周五,9:00-17:30,节假日休息

关注微信
微信扫一扫关注我们

微信扫一扫关注我们

返回顶部