JwtUtil.java

/**
 * TFG 75.678 - TFG Desarrollo web 2020 e-Learning for Schools
 * Copyright (C) 2020  Eduardo Rodriguez Carro
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */
package org.uoc.tfg.sel.security;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.uoc.tfg.sel.security.model.JWTToken;

import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;

/**
 * Componente de Utilidad para trabajar y encapsular la libreria de Token JWT de
 * forma que sea facilmente reemplazable.
 *
 * @author Eduardo Rodriguez Carro
 */
@Component
public class JwtUtil {

	/** The secret. */
	@Value("${security.jwt.secret:ihavenosecrets}")
	private String secret;
	
	/**
	 * Obtencion del objeto de Token desde String con validacion de su firma.
	 *
	 * @param token the token
	 * @return the token
	 */
	public JWTToken getToken(String token) {
		Claims claims = Jwts.parser().setSigningKey(secret).parseClaimsJws(token).getBody();
		
		JWTToken jwt = new JWTToken();
		jwt.setSubject(claims.getSubject());
		jwt.setIssuer(claims.getIssuer());
		jwt.setExpiration(claims.getExpiration());
		jwt.setIssuedAt(claims.getIssuedAt());
		jwt.setSessionId(claims.get(JWTToken.SESSION_ID, String.class));
		
		// Creamos una copia del Map
		jwt.setOther(new HashMap<>(claims));
		
		return jwt;
	}
	
	/**
	 * Generacion de un token firmado.
	 *
	 * @param claims   the claims
	 * @param subject  the subject
	 * @param lifetime the lifetime
	 * @return the string
	 */
	public String generateToken(Map<String,Object> claims,String subject,Long lifetime) {
		
		if(claims == null) {
			claims = new HashMap<>();
		}
		return Jwts.builder()
				.setClaims(claims)
				.setSubject(subject)
				.setIssuedAt(new Date())
				.setExpiration(new Date(System.currentTimeMillis() + lifetime))
				.signWith(SignatureAlgorithm.HS512, secret).compact();
	}
	

}