Micronaut Basic Authentication

Share on:

Create a project

Run mn create-app basic-auth to create a new project from scratch.

Add Security module to project

Head over to basic-auth project and open build.gradle file. Add following code snippet in build.gradle file dependencies

1implementation "io.micronaut:micronaut-security"

Implement AuthenticationProvider

Now that we have created a project and added security module, lets implement AuthenticaionProvider interface and provide a concrete implementation. For our basic use-case we would say that username=password=x where x is any value.

Our implementation code somewhat looks like this:

 1import io.micronaut.security.authentication.*;
 2import io.reactivex.Flowable;
 3import lombok.extern.slf4j.Slf4j;
 4import org.reactivestreams.Publisher;
 5
 6import javax.inject.Singleton;
 7import java.util.Collections;
 8
 9@Slf4j
10@Singleton
11public class BasicAuthenticationProvider implements AuthenticationProvider {
12    @Override
13    public Publisher<AuthenticationResponse> authenticate(AuthenticationRequest authenticationRequest) {
14        final String identity = (String) authenticationRequest.getIdentity();
15        final String secret = (String) authenticationRequest.getSecret();
16        log.debug("Basic " + identity + " access");
17        return identity.equals(secret) ? Flowable.just(new UserDetails(identity, Collections.emptyList()))
18                : Flowable.just(new AuthenticationFailed());
19    }
20}

Please note @Slf4j annotation, this is something we have added in out project using lombok more here https://projectlombok.org. This is a great productivity tools and i encourage you to try this out.

@Singleton annotation is self-explanatory i.e only single instance of this class will be created and used.

Writing Secured Controller

Create a controller with @Controller annotation and implement 2 methods:

  • One which is secured
  • Other is anonymous
 1@Slf4j
 2@Controller("/secured")
 3public class SecuredController {
 4
 5    @Get
 6    @Produces(value = MediaType.TEXT_PLAIN)
 7    @Secured(SecurityRule.IS_AUTHENTICATED)
 8    public String get(Principal principal) {
 9        log.debug("user {} accessed controller {}", principal.getName(), log.getName());
10        return "Secured controller secured access";
11    }
12
13    @Get(uri = "/anonymous")
14    @Produces(value = MediaType.TEXT_PLAIN)
15    @Secured(SecurityRule.IS_ANONYMOUS)
16    public String getAnonymous() {
17        return "Secured controller anonymous access";
18    }
19}

If you are using IntelliJ Idea, then just add a configuration for gradle and pass run argument to it and press play. Otherwise execute gradlew run command for windows or ./gradlew run for linux or mac from the root project.

Enable Security in Configuration

Though we have written logic for authentication and safe-guarded our controller for basic-authentication. Security mechanism would still not trigger. We need to enable it using setting present in application.yml

Final file looks like this:

 1# App general
 2---
 3micronaut:
 4  application:
 5    name: micronaut-authentication-series
 6---
 7
 8# App Security
 9micronaut:
10  security:
11    enabled: true
12    endpoints:
13      login:
14        enabled: true

Test

Hit http://localhost:8080/secured/anonymous and you should be able to see response without adding any authentication.

Try secure Url, http://localhost:8080/secured from postman it should return 401 Error Code. Now add Authorization type Basic Auth from Postman and supply values test:test for username:password and hit send again. You should be able to see response with 200 Code.

Code

https://gitlab.com/silentsudo/auth-sample

Reference

Official Guide

comments powered by Disqus