1

In Micronaut I have a very basic requirement. I just want to decode the JWT token and check if one key is present in the claims map. I have not come across any implementation where we are just validating the token. I have implemented the custom Authentication Provider but while debugging the API returns 401 and does not go into authentication function.

import io.micronaut.http.HttpRequest;
import io.micronaut.security.authentication.AuthenticationProvider;
import io.micronaut.security.authentication.AuthenticationRequest;
import io.micronaut.security.authentication.AuthenticationResponse;
import jakarta.inject.Singleton;
import org.reactivestreams.Publisher;
import reactor.core.publisher.Mono;

@Singleton
public class ValidateToken implements AuthenticationProvider {

    @Override
    public Publisher<AuthenticationResponse> authenticate(HttpRequest<?> httpRequest, AuthenticationRequest<?, ?> authenticationRequest) {
        System.out.println("NEW VALUE");
        return Mono.<AuthenticationResponse>create(emitter -> emitter.success(AuthenticationResponse.success("user")));
    }
}

application.yml

micronaut:
  application:
    name: addresingMicronaut
  security:
    authentication: bearer
    enabled: true
    token:
      jwt:
        enabled: true

controller.java

@Controller("/v1")
@Secured(SecurityRule.IS_AUTHENTICATED)
public class VerifyController {

    @Get("/person")
    public String findAllV2(@NotNull Integer max, @NotNull Integer offset) {
        return "1";
    }

}

I basically want the code to go through validate token function so that I can write my own logic in that function

Rahul Khanna
  • 316
  • 3
  • 12

1 Answers1

0

The com.example.ValidateToken#authenticate method is called whenever {YourBaseUrl}/login is called. You can define the JWT parameters in the AuthenticationResponse.success() method.

If you'd like to have access to the previously defined properties in a controller method, you can pass in Authentication which will give you access to said properties like so:

@Get("/person")
public String findAllV2(@NotNull Integer max, @NotNull Integer offset, @Valid Authentication authentication) {
    return "1";
}
  • It doesn't work. There is an issue that if you add micronaut-security dependency and even if you set micronaut.security.enabled=false it would still go to authenticate the token. There doesn't seem to be a way to solve this in micronaut – Rahul Khanna Nov 15 '22 at 05:59