2:然后我讲一下需求:前端给后端传入一个form-data类型数据,然后数据库中现在已经有了一条管理员用户(看下面第二个图)com.auth0 java-jwt 3.10.3 cn.hutool hutool-all 5.7.20
.withClaim("username",user.getLoginName()) //存放数据
.withClaim("password",user.getPassword())
这里的user.getxxxxxx根据自己去调整
package com.example.check.util;
import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.exceptions.JWTCreationException;
import com.auth0.jwt.exceptions.JWTDecodeException;
import com.auth0.jwt.exceptions.JWTVerificationException;
import com.auth0.jwt.interfaces.Claim;
import com.auth0.jwt.interfaces.DecodedJWT;
import com.example.check.entity.AdminLogin;
import java.util.Date;
public class TokenUtil {
private static final long EXPIRE_TIME= 60*1000;//token到期时间60s
private static final String TOKEN_SECRET="l122adasw532df"; //密钥盐
public static String sign(AdminLogin user,Date expires){
String token=null;
try {
token = JWT.create()
.withIssuer("auth0")//发行人
.withClaim("username",user.getLoginName()) //存放数据
.withClaim("password",user.getPassword())
.withExpiresAt(expires)//过期时间
.sign(Algorithm.HMAC256(TOKEN_SECRET));
} catch (IllegalArgumentException|JWTCreationException je) {
}
return token;
}
public static Boolean verify(String token){
try {
JWTVerifier jwtVerifier=JWT.require(Algorithm.HMAC256(TOKEN_SECRET)).withIssuer("auth0").build();//创建token验证器
DecodedJWT decodedJWT=jwtVerifier.verify(token);
System.out.println("认证通过:");
System.out.println("username: " + TokenUtil.getUsername(token));
System.out.println("过期时间: " + decodedJWT.getExpiresAt());
} catch (IllegalArgumentException |JWTVerificationException e) {
//抛出错误即为验证不通过
return false;
}
return true;
}
public static String getUsername(String token)
{
try{
DecodedJWT jwt=JWT.decode(token);
return jwt.getClaim("username").asString();
}catch (JWTDecodeException e)
{
return null;
}
}
}
跨域:
package com.example.check.config;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
@Configuration
public class WebMvcConfig implements WebMvcConfigurer {
@Override
public void addCorsMappings(CorsRegistry registry) {
registry.addMapping("/**")
.allowedHeaders("Content-Type","X-Requested-With","accept,Origin","Access-Control-Request-Method","Access-Control-Request-Headers","token")
.allowedMethods("*")
.allowedOriginPatterns("*")
.allowCredentials(true);
}
}
然后我们打开前端界面:点击登录后就可以在后台看到已经传过去的参数:
结束!


