pyronaut create example.micronaut.micronautguide --features=security
Table of Contents
Micronaut Basic Auth
Learn how to secure a Pyronaut application using 'Basic' HTTP Authentication Scheme.
1. Getting Started
In this guide, we will create a Pyronaut application written in Python and secure it with HTTP Basic Auth.
RFC7617 defines the "Basic" Hypertext Transfer Protocol (HTTP) authentication scheme, which transmits credentials as user-id/password pairs, encoded using Base64.
2. What you will need
To complete this guide, you will need the following:
-
Some time on your hands
-
GraalPy installed and the Pyronaut CLI available locally
3. Solution
We recommend that you follow the instructions in the next sections and create the application step by step. However, you can go right to the completed example.
-
Download and unzip the source
4. Writing the Application
Create an application using the Pyronaut CLI (Command Line Interface) or Pyronaut Launch
4.1. Authentication Provider
To keep this guide simple, create a naive AuthenticationProvider to simulate user authentication.
from jakarta.inject import Singleton
from micronaut.security.authentication import (
AuthenticationFailureReason,
AuthenticationResponse,
)
from micronaut.security.authentication.provider import HttpRequestAuthenticationProvider
@Singleton (1)
class AuthenticationProviderUserPassword(HttpRequestAuthenticationProvider): (2)
def authenticate(self, http_request, authentication_request) -> AuthenticationResponse:
identity = authentication_request.getIdentity()
secret = authentication_request.getSecret()
if identity == "sherlock" and secret == "password":
return AuthenticationResponse.success(identity)
return AuthenticationResponse.failure(AuthenticationFailureReason.CREDENTIALS_DO_NOT_MATCH)
| 1 | Use jakarta.inject.Singleton to designate a class as a singleton. |
| 2 | A Micronaut Authentication Provider implements the interface io.micronaut.security.authentication.provider.HttpRequestAuthenticationProvider. |
4.2. Controllers
Create HomeController which resolves the base URL /:
from java.security import Principal
from micronaut.http import MediaType
from micronaut.http.annotation import Get, Produces
from micronaut.security.annotation import Secured
from micronaut.security.rules import SecurityRule
@Produces(MediaType.TEXT_PLAIN)
@Secured(SecurityRule.IS_AUTHENTICATED) (1)
@Get("/") (2) (3)
def index(principal: Principal) -> str: (4)
return principal.getName()
| 1 | Annotate with io.micronaut.security.Secured to configure secured access. The isAuthenticated() expression will allow access only to authenticated users. |
| 2 | You can specify the HTTP verb that a controller action responds to. To respond to a GET request, use the io.micronaut.http.annotation.Get annotation. |
| 3 | The root route responds to /. |
| 4 | If a user is authenticated, the Micronaut framework will bind the user object to an argument of type java.security.Principal (if present). |
4.3. WWW-Authenticate
Replace the default Exception Handler for AuthorizationExceptionHandler, the exception raised when a request is not authorized.
from jakarta.inject import Singleton
from micronaut.context.annotation import Replaces
from micronaut.http import HttpHeaders, HttpResponse, HttpStatus, MutableHttpResponse
from micronaut.http.server.exceptions import ExceptionHandler
from micronaut.security.authentication import (
AuthorizationException,
DefaultAuthorizationExceptionHandler,
)
@Singleton (1)
@Replaces(DefaultAuthorizationExceptionHandler) (2)
class DefaultAuthorizationExceptionHandlerReplacement(
ExceptionHandler[AuthorizationException, MutableHttpResponse]
):
def handle(self, request, e: AuthorizationException) -> MutableHttpResponse:
if e.isForbidden():
return HttpResponse.status(HttpStatus.FORBIDDEN)
return HttpResponse.status(HttpStatus.UNAUTHORIZED).header(
HttpHeaders.WWW_AUTHENTICATE,
'Basic realm="Micronaut Guide"',
)
The previous code adds the WWW-Authenticate header to indicate the authentication scheme.
| 1 | Use jakarta.inject.Singleton to designate a class as a singleton. |
| 2 | Specify that DefaultAuthorizationExceptionHandlerReplacement replaces the bean DefaultAuthorizationExceptionHandler |
4.4. Tests
Create a test to verify the user authentication flow via Basic Auth.
import pytest
import requests
from pyronaut.test import MicronautTest, micronaut_test_fixture
@pytest.fixture
def my_context(request):
fixture = micronaut_test_fixture(request, MicronautTest()) (1)
yield fixture
fixture.stop()
@pytest.fixture
def client(my_context):
return requests.with_context(my_context) (2)
def test_verify_http_basic_auth_works(client):
response = client.get("/", headers={"Accept": "text/plain"}) (3)
assert response.status_code == 401, response.text (4)
assert response.headers["WWW-Authenticate"] == 'Basic realm="Micronaut Guide"'
response = client.get(
"/",
headers={"Accept": "text/plain"},
auth=("sherlock", "password"), (5)
)
assert response.status_code == 200
assert response.text == "sherlock" (6)
| 1 | Annotate the class with @MicronautTest so the Micronaut framework will initialize the application context and the embedded server. More info. |
| 2 | Inject the HttpClient bean and point it to the embedded server. |
| 3 | Creating HTTP Requests is easy thanks to the Micronaut framework fluid API. |
| 4 | If you attempt to access a secured endpoint without authentication, 401 is returned |
| 5 | By using basicAuth method, you populate the Authorization header with user-id:password pairs, encoded using Base64. |
| 6 | The requests response exposes the response body through text. |
4.5. Use the Micronaut HTTP Client and Basic Auth
If you want to access a secured endpoint, you can also use a Micronaut HTTP Client and supply the Basic Auth as the Authorization header value.
First create a @Client with a method home which accepts an Authorization HTTP header.
from abc import ABC, abstractmethod
from typing import Annotated
from micronaut.http import MediaType
from micronaut.http.annotation import Consumes, Get, Header
from micronaut.http.client.annotation import Client
@Client("/")
class AppClient(ABC):
@Consumes(MediaType.TEXT_PLAIN) (1)
@Get("/")
@abstractmethod
def home(self, authorization: Annotated[str, Header]) -> str: (2)
...
| 1 | The method consumes plain text, so the Micronaut framework includes the HTTP header Accept: text/plain. |
| 2 | The first character of the parameter name is capitalized and that value (Authorization) is used as the HTTP header name. To change the parameter name, specify the @Header annotation value. |
Create a test which uses the previous @Client
import base64
import pytest
from pyronaut.test import MicronautTest, micronaut_test_fixture
@pytest.fixture
def my_context(request):
fixture = micronaut_test_fixture(request, MicronautTest()) (1)
yield fixture
fixture.stop()
@pytest.fixture
def app_client(my_context):
return my_context["example.micronaut.AppClient"] (2)
def test_verify_basic_auth_works(app_client):
credentials = basic_auth("sherlock", "password")
response = app_client.home(credentials) (3)
assert response == "sherlock"
def basic_auth(username: str, password: str) -> str:
encoded = base64.b64encode(f"{username}:{password}".encode()).decode()
return f"Basic {encoded}"
| 1 | Annotate the class with @MicronautTest so the Micronaut framework will initialize the application context and the embedded server. More info. |
| 2 | Inject the AppClient bean. |
| 3 | Generate Basic Auth header value and pass it as the parameter value. |
5. Testing the Application
To run the tests:
pyronaut install
pyronaut validate-config
pyronaut test
6. Running the Application
To run the application, use the pyronaut dev command, which starts the application on port 8080.
To test the running application, issue a GET request to localhost:8080 with a Basic Authentication header. One way to do this is with curl:
curl -v -u sherlock:password localhost:8080
If you open http://localhost:8080 in a browser, a login dialog pops up due to the WWW-Authenticate header.
You can invoke the controller exposed by the native executable:
curl "http://localhost:8080" -u 'sherlock:password'
7. Next Steps
See the Micronaut security documentation to learn more.
8. License
| All guides are released with an Apache License 2.0 for the code and a Creative Commons Attribution 4.0 license for the writing and media (images). |