记录一下使用springboot集成jwt实现登录注册,以后有用到直接copy即可。
整体流程
依赖
<!--引入jwt--> <dependency> <groupid>com.auth0</groupid> <artifactid>java-jwt</artifactid> <version>3.4.0</version> </dependency> <!-- md5加密依赖 --> <dependency> <groupid>commons-codec</groupid> <artifactid>commons-codec</artifactid> </dependency>
工具类
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<string, object> 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登录注册内容请搜索代码网以前的文章或继续浏览下面的相关文章希望大家以后多多支持代码网!
发表评论