2 * Copyright 2020 Huawei Technologies Co., Ltd.
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
8 * http://www.apache.org/licenses/LICENSE-2.0
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
16 package com.eliot.eliotbe.eliotk8sclient.util;
18 import java.io.Serializable;
19 import java.util.Date;
20 import java.util.HashMap;
22 import java.util.function.Function;
24 import org.springframework.beans.factory.annotation.Value;
25 import org.springframework.security.core.userdetails.UserDetails;
26 import org.springframework.stereotype.Component;
28 import io.jsonwebtoken.Claims;
29 import io.jsonwebtoken.Jwts;
30 import io.jsonwebtoken.SignatureAlgorithm;
33 public class JwtTokenUtil implements Serializable {
35 private static final long serialVersionUID = -2550185165626007488L;
37 public static final long JWT_TOKEN_VALIDITY = 1 * 60 * 60;
39 @Value("${jwt.secret}")
40 private String secret;
42 //retrieve username from jwt token
43 public String getUsernameFromToken(String token) {
44 return getClaimFromToken(token, Claims::getSubject);
47 //retrieve expiration date from jwt token
48 public Date getExpirationDateFromToken(String token) {
49 return getClaimFromToken(token, Claims::getExpiration);
52 public <T> T getClaimFromToken(String token, Function<Claims, T> claimsResolver) {
53 final Claims claims = getAllClaimsFromToken(token);
54 return claimsResolver.apply(claims);
56 //for retrieveing any information from token we will need the secret key
57 private Claims getAllClaimsFromToken(String token) {
58 return Jwts.parser().setSigningKey(secret).parseClaimsJws(token).getBody();
61 //check if the token has expired
62 private Boolean isTokenExpired(String token) {
63 final Date expiration = getExpirationDateFromToken(token);
64 return expiration.before(new Date());
67 //generate token for user
68 public String generateToken(UserDetails userDetails) {
69 Map<String, Object> claims = new HashMap<>();
70 return doGenerateToken(claims, userDetails.getUsername());
73 private String doGenerateToken(Map<String, Object> claims, String subject) {
75 return Jwts.builder().setClaims(claims).setSubject(subject).setIssuedAt(new Date(System.currentTimeMillis()))
76 .setExpiration(new Date(System.currentTimeMillis() + JWT_TOKEN_VALIDITY * 1000))
77 .signWith(SignatureAlgorithm.HS512, secret).compact();
81 public Boolean validateToken(String token, UserDetails userDetails) {
82 final String username = getUsernameFromToken(token);
83 return (username.equals(userDetails.getUsername()) && !isTokenExpired(token));