100 Recipes for Programming Java: Learn Java Today by Jamie Munro
Author:Jamie Munro [Munro, Jamie]
Language: eng
Format: azw3
Published: 2017-08-09T04:00:00+00:00
Identifying the current user
It's very likely you will need to know the user who is performing the request within your REST endpoints. The following approaches can be useful to do it:
Overriding the SecurityContext
Within your ContainerRequestFilter.filter(ContainerRequestContext) method, you can set a new security context information for the current request.
Override the SecurityContext.getUserPrincipal(), returning a Principal instance.
The Principal's name is the username of the user you issued the token for. You will have to know it when validating the token.
final SecurityContext currentSecurityContext = requestContext.getSecurityContext(); requestContext.setSecurityContext(new SecurityContext() { @Override public Principal getUserPrincipal() { return new Principal() { @Override public String getName() { return username; } }; } @Override public boolean isUserInRole(String role) { return true; } @Override public boolean isSecure() { return currentSecurityContext.isSecure(); } @Override public String getAuthenticationScheme() { return "Bearer"; } });
Inject a proxy of the SecurityContext in any REST endpoint class:
@Context SecurityContext securityContext;
The same can be done in a method:
@GET @Secured @Path("{id}") @Produces(MediaType.APPLICATION_JSON) public Response myMethod(@PathParam("id") Long id, @Context SecurityContext securityContext) { ... }
And get the Principal:
Principal principal = securityContext.getUserPrincipal(); String username = principal.getName();
Using CDI (Context and Dependency Injection)
If, for some reason, you don't want to override the SecurityContext, you can use CDI, which provides useful features such as events and producers.
Create a CDI qualifier which will be used when handling the authentication event and when injecting the authenticated user in your beans:
@Qualifier @Retention(RUNTIME) @Target({ METHOD, FIELD, PARAMETER }) public @interface AuthenticatedUser { }
In your AuthenticationFilter created above, inject an Event:
@Inject @AuthenticatedUser Event<String> userAuthenticatedEvent;
When the user authenticates, fire the event passing the username as parameter (remember, your token must be associated to a user and you need to be able to retrieve the username from a token):
userAuthenticatedEvent.fire(username);
Probably you have a class which represents a user in your application. Let's call this class User.
The piece of code below handles the authentication event, finds a User instance with the correspondent username and assigns it to the field authenticatedUser:
@RequestScoped public class AuthenticatedUserProducer { @Produces @RequestScoped @AuthenticatedUser private User authenticatedUser; public void handleAuthenticationEvent(@Observes @AuthenticatedUser String username) { this.authenticatedUser = findUser(username); } private User findUser(String username) { // Hit the the database or a service to find a user by its username and return it // Return the User instance } }
The authenticatedUser field produces a User instance which can be injected in your beans, such as JAX-RS services, CDI beans, servlets and EJBs:
@Inject @AuthenticatedUser User authenticatedUser;
Note that the CDI @Produces annotation is different from the JAX-RS @Produces annotation:
CDI: javax.enterprise.inject.Produces
JAX-RS: javax.ws.rs.Produces
Download
This site does not store any files on its server. We only index and link to content provided by other sites. Please contact the content providers to delete copyright contents if any and email us, we'll remove relevant links or contents immediately.
The Mikado Method by Ola Ellnestam Daniel Brolund(27093)
Hello! Python by Anthony Briggs(25942)
Secrets of the JavaScript Ninja by John Resig Bear Bibeault(25283)
Kotlin in Action by Dmitry Jemerov(24393)
The Well-Grounded Java Developer by Benjamin J. Evans Martijn Verburg(23590)
Dependency Injection in .NET by Mark Seemann(23311)
OCA Java SE 8 Programmer I Certification Guide by Mala Gupta(21942)
Algorithms of the Intelligent Web by Haralambos Marmanis;Dmitry Babenko(20847)
Grails in Action by Glen Smith Peter Ledbrook(19869)
Adobe Camera Raw For Digital Photographers Only by Rob Sheppard(17072)
Sass and Compass in Action by Wynn Netherland Nathan Weizenbaum Chris Eppstein Brandon Mathis(16832)
Secrets of the JavaScript Ninja by John Resig & Bear Bibeault(14464)
Test-Driven iOS Development with Swift 4 by Dominik Hauser(12581)
Jquery UI in Action : Master the concepts Of Jquery UI: A Step By Step Approach by ANMOL GOYAL(11865)
A Developer's Guide to Building Resilient Cloud Applications with Azure by Hamida Rebai Trabelsi(10650)
Hit Refresh by Satya Nadella(9236)
The Kubernetes Operator Framework Book by Michael Dame(8586)
Exploring Deepfakes by Bryan Lyon and Matt Tora(8443)
Robo-Advisor with Python by Aki Ranin(8386)