Micronaut Security

repository·5.4.x·Indexed 41 days ago

https://github.com/micronaut-projects/micronaut-security

The official security framework for Micronaut applications, providing modular support for authentication and authorization protocols including JWT, OAuth2, LDAP, and session-based authentication. It supports Ahead-of-Time (AOT) optimizations to reduce startup time and memory usage, including build-time JWKS fetching and OpenID Connect configuration.

Tokens
55.4K
Snippets
171
Records
274
Agent score
48%

What's inside Micronaut Security

  1. Introduction to Micronaut Security

    5.4.x

    Micronaut Security is a fully featured and customizable security solution designed for Micronaut applications. It provides the necessary abstractions and implementations to secure your application's endpoints, manage authentication, and handle authorization.

    Compatibility Note: Micronaut Security 3.x is specifically designed for and requires Micronaut 3.x.

  2. Key changes in Micronaut Security 3

    5.4.x

    Micronaut Security 3 introduced several breaking changes and improvements to the security API:

    • Reactive Security Rules: The SecurityRule[] API is now reactive, allowing for non-blocking security checks.
    • Consolidated Authentication State: Authentication state has been consolidated into a single interface for easier management.
    • Enhanced Authentication API:
      • The Authentication interface now includes a getRoles() method.
      • New static factory methods have been added to both Authentication and AuthenticationResponse to simplify the creation of authentication-related objects.
  3. How authentication is resolved via Security Filters

    5.4.x

    Micronaut Security uses a Security Filter to resolve authentication for each incoming request. The filter attempts to resolve an api:security.authentication.Authentication[] array. This authentication state can be derived from several sources, including:

    • A token provided in an HTTP Header.
    • A token stored in a cookie.
    • An HTTP session.

    Understanding this mechanism is key to knowing how the framework identifies the user making a request.

  4. Use @RunAs to apply authentication to method invocations

    5.4.x

    The @io.micronaut.security.annotation.RunAs annotation allows you to apply a specific authentication context to intercepted method calls. This is useful for delegating to services that require an authenticated user when the caller is not authenticated (e.g., a @Scheduled task).

    Key Behaviors

    • Context Management: Micronaut Security builds an io.micronaut.security.authentication.Authentication object from the annotation and sets it in the current security context for the duration of the invocation.
    • Restoration:
      • For synchronous methods, the previous authentication is restored when the method returns.
      • For asynchronous methods (e.g., CompletionStage or reactive types), the previous authentication is restored when the asynchronous result completes.
    • Scope: The annotation does not authenticate the incoming request and does not permanently replace the caller's identity.

    Configuration Options

    • Roles: The annotation value is an alias for roles. @RunAs("ROLE_ADMIN") is equivalent to @RunAs(roles = "ROLE_ADMIN").
    • Appending vs Replacing: By default, roles and attributes are appended to the current authentication. To replace them instead, set appendRoles = false or appendAttributes = false.
    • User Name: If name is omitted or blank and an authentication already exists, the current user name is preserved.
    @RunAs("ROLE_ADMIN")
    public void myMethod() {
        // This method runs with ROLE_ADMIN authentication
    }
  5. How EndUserSecurityContext resolves tokens for Oracle JDBC

    5.4.x

    The EndUserSecurityContext relies on two different mechanisms to resolve its tokens:

    • Database Access Token Resolution: The provider automatically requests this token by performing an OAuth 2.0 Client Credentials flow against the tokenUrl configured in the datasource properties (datasources.*.data-source-properties.oracle.jdbc.provider.endUserSecurityContext.tokenUrl).
    • End User Token Resolution: The provider retrieves the end user's identity by accessing the current SecurityContextHolder. The token itself is resolved by Micronaut Security using the io.micronaut.security.token.reader.TokenResolver[] API, which typically extracts it from the Authorization header of the incoming HTTP request.
  6. How TokenAuthenticationFetcher works

    5.4.x

    The TokenAuthenticationFetcher is a component used to automate the process of extracting and validating security tokens from HTTP requests. It orchestrates two main steps:

    1. Token Retrieval: It uses the TokenResolver API to attempt to retrieve a token from the incoming HttpRequest (e.g., from an Authorization header).
    2. Token Validation: Once a token is retrieved, it uses the TokenValidator API to validate the token's authenticity and integrity.

    This mechanism allows Micronaut Security to handle token-based authentication (like JWT) seamlessly by decoupling the method of finding the token from the logic used to verify it.

  7. Configure the JWT audience claim

    5.4.x

    The built-in JWTClaimsSetGenerator automatically includes the aud (audience) claim in the generated JWT if a bean of type io.micronaut.security.token.claims.ClaimsAudienceProvider is present in the application context. You can implement this interface to control the value returned by the audience() method.

    @Singleton
    public class CustomClaimsAudienceProvider implements ClaimsAudienceProvider {
        @Override
        public String audience() {
            return "your-audience-value";
        }
    }
  8. How the SecurityFilter works in Micronaut Security

    5.4.x

    When the micronaut-security dependency is present, it registers a SecurityFilter (implementing api:security.filters.SecurityFilter[]) into the Micronaut HTTP Server Filter chain. The security process follows a two-step lifecycle for every incoming request:

    1. Authentication: The filter evaluates the request against every bean of type api:security.filters.AuthenticationFetcher[]. This step attempts to resolve an instance of api:security.authentication.Authentication[].
    2. Authorization: If authentication is successful (or optional), the resulting authentication is evaluated against every bean of type api:security.rules.SecurityRule[] to determine if the request is authorized. If the request fails authorization, an api:security.authentication.AuthorizationException[] is thrown.