I am currently working on a project for the university. I have to create a rest interface and an authentication. I have created the Rest interface with Micronaut. For the login and authentication I used Json Web Token (JWT). To login to the system you have to enter a username and a password. At the rest point of the login the data username and password are fetched from the database and compared if it fits. (Security is not so important, the focus of the project is different) But if I want to make a booking of a card (that's what the project is about) I have to save the user in the transaction. Now the question is how I can do this best. Would it be best if I save a cookie with the username and read it out again when booking? I don't know much about JWT so another question is, can I decode the token and extract the username from it?
Are there any other approaches which are better suited for this? Can I use Micronaut JWT to return the UserID in a response? Unfortunately I can't find anything in the examples.
@Singleton
public class LoginApi implements AuthenticationProvider{
private WebLoginService webLoginService = ServiceLocator.getWebLoginService();
@Override
public Publisher<AuthenticationResponse> authenticate(HttpRequest<?> httpRequest, AuthenticationRequest<?, ?> authenticationRequest) {
return Flux.create(emitter -> {
CustomerID customerID = webLoginService.tryToLogIn((String) authenticationRequest.getIdentity(), (String) authenticationRequest.getSecret());
if(customerID != null && customerID.customerID() != null) {
emitter.next(AuthenticationResponse.success((String) customerID.customerID()));
emitter.complete();
} else {
emitter.error(AuthenticationResponse.exception());
}
}, FluxSink.OverflowStrategy.ERROR);
}
}
Would it be best if I save a cookie with the username and read it out again when booking?
Likely not. If what you want is the user name it would be better to retrieve that from a SecurityService
, Principal
or Authentication
object as described at https://micronaut-projects.github.io/micronaut-security/3.2.1/guide/#retrievingAuthenticatedUser.