This article links to an article on: www.jianshu.com/p/5e1a07f5c…

Juejin. Cn/post / 684490…

Java’s JJWT implements JWT.

JJWT is a Java library that provides end-to-end JWT creation and validation. Always free and open source (Apache License, version 2.0), JJWT is easy to use and understand. It is designed as a smooth, architecture-centric interface that hides much of its complexity.

Let’s test the code and steps:

The creation of a token

(1) Create maven project and introduce dependencies

<dependency>
      <groupId>io.jsonwebtoken</groupId>
      <artifactId>jjwt</artifactId>
      <version>0.6.0</version>
</dependency>
Copy the code

(2) Create class CreateJwtTest for generating tokens

public class CreateJwtTest {
    public static void main(String[] args) {
        JwtBuilder builder= Jwts.builder().setId("888")
        .setSubject("White")
        .setIssuedAt(new Date())
      .signWith(SignatureAlgorithm.HS256,"itcast"); System.out.println( builder.compact() ); }}Copy the code

SetIssuedAt Used to set the signing time signWith used to set the signature key

(3) Test run, the output is as follows: eyJhbGciOiJIUzI1NiJ9.eyJqdGkiOiI4ODgiLCJzdWIiOiLlsI_nmb0iLCJpYXQiOjE1MjM0M TM0NTh9. Gq0J ‐ cOM_qCNqU_s ‐ d_IrRytaNenesPmqAIhQpYXHZk

Token of parsing

We have just created the token. In the Web application, this is done by the server and then sent to the client. The client needs to carry the token with it the next time it sends a request to the server (this is like holding a ticket). The server receiving the token should parse the information in the token (such as the user ID), query the database based on this information and return the corresponding result. Create ParseJwtTest:

public class ParseJwtTest { public static void main(String[] args) { String token="eyJhbGciOiJIUzI1NiJ9.eyJqdGkiOiI4ODgiLCJzdWIiOiLlsI_nmb0iLCJpYXQiO JE1MjM0MTM0NTh9. Gq0J ‐ cOM_qCNqU_s ‐ d_IrRytaNenesPmqAIhQpYXHZk "; Claims claims =Jwts.parser().setSigningKey("itcast").parseClaimsJws(token).getBody(); System.out.println("id:"+claims.getId()); System.out.println("subject:"+claims.getSubject()); System.out.println("IssuedAt:"+claims.getIssuedAt()); }}Copy the code

Try tampering with the token or signature key, and you’ll find an error at runtime, so parsing the token is also validating the token

SetExpiration method is used to set the expiration time test run, and can be read normal, when no overdue caused when expired IO. Jsonwebtoken. ExpiredJwtException anomalies.

Custom claims

The previous example stores only id and Subject information. If you want to store more information (such as roles) you can create CreateJwtTest3 with custom claims

public class CreateJwtTest3 {
public static void main(String[] args) {
// For testing purposes, we set the expiration time to 1 minute
long now = System.currentTimeMillis();// The current time
long exp = now + 1000*60;// The expiration time is 1 minute
JwtBuilder builder= Jwts.builder().setId("888")
.setSubject("White")
.setIssuedAt(new Date())
.signWith(SignatureAlgorithm.HS256,"itcast")
.setExpiration(new Date(exp))
.claim("roles"."admin")
.claim("logo"."logo.png"); System.out.println( builder.compact() ); }}Copy the code

When we use SpringBoot, we typically put JWT validation in the utility class of the module of the common subsystem,

@ConfigurationProperties("jwt.config")
public class JwtUtil {
private String key ;
private long ttl ;// One hour
public String getKey(a) {
return key;
}
public void setKey(String key) {
this.key = key;
}
public long getTtl(a) {
return ttl;
}
public void setTtl(long ttl) {
this.ttl = ttl;
}
/** * generates JWT **@param id
* @param subject
* @return* /
public String createJWT(String id, String subject, String roles) {
long nowMillis = System.currentTimeMillis();
Date now = newDate(nowMillis); JwtBuilder builder = Jwts.builder().setId(id) .setSubject(subject) .setIssuedAt(now) .signWith(SignatureAlgorithm.HS256,  key).claim("roles",
roles);
if (ttl > 0) {
builder.setExpiration( new Date( nowMillis + ttl));
}
return builder.compact();
}
/** * parse JWT *@param jwtStr
* @return* /
public Claims parseJWT(String jwtStr){
returnJwts.parser() .setSigningKey(key) .parseClaimsJws(jwtStr) .getBody(); }}Copy the code

Modify the application.yml of the project that needs to use the utility class and add the configuration

The administrator logs in to the background to issue the token

@Bean
public JwtUtil jwtUtil(a){
return new util.JwtUtil();
}
Copy the code

Here is an example of my login:

@Autowired private JwtUtil jwtUtil; @param loginname * @param password * @return */ @requestMapping (value="/login",method= requestmethod.post) public Result login(@RequestBody Map<String,String> loginMap){ Admin admin = adminService.findByLoginnameAndPassword(loginMap.get("loginname"), loginMap.get("password")); if(admin! =null){// Generate token String Token = jwtutil.createJwt (admin.getid (), admin.getLoginName (), "admin"); Map map=new HashMap(); map.put("token",token); map.put("name",admin.getLoginname()); Return new Result(true, statuscode. OK," login succeeded ",map); } else {return new Result (false, StatusCode. LOGINERROR "username or password is wrong Error "); }}Copy the code

Please give me a thumbs up if you like

Technology advances best when ideas collide