package com.covas.Resources; import java.nio.charset.StandardCharsets; import java.time.Duration; import javax.inject.Inject; import javax.ws.rs.CookieParam; import javax.ws.rs.GET; import javax.ws.rs.Path; import javax.ws.rs.Produces; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.NewCookie; import javax.ws.rs.core.Response; import com.covas.Classes.Hash; import com.covas.Entity.UsersEntity; import io.smallrye.jwt.auth.principal.JWTParser; import io.smallrye.jwt.auth.principal.ParseException; import io.smallrye.jwt.build.Jwt; import org.eclipse.microprofile.jwt.Claims; import org.eclipse.microprofile.jwt.JsonWebToken; import org.jboss.logging.Logger; import org.jboss.resteasy.annotations.jaxrs.HeaderParam; import org.postgresql.shaded.com.ongres.scram.common.bouncycastle.base64.Base64; @Path("/token") public class TokenRessource { @Inject JsonWebToken jwt; private static final Logger LOGGER = Logger.getLogger(UsersRessources.class); @Inject JWTParser parser; @GET @Produces(MediaType.APPLICATION_JSON) public Response tokenRefresh(@HeaderParam("Authorization") String auth, @CookieParam("user") String user, @CookieParam("jwt") String jwtCookie) { String name = "anonymous"; String password = ""; if(auth == null){ if(user == null){ return Response.status(Response.Status.BAD_REQUEST).build(); } else { name = new String(Base64.decode(user), StandardCharsets.UTF_8); } } else { String[] hash = new String(Base64.decode(auth.split(" ")[1]), StandardCharsets.UTF_8).split(":"); name = hash[0]; password = Hash.encryptSHA512(hash[1]); } UsersEntity users = UsersEntity.findByPseudo(name); if (users == null){ return Response.status(Response.Status.NOT_FOUND).build(); } if (jwtCookie == null) { if((!password.equals(users.password)) && (!users.status)) { return Response.status(Response.Status.FORBIDDEN).build(); } // Create a JWT token signed using the 'HS256' algorithm String newJwtCookie = Jwt.issuer("https://example.com/issuer").upn(name).groups(users.roles).claim(Claims.kid, users.id.toString()).expiresIn(Duration.ofMinutes(1)).sign(); // or create a JWT token encrypted using the 'A256KW' algorithm // Jwt.upn("alice").encryptWithSecret(secret); String nameEncoded = Base64.toBase64String(name.getBytes(StandardCharsets.UTF_8)); return Response.status(Response.Status.CREATED).cookie(new NewCookie("jwt", newJwtCookie), new NewCookie("user", nameEncoded)).build(); } // All mp.jwt and smallrye.jwt properties are still effective, only the verification key is customized. try { jwt = parser.parse(jwtCookie); } catch(ParseException p){ return Response.status(Response.Status.NOT_ACCEPTABLE).build(); } // or jwt = parser.decrypt(jwtCookie, secret); String kid = jwt.getClaim(Claims.kid).toString(); if(!kid.equals(users.id.toString())){ return Response.status(Response.Status.UNAUTHORIZED).build(); } return Response.status(Response.Status.OK).build(); } }