package com.covas; import javax.annotation.security.PermitAll; import javax.annotation.security.RolesAllowed; import javax.enterprise.context.RequestScoped; import javax.inject.Inject; import javax.print.attribute.standard.Media; import javax.ws.rs.CookieParam; import javax.ws.rs.GET; import javax.ws.rs.InternalServerErrorException; import javax.ws.rs.Path; import javax.ws.rs.Produces; import javax.ws.rs.core.Context; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.NewCookie; import javax.ws.rs.core.Response; import javax.ws.rs.core.SecurityContext; 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.JsonWebToken; @Path("/token") public class TokenRessource { @Inject JsonWebToken jwt; @Inject JWTParser parser; private String secret = "AyM1SysPpbyDfgZld3umj1qzKObwVMko"; @GET @Path("generate") @Produces("text/plain") public Response getUserName(@CookieParam("jwt") String jwtCookie) throws ParseException { Response response = null; if (jwtCookie == null) { // Create a JWT token signed using the 'HS256' algorithm String newJwtCookie = Jwt.upn("Alice").signWithSecret(secret); // or create a JWT token encrypted using the 'A256KW' algorithm // Jwt.upn("alice").encryptWithSecret(secret); return Response.ok("Alice").cookie(new NewCookie("jwt", newJwtCookie)).build(); } else { // All mp.jwt and smallrye.jwt properties are still effective, only the verification key is customized. JsonWebToken jwt = parser.verify(jwtCookie, secret); // or jwt = parser.decrypt(jwtCookie, secret); return Response.ok(jwt.getName()).build(); } } @GET @Path("permit-all") @PermitAll @Produces(MediaType.APPLICATION_JSON) public Token hello(@Context SecurityContext ctx) { return getResponseString(ctx); } @GET @Path("roles-allowed") @RolesAllowed({ "User", "Admin" }) @Produces(MediaType.APPLICATION_JSON) public Token helloRolesAllowed(@Context SecurityContext ctx) { Token token = getResponseString(ctx); token.birthday = jwt.getClaim("birthday").toString(); return token; } private Token getResponseString(SecurityContext ctx) { String name; if (ctx.getUserPrincipal() == null) { name = "anonymous"; } else if (!ctx.getUserPrincipal().getName().equals(jwt.getName())) { throw new InternalServerErrorException("Principal and JsonWebToken names do not match"); } else { name = ctx.getUserPrincipal().getName(); } return new Token(name, ctx.isSecure(), ctx.getAuthenticationScheme(), hasJwt()); } private boolean hasJwt() { return jwt.getClaimNames() != null; } }