JSON Web Tokens (JWT) are an open, industry standard (RFC 7519) method for representing claims securely between two parties.
JWT defines a compact and self-contained way for securely transmitting information between parties as a JSON object. With JWT Auth you can integrate security features such as single sign on into your Helidon MP applications.
<dependency>
<groupId>io.helidon.microprofile.jwt</groupId>
<artifactId>helidon-microprofile-jwt-auth</artifactId>
</dependency>The main configuration point for JWT Auth is a JAX-RS Application class. As this class is discovered using CDI, it must have a bean defining annotation.
Minimal required setup is done using @LoginConfig(authMethod = "MP-JWT"):
@LoginConfig(authMethod = "MP-JWT")
@ApplicationScoped
public class ProtectedApplication extends Application{
}The following interfaces and annotations are used to work with JWT in Helidon MP:
-
JsonWebToken- an interface used in CDI beans (@RequestScoped) dependency injection to obtain the JWT of the currently executing caller. -
@Claim- an annotation used by CDI bean (@RequestScoped) dependency injection to obtain individual claims from the caller’s JWT. -
ClaimValue- a proxy interface used with@Claimannotation to оbtain the value of a claim by callinggetValue().
A configuration example in microprofile-config.properties:
mp.jwt.verify.issuer=https://{PublicIssuerDomain}/oauth2/default
mp.jwt.verify.publickey.location=${mp.jwt.verify.issuer}/v1/keys@Path("/hello")
public class HelloResource {
@GET
@Produces(TEXT_PLAIN)
public String hello(@Context SecurityContext context) {
Optional<Principal> userPrincipal = context.userPrincipal();
return "Hello, " + userPrincipal.get().getName() + "!";
}
}Do not forget to annotate the HelloApplication class to enable JWT:
@LoginConfig(authMethod = "MP-JWT")
@ApplicationScoped
public class HelloApplication extends Application {
@Override
public Set<Class<?>> getClasses() {
return Set.of(HelloResource.class);
}
}Add the following configuration in microprofile-config.properties:
mp.jwt.verify.issuer=https://{IssuerPublicDomain}/oauth2/default
mp.jwt.verify.publickey.location=${mp.jwt.verify.issuer}/v1/keysObtain the Security Token from external issuer:
TOKEN=sdf4dDSWFcswdsffDSasEgv...Run the application and execute an HTTP request against it:
curl -X GET -I -H "Authorization: Bearer $TOKEN" http://localhost:8080/helloThe result should be:
HTTP/1.1 200 OK
Date: 08.06.2022 10:33:47 EEST
connection: keep-alive
content-length: 28
Hello, secure@helidon.io!which means that the request successfully passed authentication.
Learn more about JWT authentication at:
Eclipse MicroProfile Interoperable JWT RBAC
-
{microprofile-jwt-spec-url}[MicroProfile JWT Auth Spec]