mvn clean install tomee:run
MicroProfile JWT Principal
This is an example on how to use MicroProfile JWT in TomEE by accessing Principal from the JsonWebToken.
Run the application:
This example is a CRUD application for orders in store.
Requirments and configuration
For usage of MicroProfile JWT we have to change the following to our project:
-
Add the dependency to our
pom.xml
file:<dependency> <groupId>org.eclipse.microprofile.jwt</groupId> <artifactId>microprofile-jwt-auth-api</artifactId> <version>${mp-jwt.version}</version> <scope>provided</scope> </dependency>
-
Annotate our
Application.class
with@LoginConfig(authMethod = "MP-JWT")
-
Provide public and private key for authentication. And specify the location of the public key and the issuer in our
microprofile-config.properties
file.mp.jwt.verify.publickey.location=/publicKey.pem mp.jwt.verify.issuer=https://example.com
-
Define
@RolesAllowed()
on the endpoints we want to protect.
Obtaining the JWT Principal
We obtain the Principal
in the MicroProfile class org.eclipse.microprofile.jwt.JsonWebToken
. From there
we can acquire username and groups of the user that is accessing the endpoint.
@Inject
private JsonWebToken jwtPrincipal;
About the application architecture
The application enables us to manipulate orders with specific users. We have two users Alice Wonder
and John Doe
. They can read, create, edit and delete specific entries. And for each creation
we save the user who created the order. In case a user edits the entry we record that by accessing
the Principal
who has sent the request to our backend.
alice-wonder-jwt.json
{
"iss": "https://example.com",
"upn": "alice",
"sub": "alice.wonder@example.com",
"name": "Alice Wonder",
"iat": 1516239022,
"groups": [
"buyer"
]
}
john-doe-jwt.json
{
"iss": "https://example.com",
"upn": "john",
"sub": "john.doe@example.com",
"name": "John Doe",
"iat": 1516239022,
"groups": [
"merchant"
]
}
Access the endpoints with JWT token
We access endpoints from our test class by creating a JWT
with the help of
our TokenUtils.generateJWTString(String jsonResource)
which signs our user
data in json format with the help of our src/test/resources/privateKey.pem
key.
We can also generate new privateKey.pem
and publicKey.pem
with the
GenerateKeyUtils.generateKeyPair(String keyAlgorithm, int keySize)
method.