This section will document breaking changes that may happen during milestone or release candidate releases, as well as major releases eg (1.x.x → 2.x.x).
Micronaut Security 5.6 breaking changes
To stop buffering request bodies it does not need, the CSRF filter now resolves tokens sequentially. Previously, whenever the FieldCsrfTokenResolver was enabled (the default), the filter ran every resolver for every protected request, so each form submission had its whole body read and held in memory before a valid CSRF token in the HTTP header was considered. Every form submission therefore cost the server memory proportional to its body, up to micronaut.server.max-request-size, even when the body was not needed to validate the request. The filter now consults the CsrfTokenResolver and FutureCsrfTokenResolver beans one at a time, in order, and accepts the request at the first token which validates, so the body is not parsed when the HTTP header carries a valid CSRF token. A resolver which does not find a token, which throws, or whose token does not validate, no longer rejects the request by itself: the next resolver is consulted, and the request is rejected when no resolver yields a valid token. Previously, when no FutureCsrfTokenResolver bean was registered (for example with micronaut.security.csrf.token-resolvers.field.enabled=false), the first resolver which threw, or which yielded a token which did not validate, rejected the request.
Reporting API endpoint names are validated against the HTTP Structured Fields dictionary key grammar: they start with a lowercase ASCII letter or and contain only lowercase letters, digits, _, -, . or . A browser discards the whole Reporting-Endpoints header when one key is outside that grammar. The application now fails to start when an entry under micronaut.security.reporting-endpoints has an invalid name. A configuration entry without a url, and an endpoint contributed by a ReportingEndpoint or ReportingEndpointProvider bean with an invalid name or without a URL, is left out of the header and logged at WARN; previously a missing URL failed every response carrying the header. The constructor of ReportingEndpoints throws IllegalArgumentException for such an endpoint. When two endpoints share a name, the response filter now advertises only the first one and logs the other at WARN; endpoints from configuration or beans come before those from providers. Previously both were serialized and the browser used the last one.
Token cookies default to SameSite=Lax
The JWT access token cookie (micronaut.security.token.cookie) and the refresh token cookie (micronaut.security.token.refresh.cookie) are issued with the SameSite=Lax attribute by default starting with 5.6.0. Previously, no SameSite attribute was set.
This change mitigates cross-site request forgery (CSRF). Without the attribute, the handling of the cookie is left to the browser, and browsers that do not treat such cookies as Lax send them with every cross-site request. A malicious site could then trigger authenticated requests, such as a form POST, on behalf of a logged-in user. With SameSite=Lax, the browser sends the token cookies with same-site requests and with top-level navigations that use a safe HTTP method such as GET, but not with cross-site subrequests or cross-site POST requests.
The cookie-same-site setting accepts Strict, Lax or None. Use None only when the application requires cross-site token cookies. Unlike omitting the attribute, which allows the browser to apply its default SameSite policy, None explicitly permits cookies to be sent with cross-site requests:
SameSite=None requires the cookie to also be Secure.
To restore the previous omission of the SameSite attribute, set cookie-same-site to an empty value. Omitting the attribute uses the browser’s default SameSite policy; it is not equivalent to SameSite=None.
A key left without a value, such as cookie-same-site: or cookie-same-site: ~ in YAML, is an empty value as well. As before, a value other than Strict, Lax or None (case-insensitive) is not rejected: it also omits the SameSite attribute.
Warning when token cookies are issued without Secure
cookie-secure still defaults to the secure status of the request, so plain HTTP local development keeps working. However, if a login issues a token cookie without the Secure attribute over a request that was not detected as secure, CookieLoginHandler logs a WARN once starting with 5.6.0. Behind a TLS-terminating proxy, explicitly set micronaut.security.token.cookie.cookie-secure=true and micronaut.security.token.refresh.cookie.cookie-secure=true.
On the Netty server, request.isSecure() checks whether the connection to the application uses TLS. Forwarded headers such as Forwarded and X-Forwarded-Proto, and the host-resolution settings, do not change that result or add the Secure cookie attribute.
Refresh token cookie default maximum age
RefreshTokenCookieConfigurationProperties now declares the 30 day default of micronaut.security.token.refresh.cookie.cookie-max-age, so getCookieMaxAge() returns it when the setting is not configured. Previously it returned an empty Optional and TokenCookieLoginHandler applied the default. The refresh token cookie issued is unchanged.
Micronaut Security 5.5 breaking changes
Starting with 5.5.2, issuer claim matching is stricter. Previously, the iss claim was accepted when the expected issuer (micronaut.security.token.jwt.claims-validators.issuer, or micronaut.security.oauth2.clients..openid.issuer for IdTokenClaimsValidator and DefaultProviderResolver) merely ended with the claim value once the scheme and trailing slash were removed, so for a configured issuer admin-portal values such as portal, l, /, https:// or an empty string passed validation, and for https://idcs-abc.identity.oraclecloud.com the parent domain https://identity.oraclecloud.com/ did.
Now the iss claim must be equal to the expected issuer. Suffixes and parent domains are never accepted.
For micronaut.security.token.jwt.claims-validators.issuer (IssuerJwtClaimsValidator), a value starting with http:// or https:// is compared after removing the scheme and a single trailing slash; the scheme is now matched case-insensitively (HTTPS:// equals https://), while the host, port and path remain case-sensitive as before. The trailing slash is only ignored when the value has no query or fragment, where it is part of that component. Any other value is an opaque StringOrURI and is compared verbatim, so admin-portal/ no longer matches admin-portal. Surrounding whitespace in the claim is not ignored.
If micronaut.security.token.jwt.claims-validators.issuer is present but has no value (for example issuer: in YAML), IssuerJwtClaimsValidator now rejects every token and logs a warning at startup; previously it accepted any iss claim.
For the OpenID client validators (IdTokenClaimsValidator and DefaultProviderResolver), the iss claim must be identical to the expected issuer (micronaut.security.oauth2.clients..openid.issuer-identifier if set, otherwise openid.issuer), as OpenID Connect Core 1.0 section 3.1.3.7 requires: only the case of the scheme and a single trailing slash (when the issuer has no query or fragment) are tolerated, so an http:// claim no longer matches an https:// issuer and the host is compared case-sensitively. This is the same comparison IssuerClaimValidator and the issuer binding of the JWKS use.
If your provider issues tokens whose iss differs from the configured issuer, configure the exact iss value: claims-validators.issuer for IssuerJwtClaimsValidator, and openid.issuer-identifier for the OpenID client validators (for example https://identity.oraclecloud.com/ for Oracle IDCS, whose tenant specific openid.issuer is only the discovery URL).
ClaimsUtils.endsWithIgnoringProtocolAndTrailingSlash(String, String) has been deprecated and now delegates to ClaimsUtils.equalsIgnoringProtocolAndTrailingSlash(String, String), which implements the rule above.
Starting with 5.5.2, when micronaut.security.authentication is set to idtoken, IdTokenClaimsValidator ignores OAuth 2.0 clients configured with micronaut.security.oauth2.clients.*.enabled: false. ID tokens issued to a disabled client no longer authenticate requests as bearer tokens or JWT cookies. The OpenID provider metadata and the JWKS signature configuration of a disabled client are no longer registered. This removes only the trust that client itself contributed: if the claims validator is disabled with micronaut.security.token.jwt.claims-validators.openid-idtoken: false, a token issued to the disabled client is still accepted when an enabled client trusts the same issuer and signing keys, because nothing checks the aud claim. Keep IdTokenClaimsValidator, or an equivalent custom GenericJwtClaimsValidator, active to isolate clients that share an OpenID provider. In idtoken authentication mode, unsigned JWTs are now always rejected, including when every OAuth 2.0 client is disabled or none is configured and no JWKS signature configuration exists. DefaultProviderResolver and the well-known proxy also ignore disabled clients. The constructor DefaultProviderResolver(List<OpenIdClientConfiguration>) has been deprecated. Use DefaultProviderResolver(List<OpenIdClientConfiguration>, Collection<OauthClientConfiguration>) instead.
AttributesConvertibleValues no longer splits a single-valued LDAP attribute at commas when it is read as a collection or an array. Every attribute value is one element. As a result, DefaultLdapGroupProcessor maps an LDAP group named Sales,Marketing to the single role Sales,Marketing instead of the two roles Sales and Marketing. Applications relying on the previous splitting must map such groups themselves with a custom LdapGroupProcessor.
The toString() of all security events no longer includes the event source. AccessTokenGeneratedEvent, RefreshTokenGeneratedEvent and TokenValidatedEvent no longer print the token, and the events extending SecurityEvent (LoginSuccessfulEvent, LoginFailedEvent, LogoutEvent and TokenValidatedEvent) no longer print the authentication or response they carry, whose attributes may hold tokens in OAuth 2.0 and OpenID Connect flows. Micronaut Framework logs every published event at DEBUG level with its string representation, which wrote these values to the log. Use getSource() or getRefreshToken() to obtain the value in your listeners.
SignedRefreshTokenGenerator no longer includes the token being validated in its WARN log messages. The introspection endpoint and the refresh token grant hand client-supplied tokens, such as other users' access tokens, to the refresh token validator, so the value was being written to the application log. The parse or verification exception is now logged at DEBUG without the token.
Log statements no longer include credentials, tokens or claim values: the Authorization header (HttpHeaderTokenReader), undecodable basic auth credentials (BasicAuthUtils), JSON Web Tokens verified or rejected by the signature validators and JWKS signatures, the claim set generated by JWTClaimsSetGenerator (only claim names are logged), the access tokens handled by the client credentials client, and the nonce and claims of an ID token that fails nonce validation. Applications relying on these log messages for troubleshooting no longer see the values.
TokenAuthenticationFetcher consults the TokenValidator beans one at a time, in order, and stops at the first validator which authenticates the token. Previously every validator was invoked concurrently for each token, which handed tokens already accepted by the JWT validator to lower precedence validators such as the OpenID provider UserInfo endpoint validator. Lower precedence validators are now only invoked once every preceding validator rejected the token. When the request carries several tokens, for example in a header and a cookie, they are likewise validated one at a time in the order the token readers resolve them.
IpPatternsRule no longer compiles every entry of micronaut.security.ip-patterns as a regular expression. An entry made only of hexadecimal digits, dots, colons and (for example 127.0.0.1 or 192.168.1.) is now an IP wildcard whose dots and colons match literally. Previously 192.168.1. was the regular expression 192.168.1., which also admitted 192.168.10.5 or 192.168.100.5. Entries containing any other character (for example 192\.168\.1\.\d+), and entries starting with a dot (for example the "allow all" regular expression .), keep being compiled as regular expressions. A in the middle of a wildcard matches within a single address segment (192.168..1 does not match 192.168.2.3.1), while a trailing matches the rest of the address. To allow every address use 0.0.0.0, or ..
CsrfTokenValidator no longer falls through to another CsrfTokenRepository when the token found in a repository does not match the token supplied in the request. Repositories are consulted following their Ordered order and the first repository holding a CSRF token for the request is authoritative. SessionCsrfTokenRepository now runs before CookieCsrfTokenRepository: with Session-Based Authentication, a request carrying an HTTP session which holds a CSRF token is only accepted when the supplied token matches the session token; a CSRF cookie does not replace it.
DefaultOpenIdAuthenticationMapper qualifies the username with the provider name when more than one enabled OAuth 2.0 client, other than client-credentials-only clients, is configured under micronaut.security.oauth2.clients: Authentication.getName() is <provider name>:<sub> instead of <sub>, so that the same subject at two providers never maps to one user. With a single client the username remains the sub claim. The unqualified subject is kept in the sub attribute. The username of authentications created from an ID token with micronaut.security.authentication set to idtoken is not qualified. Applications with several clients which key data on the username must migrate those keys, or set micronaut.security.oauth2.openid.qualify-username-with-provider to false to restore the previous (unsafe) behavior. See User Details Mapping.
JWTClaimsSetGenerator now writes the sub claim after the authentication attributes, so the sub claim of a generated JWT is always Authentication.getName(). Previously an authentication attribute named sub replaced the principal name in the token, which turned a provider-qualified username back into the bare subject on every later request.
The constructor DefaultOpenIdAuthenticationMapper(OpenIdAdditionalClaimsConfiguration, AuthenticationModeConfiguration) has been deprecated. Use DefaultOpenIdAuthenticationMapper(OpenIdAdditionalClaimsConfiguration, AuthenticationModeConfiguration, OpenIdConfiguration, Collection<OauthClientConfiguration>) instead.
Starting with 5.5.2, micronaut.security.token.jwt.signatures.jwks.*.key-type is applied again when verifying token signatures with a remote JSON Web Key Set. Since 3.11.0 the setting had no effect: a token signed with a key of any type in the JWKS was accepted. A JWKS configured with a key-type now only verifies tokens signed with a key of that type. The setting no longer defaults to RSA; unless it is configured, keys of any type are matched, which preserves the previous behavior for applications that do not set it. JwksSignatureConfigurationProperties.DEFAULT_KEYTYPE is deprecated, and JwksSignatureConfiguration.getKeyType() returns null for a JWKS without a configured key-type. The key-type value is case-insensitive and must be one of RSA, EC, OKP or oct; any other value now fails application startup with a ConfigurationException. A key published in the JWKS with an explicit alg is only used to verify tokens whose header declares that algorithm; keys without alg match any algorithm.
AbstractEndSessionRequest no longer expands the OpenID provider end session URL as a URI template. The logout parameters are percent-encoded and appended to the query component of the provider URL, preserving any query component it already has. If the provider URL is empty or not a valid URI, getUrl(HttpRequest, Authentication) returns null and /oauth/logout does not redirect, instead of throwing or redirecting to a malformed URL. The provider URL must be an absolute http or https URL with a host and without user information: a relative URL, another scheme, an empty or non-ASCII host, or https://user:password@provider.example/logout now results in this 404 response instead of being passed through. So does a provider URL that is not a strict RFC 3986 URI, for example one with an unencoded space or { in its path. Characters such as { or non-ASCII in the query component of the provider URL are percent-encoded, and a ; in it is treated as a parameter separator.
A failed retrieval of a remote JSON Web Key Set (connection error, non-2xx response, unparseable body or a JWK Set without keys) is no longer retried for every token. The JWK Set is not requested again until the back-off configured with micronaut.security.token.jwt.signatures.jwks-client.failure-backoff (default 10 seconds) elapses; tokens which cannot be verified by another signature configuration are rejected meanwhile. Set the property to 0s to restore the previous behavior. Concurrent requests share one retrieval per signature configuration and url, bounded by micronaut.security.token.jwt.signatures.jwks-client.retrieval-timeout (default 30 seconds); a retrieval which exceeds it is treated as a failure.
JwkSetFetcherclearCache(url) now also evicts the JWK Set cached by the caching implementations (the Reactor based one evicts the entries for that url; the Micronaut Cache based one evicts the whole jwks cache, since its entries are keyed by provider name and url) in addition to the AOT optimization and the failure back-off.
The constructor DefaultJwkSetFetcher(JwksClient) has been deprecated. Use DefaultJwkSetFetcher(JwksClient, JwksClientConfiguration) instead.
CookiePriorToLoginPersistence only stores the path and query of the request rejected prior to login, and only honours a local path (one starting with a single /) when redirecting after login. Scheme-relative (//host/…) or absolute URIs are ignored and the login handlers fall back to micronaut.security.redirect.login-success.
The plain OAuth 2.0 client (DefaultOauthClient) now sends the application’s own callback URL, built with OauthRouteUrlBuilder, as the redirect_uri parameter of the authorization code grant token request. Previously the value stored in the state parameter of the authorization response was used, which allowed anyone redirecting the browser to the callback endpoint to choose the redirect_uri sent to the provider and redeem an authorization code issued for a different redirection URI (RFC 6749 sections 4.1.3 and 10.6). The OpenID Connect client already behaved this way.
The constructor DefaultOauthAuthorizationResponseHandler(TokenEndpointClient, StateValidator, PkcePersistence) has been deprecated. Use DefaultOauthAuthorizationResponseHandler(TokenEndpointClient, OauthRouteUrlBuilder, StateValidator, PkcePersistence) instead.
The constructor OauthCodeTokenRequestContext(AuthorizationResponse, SecureEndpoint, OauthClientConfiguration, String) has been deprecated. Use OauthCodeTokenRequestContext(AuthorizationResponse, OauthRouteUrlBuilder, SecureEndpoint, OauthClientConfiguration, String) instead. A context created with the deprecated constructor no longer sends a redirect_uri parameter to the token endpoint.
Starting with 5.5.2, the JSON Web Key Set published at the jwks_uri of an OpenID provider is registered as a signature configuration for request tokens only when micronaut.security.authentication is set to idtoken, as it was before Micronaut Security 4.8.0. In cookie, session and bearer modes, or when the authentication mode is not set, tokens signed by the provider’s keys, such as ID tokens issued to other clients, no longer authenticate requests. Applications that must accept the provider’s tokens as request credentials in those modes need to configure the JWKS explicitly with micronaut.security.token.jwt.signatures.jwks.*.
The ID token returned by the token endpoint during the authorization code flow is verified exclusively against the issuing provider’s JWKS. It is no longer accepted when signed by any other signature configuration of the application.
Single-valued keys directly under micronaut.security.ldap, such as the global switch micronaut.security.ldap.enabled, no longer create an LdapConfiguration named after the key. Previously micronaut.security.ldap.enabled: true created a configuration and an LdapAuthenticationProvider named enabled with no server, whose failures turned login attempts for unknown usernames into HTTP 500 responses and allowed username enumeration. Only keys with nested properties, for example micronaut.security.ldap.default.*, define LDAP configurations.
The HTTP clients Micronaut Security creates to talk to an identity provider (token endpoint, OpenID provider metadata discovery, UserInfo endpoint and JWK Set retrieval) no longer follow redirects, regardless of micronaut.http.client.follow-redirects. A redirect returned by the provider is never followed, so the request fails instead of reaching the redirect target. An HttpClient bean named after an OAuth 2.0 provider is no longer used to call its token endpoint: a client that never follows redirects is created from the service configuration micronaut.http.services.<provider>.*, or from the default client configuration, instead. See HTTP Clients for the Provider.
The constructor OpenIdProviderMetadataFetcherFactory() has been replaced by OpenIdProviderMetadataFetcherFactory(BeanContext, HttpClientConfiguration) and the factory method createOpenIdProviderMetadataFetcher(OpenIdClientConfiguration, HttpClient) by createOpenIdProviderMetadataFetcher(OpenIdClientConfiguration). The class is internal API.
Starting with 5.5.2, the JSON Web Key Set registered for the jwks_uri of an OpenID client is bound to the issuer of that client (the issuer asserted by the provider metadata or, if it asserts none, micronaut.security.oauth2.clients..openid.issuer). Tokens whose iss claim is not equal to the issuer (tolerating only the case of the scheme and a trailing slash), or that have no or an empty iss claim, are no longer verified with the keys of that provider, even if their signature validates against one of them. This prevents a key trusted for one provider from signing tokens as another provider. Applications that must verify tokens of a different issuer with a provider’s keys need to configure the JWKS explicitly with micronaut.security.token.jwt.signatures.jwks..url, optionally bound to the expected issuer with micronaut.security.token.jwt.signatures.jwks.*.issuer.
LdapAuthenticationProvider no longer returns AuthenticationFailureReason.USER_NOT_FOUND when the username does not match any directory entry. It returns CREDENTIALS_DO_NOT_MATCH, the same reason as for a wrong password, and attempts a bind against a decoy DN (a random non-existent entry under the search base, or the entry configured with micronaut.security.ldap.*.search.decoy-dn) so that unknown usernames cannot be enumerated through the failure message and the response-time difference is narrowed. Only the client-side cost is equalised by default; see the LDAP section for configuring a decoy account where directory-side timing matters.
The Authentication created by the UserInfo endpoint token validator is bound to the provider which answered. The attribute oauth2Provider is always set to the provider name, and when micronaut.security.oauth2.openid.qualify-username-with-provider is true, or it is not set and more than one enabled OAuth 2.0 client is configured under micronaut.security.oauth2.clients, the username is <provider name>:<sub> instead of <sub>, so that the same subject at two providers never maps to one user. Applications with several clients which key data on Authentication.getName() for UserInfo-validated requests must migrate those keys. Client names under micronaut.security.oauth2.clients containing : are not supported by the configuration binding, and the UserInfo validator additionally rejects them with a ConfigurationException when usernames are qualified, since they would make the qualified name ambiguous. See the UserInfo Endpoint section.
With micronaut.security.authentication set to idtoken, OktaEndSessionEndpoint (used for Okta and Oracle Cloud) only sends as id_token_hint the token which authenticated the request, as recorded in the SecurityContext. Previously, it sent the first token found in the request, which could be an unrelated Authorization: Bearer header added by a gateway rather than the ID token cookie. If no token authenticated the request and the authentication has no openIdToken attribute, no id_token_hint is sent.
Starting with 5.5.2, IssuerClaimValidator requires the iss claim of an ID token to match the issuer expected for the OpenID client in addition to the Issuer Identifier of the provider metadata. The expected issuer is micronaut.security.oauth2.clients..openid.issuer, or micronaut.security.oauth2.clients..openid.issuer-identifier when set. The comparison is exact, tolerating only the case of the scheme and a trailing slash. Moreover, an issuer announced in the provider’s discovery document that does not match the expected issuer is discarded (an error is logged) and the expected issuer is used instead, as required by OpenID Connect Discovery 1.0 section 4.3. ID tokens whose iss claim only matched the issuer announced by the provider are now rejected. If the provider issues tokens with an iss that differs from the URL used to fetch the discovery document (for example, discovery over a cluster-internal URL, or Oracle IDCS with a tenant specific issuer and the provider wide issuer https://identity.oraclecloud.com/), set micronaut.security.oauth2.clients.*.openid.issuer-identifier to the expected iss value.
Micronaut Security 5.4 breaking changes
SessionLoginHandler issues a new session on successful login instead of reusing the session present in the request. Attributes of the previous session are migrated to the new session and the previous session is deleted from the session store.
SessionLogoutHandler deletes the session from the session store and expires the session cookie on logout instead of only removing the authentication from the session.
The constructor SessionLogoutHandler(RedirectConfiguration, RedirectService) has been deprecated. Use SessionLogoutHandler(RedirectConfiguration, RedirectService, SessionStore, List<HttpSessionIdEncoder>) instead.
Micronaut Security 5.0 breaking changes
The JSR 250 annotation mappers have been moved to a new module micronaut-security-processor.
If you are using the @RolesAllowed, @PermitAll or @DenyAll annotations, you will need to replace the micronaut-security-annotations dependency with micronaut-security-processor in your project.
Deprecations
The Singleton constructor io.micronaut.security.token.jwt.validator.JwtTokenValidator(Collection<SignatureConfiguration>, Collection<EncryptionConfiguration>,
Collection<GenericJwtClaimsValidator>, JwtAuthenticationFactory) deprecated previously has been removed.
JwtTokenValidator(Collection<SignatureConfiguration>, Collection<EncryptionConfiguration>, Collection<GenericJwtClaimsValidator>, JwtAuthenticationFactory, ExecutorService) is used instead.
The following methods in io.micronaut.security.oauth2.client.DefaultOpenIdProviderMetadata deprecated previously have been removed. Note that the Open ID provider name is now required in all cases:
Constructor DefaultOpenIdProviderMetadata().
Use DefaultOpenIdProviderMetadata(String) instead.
Static method Builder builder().
Use DefaultOpenIdProviderMetadata(String) instead
Nested constructor DefaultOpenIdProviderMetadata.Builder().
Use DefaultOpenIdProviderMetadata.Builder(String) instead
The Singleton constructor io.micronaut.security.oauth2.endpoint.authorization.response.DefaultOpenIdAuthorizationResponseHandler(OpenIdTokenResponseValidator, OpenIdAuthenticationMapper, TokenEndpointClient, OauthRouteUrlBuilder<T>, StateValidator, PkcePersistence) deprecated previously has been removed.
DefaultOpenIdAuthorizationResponseHandler(OpenIdTokenResponseValidator, OpenIdAuthenticationMapper, TokenEndpointClient, OauthRouteUrlBuilder<T>, StateValidator, PkcePersistence), ExecutorService) is used instead.
Micronaut Security 4.0 breaking changes
SecurityRulecheck method no longer contains the argument RouteMatch. You can easily retrieve a RouteMatch
with the HttpRequest method argument with request.getAttribute(HttpAttributes.ROUTE_MATCH).orElse(null).
For applications with micronaut.security.authentication set to cookie and micronaut.security.redirect.enabled set to false, the server responds with 401 HTTP Status code instead of 200 for login failed attempts.
micronaut.security.intercept-url-map-prepend-pattern-with-context-path defaults to true. Thus intercept url patterns are be prepended with the server context path if it is set.
Micronaut Security APIs have been decoupled from HTTP. Many APIs now have generics instead of HTTP-related types such as HttpRequest.
For example, instead of AuthenticationProvider, you should use AuthenticationProvider<HttpRequest<?>>.
The mappers for javax.annotation.security annotations – DenyAll, PermitAll, RolesAllowed – have been removed. Use the Jakarta versions for jakarta.annotation.security annotations instead.
The return type of the OpenIdAuthenticationMapper.createAuthenticationResponse has changed to return a Publisher to be consistent with the OauthAuthenticationMapper interface. Because the method now returns a Publisher, blocking operations can be offloaded to another thread pool using the reactive streams implementation of your choice.
Micronaut Security 3.4 breaking changes
Sensitive endpoints will now respond with an error unless a replacement for the SensitiveEndpointRule is bound.
The following code snippet illustrates how to restore the previous functionality:
The previous functionality allows any authenticated user, no matter their role to view sensitive endpoints.
The AuthenticationUserDetailsAdapter class has been deleted.
SecurityRule Changes
The SecurityRule API has changed. The last argument to the method was a map that represented the user attributes. Instead that argument was replaced with a reference to the Authentication. This has the benefit of rules now having access to the username of the logged in user as well as access to the convenience method getRoles().
In addition, the return type of the method has changed to return a Publisher. This was necessary because the security rules execute as part of the security filter which may be on a non blocking thread. Because the method now returns a Publisher, blocking operations can be offloaded to another thread pool using the reactive streams implementation of your choice.
The RolesFinder method findInClaims has been deprecated and usages should be replaced with resolveRoles(@Nullable Map<String, Object> attributes).
5 Installation
Using the CLI
If you are creating your project using the Micronaut CLI, supply either security,security-jwt or security-session features configure the security support in your project:
$ mn create-app my-app --features security
To use the Micronaut’s security capabilities you must have the security dependency on your classpath:
The micronaut-security-processor dependency is only required to use JSR 250 annotations
By default Micronaut returns HTTP Status Unauthorized (401) for any endpoint invocation. Routes must be explicitly allowed through the provided mechanisms.
For each request, the filter evaluates the request against the beans of type AuthenticationFetcher. Fetchers are consulted sequentially in their Ordered precedence, and the first one to emit an Authentication wins; fetchers of lower precedence are not invoked once an authentication has been resolved.
A custom AuthenticationFetcher must return a publisher that either emits a single Authentication or completes empty. When using Mono.create, emit only one terminal signal.
Then, the optional authentication is evaluated against every bean of type SecurityRule to determine if the request is authorized. If not authorized, an AuthorizationException is thrown.
6.1 Built-In Authentication Fetchers
You can write your own bean of type AuthenticationFetcher. However, Micronaut Security ships with several built-in authentication fetchers:
It parses the credentials from an HTTP Request, which uses Basic Authentication. Then, it invokes every Authentication Provider using the parsed credentials.
The TokenValidator beans are consulted sequentially, in order. The first validator which authenticates the token wins, and the token is not handed to the remaining validators. A validator is only consulted once every validator preceding it has rejected the token.
Give validators which send the token to a remote service, such as the UserInfo endpoint token validator, the lowest precedence. That way they only receive tokens which no local validator (for example the JWT validator) accepted.
6.1.2.1 Token Readers
You can write your own bean of type TokenReader. However, Micronaut Security ships with several built-in beans of type TokenReader.
Whether the cookie is a session cookie. A session cookie does not have an expiration date. cookie-max-age is ignored if session cookie is set to true. Default value (false).
micronaut.security.token.cookie.cookie-domain
java.lang.String
Sets the domain name of this Cookie.
micronaut.security.token.cookie.cookie-http-only
java.lang.Boolean
Whether the Cookie can only be accessed via HTTP. Default value ({@value #DEFAULT_HTTPONLY}).
micronaut.security.token.cookie.cookie-secure
java.lang.Boolean
Sets whether the cookie is secured. Defaults to the secure status of the request.
Behind a TLS-terminating proxy, set this explicitly to true. With the Netty server, forwarded headers do not change the secure status of the request.
Sets the same-site setting of the cookie. Default value Lax. Allowed values: Strict, Lax or None. An empty or unrecognized value omits the SameSite attribute.
micronaut.security.token.cookie.enabled
boolean
Sets whether JWT cookie configuration is enabled. Default value (true).
micronaut.security.token.cookie.cookie-name
java.lang.String
Cookie Name. Default value ("JWT").
micronaut.security.token.cookie.cookie-path
java.lang.String
Sets the path of the cookie. Default value ("/").
6.2 Security Rules
The decision to allow access to a particular endpoint to anonymous or authenticated users is determined by a collection of
Security Rules which are executed from the SecurityFilter. Micronaut ships with several built-in security rules. If they don’t fulfil your needs,
you can implement your own SecurityRule.
Security rules return a publisher that should emit a single SecurityRuleResult. See the following table for a description of each result.
The rule doesn’t apply to the request resource, or it cannot be determined either way. This result will cause other security rules to be considered.
If all security rules return UNKNOWN, the request will be rejected!
SecurityFilter evaluates security rules in order. The remaining rules are not evaluated once a rule returns ALLOWED or REJECTED.
Security rules implement the ordered interface and so all of the existing rules have a static variable ORDER that stores the order of that rule. The rules they are executed in order from lower to higher values. You can use those variables to place your custom rule before or after any of the existing rules.
In the following table you can find the order and a short description of the behavior of built-in security rules. You can find more details about theese rules in their own guide sections.
Do not execute any blocking operations in the rule implementation without offloading those operations to another thread pool.
Since version 2.5, the Micronaut Framework executes the filters and then it reads the HTTP Request’s body.
SecurityFilter evaluates the beans of type SecurityRule.
Because of that, SecurityRule cannot rely on HTTP Request’s body because the Micronaut Framework has not read the body yet.
6.2.1 IP Pattern Rule
When you turn on security, traffic coming from any ip address is allowed by default.
You can however reject traffic not coming from a white list of IP Patterns as illustrated below:
In the previous code, the IpPatternsRule rejects traffic not coming
either 127.0.0.1 or 192.168.1.* range.
Each entry of micronaut.security.ip-patterns is interpreted in one of two ways:
A pattern made only of hexadecimal digits, dots, colons and (for example 127.0.0.1, 192.168.1. or fe80:*) is an IP wildcard. Dots and colons match literally. A inside the pattern matches within one address segment (192.168..1 matches 192.168.2.1 but not 192.168.2.3.1), and a trailing matches the rest of the address, so 192.168.1. matches 192.168.1.0 to 192.168.1.255 and does not match 192.168.10.5. Hexadecimal digits match regardless of case, so FE80:* and fe80:* are equivalent.
Any other pattern (for example 192\.168\.1\.\d+ or ^10\.0\.(1|2)\.[0-9]{1,3}$) is compiled as a Java regular expression that must match the whole remote host address. Escape dots as \. in regular expressions; an unescaped dot matches any character. A pattern that contains 192.168.1. together with other characters (for example 192.168.1.|10.0.0.1) is a regular expression, not a wildcard. A pattern starting with a dot, such as .*, is always a regular expression.
The special value 0.0.0.0 (the default) matches every address; and the regular expression . do too.
The address compared is the one returned by HttpRequest#getRemoteAddress(), the TCP peer, so behind a proxy or load balancer it is the proxy’s address (X-Forwarded-For is not consulted). IPv6 addresses are compared in their uncompressed form (0:0:0:0:0:0:0:1, not ::1).
The IP patterns rule never explicitly allows requests, it only rejects requests if the address does not match. There must be other security rules that determine whether a resource should be accessed.
If the desired behavior is to allow access to all resources as long as the address matches, create a security rule that executes after this one that returns ALLOWED.
6.2.2 Secured Annotation
As illustrated below, you can use the @Secured annotation to control
access to controllers or controller methods.
import io.micronaut.http.MediaType;
import io.micronaut.http.annotation.Controller;
import io.micronaut.http.annotation.Get;
import io.micronaut.http.annotation.Produces;
import io.micronaut.security.annotation.Secured;
import io.micronaut.security.authentication.Authentication;
import io.micronaut.security.rules.SecurityRule;
@Controller("/example")
@Secured(SecurityRule.IS_AUTHENTICATED) // (1)
public class ExampleController {
@Produces(MediaType.TEXT_PLAIN)
@Get("/admin")
@Secured({"ROLE_ADMIN", "ROLE_X"}) // (2)
public String withroles() {
return "You have ROLE_ADMIN or ROLE_X roles";
}
@Produces(MediaType.TEXT_PLAIN)
@Get("/anonymous")
@Secured(SecurityRule.IS_ANONYMOUS) // (3)
public String anonymous() {
return "You are anonymous";
}
@Produces(MediaType.TEXT_PLAIN)
@Get("/authenticated") // (1)
public String authenticated(Authentication authentication) {
return authentication.getName() + " is authenticated";
}
}
from micronaut.http import MediaType
from micronaut.http.annotation import Controller, Get, Produces
from micronaut.security.annotation import Secured
from micronaut.security.authentication import Authentication
from micronaut.security.rules import SecurityRule
@Controller("/example")
@Secured(SecurityRule.IS_AUTHENTICATED) # (1)
class ExampleController:
@Produces(MediaType.TEXT_PLAIN)
@Get("/admin")
@Secured(["ROLE_ADMIN", "ROLE_X"]) # (2)
def withroles(self) -> str:
return "You have ROLE_ADMIN or ROLE_X roles"
@Produces(MediaType.TEXT_PLAIN)
@Get("/anonymous")
@Secured(SecurityRule.IS_ANONYMOUS) # (3)
def anonymous(self) -> str:
return "You are anonymous"
@Produces(MediaType.TEXT_PLAIN)
@Get("/authenticated") # (1)
def authenticated(self, authentication: Authentication) -> str:
return authentication.getName() + " is authenticated"
import io.micronaut.http.MediaType
import io.micronaut.http.annotation.Controller
import io.micronaut.http.annotation.Get
import io.micronaut.http.annotation.Produces
import io.micronaut.security.annotation.Secured
import io.micronaut.security.authentication.Authentication
import io.micronaut.security.rules.SecurityRule
@Controller("/example")
@Secured(SecurityRule.IS_AUTHENTICATED) // (1)
class ExampleController {
@Produces(MediaType.TEXT_PLAIN)
@Get("/admin")
@Secured("ROLE_ADMIN", "ROLE_X") // (2)
fun withroles(): String = "You have ROLE_ADMIN or ROLE_X roles"
@Produces(MediaType.TEXT_PLAIN)
@Get("/anonymous")
@Secured(SecurityRule.IS_ANONYMOUS) // (3)
fun anonymous(): String = "You are anonymous"
@Produces(MediaType.TEXT_PLAIN)
@Get("/authenticated") // (1)
fun authenticated(authentication: Authentication): String = "${authentication.name} is authenticated"
}
Users granted role ROLE_ADMIN or ROLE_X roles can access withroles Controller’s action.
2
Anonymous users (authenticated and not authenticated users) can access anonymous Controller’s action.
The use of JSR 250 annotations requires io.micronaut.security:micronaut-security-processor to be in the annotation processor classpath (annotationProcessor, kapt, compileOnly) respectively for Java, Kotlin, Groovy.
When the @Secured annotation has a set of roles, the SecuredAnnotationRule grants access to a user if they have any of the roles.
Don’t use both annotations, @Secured and @RolesAllowed, in the same method. If you use it, the first occurrence (either @RolesAllowed or @Secured) is used. The other annotation is ignored.
6.2.2.2 Secured with expressions
In combination with @Secured, you can use expressions, introduced in Micronaut Framework 4.0, to access the authenticated user:
@Controller("/authenticated")
public class ExampleController {
@Secured("#{ user?.attributes?.get('email') == 'sherlock@micronaut.example' }")
@Produces(MediaType.TEXT_PLAIN)
@Get("/email")
public String authenticationByEmail(Principal principal) {
return principal.getName() + " is authenticated";
}
}
user is null for anonymous requests. A request is allowed only if the expression evaluates to true. If the expression evaluates to false or to null, for example because it navigates the user with user?. and no user is authenticated, the request is rejected. Later security rules, such as an intercept URL map entry, do not get the chance to allow it.
6.2.3 Intercept URL Map
Moreover, you can configure endpoint authentication and authorization access with an Intercept URL Map:
pattern /images/* enables access to authenticated and not authenticated users
pattern /books enables access for everyone authenticated
pattern /books/grails enables access for users who are granted any of the specified roles.
As you see in the previous code listing, any endpoint is identified by a combination of pattern
and an optional HTTP method.
If a given request URI matches more than one intercept url map, the one that specifies an http method that matches the request method will be used. If there are multiple mappings that do not specify a method and match the request URI, then the first mapping will be used. For example:
The example below defines that all HTTP requests to URIs matching the pattern /v1/myResource/** and using HTTP method GET will be accessible to everyone. Requests matching the same URI pattern but using a different HTTP method than GET require fully authenticated access.
accessing /v1/myResource/** with a GET request does not require authentication
accessing /v1/myResource/** with a request that isn’t GET requires authentication
Patterns are matched against the request path the router uses to select a route: the percent-encoded path, with each segment decoded. A segment is kept percent-encoded if decoding it would introduce a slash or leave it blank. Thus, a path variable such as x%2Fy or %20 cannot skip a fixed-depth pattern such as /admin/*.
When micronaut.server.context-path is set, the patterns are prepended with the context path by default (see micronaut.security.intercept-url-map-prepend-pattern-with-context-path). Requests for the context root, for example /context and /context/, are matched as the root path / is matched when no context path is set. Thus, root patterns such as / or /* keep protecting the application’s root route.
When the @Secured annotation has a set of roles, the SecuredAnnotationRule grants access to a user if they have any of the roles.
6.2.4 Built-In Endpoints Security
When you turn on security, Built-in endpoints are secured depending on their sensitive value.
the /info endpoint is open for unauthenticated access
You need to replace the default implementation SensitiveEndpointRule and implement SensitiveEndpointRule::checkSensitiveAuthenticated to allow authenticated users access to sensitive endpoints. For example, you may want to restrict access to users with a specific role:
@RunAs(
name = "aegon",
roles = ["TARGARYEN"],
attributes = [
Attribute(key = "family_name", value = "Targaryen"),
Attribute(key = "given_name", value = "Aegon")
]
)
@Singleton
open class RunAsService {
open fun changeAuth(): Authentication? = SecurityContextHolder.getSecurityContext().authentication
}
@RunAs(
name = "aegon",
roles = ["TARGARYEN"],
attributes = [
@Attribute(key = "family_name", value = "Targaryen"),
@Attribute(key = "given_name", value = "Aegon")
]
)
@Singleton
class RunAsService {
Authentication changeAuth() {
SecurityContextHolder.securityContext.authentication
}
}
Micronaut Security builds an Authentication from @RunAs and sets it in the current security context for the invocation.
For synchronous methods, Micronaut Security restores the previous authentication when the method returns.
For asynchronous methods (for example, CompletionStage and reactive return types), Micronaut Security restores the previous authentication when the asynchronous result completes.
The annotation does not authenticate the incoming request or permanently replace the caller’s identity.
By default, @RunAs appends the supplied roles and attributes to the current authentication.
The annotation value is an alias for roles, so @RunAs("ROLE_ADMIN") is equivalent to @RunAs(roles = "ROLE_ADMIN").
Set appendRoles or appendAttributes to false to replace the current values instead.
If name is omitted or blank and an authentication already exists, Micronaut Security keeps the current user name.
You can also use jakarta.annotation.security.RunAs; Micronaut Security maps it to @RunAs and uses the Jakarta annotation value as the run-as role.
The use of jakarta.annotation.security.RunAs requires io.micronaut.security:micronaut-security-processor to be in the annotation processor classpath (annotationProcessor, kapt, compileOnly) respectively for Java, Kotlin, Groovy.
One good use case is a bean with Scheduled methods. Because scheduled tasks do not run as part of an incoming authenticated request, @RunAs lets the scheduled job delegate to services that expect an authenticated user.
6.3 Static Resource Authentication Bypass
Resolving an Authentication can be expensive; for example, an AuthenticationFetcher may hit a database on every request. For static resources served anonymously, that work is wasted.
Set micronaut.security.filter.static-resource-authentication-bypass to true to skip every AuthenticationFetcher for requests which are served as anonymous static resources:
The bypass is disabled by default. When enabled, SecurityFilter skips authentication resolution only if all of the following hold:
The request method is GET or HEAD.
The request did not match a route. A route always takes precedence over a static resource, and routed requests are never bypassed.
The request path resolves to a static resource.
The first micronaut.security.intercept-url-map entry which applies to the request grants isAnonymous() access.
An explicit isAnonymous() intercept URL map entry is required. Without one, no request is bypassed.
Bypassing only skips authentication resolution. Every bean of type SecurityRule is still evaluated, so the request is authorized exactly as an anonymous request would be. Because the entry grants isAnonymous() access, the outcome cannot depend on who is making the request.
The rules are evaluated with a null authentication, and no Authentication is available for the rest of the filter chain. If your application defines a SecurityRule ordered before ConfigurationInterceptUrlMapRule, or a filter which reads the authentication for bypassed paths, it observes an anonymous request.
To decide which requests bypass authentication resolution yourself, replace the default implementation with your own bean of type StaticResourceAuthenticationBypass. The configuration property must still be set to true.
You may need to replace some of those beans to customize Micronaut Security exception handling to your needs.
8 Endpoints
The Security Filter section describes how for each request an Authentication maybe resolved. It maybe a token placed in an HTTP Header, in a cookie, or an HTTP session.
How do you obtain such a token or how is the user saved into the HTTP Session in the first place?. In a Micronaut application, you can expose the LoginController.
8.1 Login Controller
To enable the LoginController, you need to have a bean of type LoginHandler. A custom implementation can, of course, be provided. However, several Login Handlers implementations are available out of the box.
Status code for unsupported content type. Default to 404
micronaut.security.endpoints.login.enabled
boolean
Enables the controller.
micronaut.security.endpoints.login.path
java.lang.String
Path to the controller.
8.1.1 Login Handler
The LoginHandler API defines how to respond to a successful or failed login attempt. For example, with the Login Controller or with OAuth 2.0 support.
8.2 Logout Controller
To enable the logout controller you need a bean of type LogoutHandler. The behaviour of the controller is delegated to it.
A custom implementation can, of course, be provided. However, several Logout Handlers implementations are available out of the box.
Enables HTTP GET invocations of LogoutController. Default value (false).
If you are using JWT authentication not stored in a cookie, you may not need to invoke the /logout endpoint. Since logging out normally means simply deleting the JWT token in the client.
You can provide your own implementations of LoginHandler and LogoutHandler.
However, Micronaut security modules ship with several implementations which you can enable by setting the configuration micronaut.security.authentication
When you set micronaut.security.authentication=idtoken, IdTokenLoginHandler a bean of type LoginHandler and JwtCookieClearerLogoutHandler a bean of type LogoutHandler are enabled. Additionally, a ReactiveJwksSignature bean is registered for the jwks_uri of each OpenID provider, so ID tokens issued by the provider can be used as request credentials, and IdTokenClaimsValidator verifies that they were issued to this client. Only enabled OAuth 2.0 clients are considered. A disabled client contributes no provider metadata and no JWKS, but that removes only its own trust: when several clients share the same OpenID provider, only IdTokenClaimsValidator checks that the aud claim names an enabled client, so disabling it with micronaut.security.token.jwt.claims-validators.openid-idtoken: false lets a token issued to a disabled client authenticate through the signing keys of an enabled sibling. ID token authentication never accepts unsigned JWTs: even when every OAuth 2.0 client is disabled, or none is configured, and therefore no JWKS is registered, a token without a signature is rejected.
The iss claim of such a token must be identical to the expected issuer of an OpenID client: micronaut.security.oauth2.clients..openid.issuer-identifier if set, otherwise micronaut.security.oauth2.clients..openid.issuer. Only the case of the scheme and a trailing slash are tolerated; the scheme, host, port and path must match. The same expected issuer is used by ProviderResolver to resolve the OpenID client of a token from its iss claim.
9 Security Configuration
The following global configuration options are available:
Defines which authentication to use. Defaults to null. Possible values bearer, session, cookie, idtoken. Should
only be supplied if the service handles login and logout requests.
micronaut.security.enabled
boolean
If Security is enabled. Default value true
micronaut.security.intercept-url-map
java.util.List
Map that defines the interception patterns.
micronaut.security.ip-patterns
java.util.List
Allowed IP patterns. Default value (["0.0.0.0"]). A pattern made only of hexadecimal digits, dots, colons
and {@code } (e.g. {@code 192.168.1.}) is an IP wildcard whose dots and colons match literally; any other pattern
is a regular expression matched against the whole host address.
Determines how authentication providers should be processed. Default value ANY. Possible values: ANY or ALL.
micronaut.security.reject-not-found
boolean
Whether the server should respond with 401 for requests that do not match any routes on the server, if you set it to false, it will return 404 for requests that do not match any routes on the server. Default value (true).
9.1 Reject Not Found Routes
By default, when you include Micronaut security the app returns 401 or 403 even for non existing routes. The behavior prevents attackers from discovering what endpoints are available in your application. However, if you wish to return 404 for non found routes you can set micronaut.security.reject-not-found: false in your configuration.
9.2 Authentication Strategy
By default, Micronaut requires just one Authentication Provider to return a successful authentication response. You can set micronaut.security.authentication-provider-strategy: ALL to require all AuthenticationProviders to return a successful authentication response.
9.3 Handlers without redirection
Some built-in handlers respond with a 303 (See other) response to the urls defined in the Redirection Configuration
If you disable redirection configuration with by setting micronaut.security.redirect.enabled to false, these handlers respond with 200 responses instead.
9.4 Redirection Configuration
Several security flows (e.g. session based authentication, Cookie Token authentication) may involve redirection after the user logs in.
You can configure the redirection destinations with:
Where the user is redirected to after a successful login. Default value ("/").
micronaut.security.redirect.login-failure
java.lang.String
Where the user is redirected to after a failed login. Default value ("/").
micronaut.security.redirect.logout
java.lang.String
URL where the user is redirected after logout. Default value ("/").
micronaut.security.redirect.prior-to-login
boolean
If true, the user should be redirected back to the unauthorized
request that initiated the login flow. Supersedes the <code>login-success</code>
configuration for those cases. Default value false.
micronaut.security.redirect.enabled
boolean
Sets whether Redirection configuration enabled. Default value (true).
Where the user is redirected to after trying to access a secured route. Default value ("/").
micronaut.security.redirect.unauthorized.enabled
boolean
Whether it should redirect on unauthorized rejections. Default value (true).
Use the API RedirectService, which prepends the context path, if defined, to the redirect URLs.
Redirecting to the URI requested prior to login
When micronaut.security.redirect.prior-to-login is true, CookiePriorToLoginPersistence stores the URI of the request that was rejected as unauthorized in an ORIGINAL_URI cookie and the login handlers redirect to it after a successful login instead of to login-success.
To prevent an open redirect (CWE-601), only the path and query of the unauthorized request are stored, and only a local path, one that starts with a single /, is honoured when the cookie is read back. A request line such as GET ///evil.example/x, which browsers would follow as a scheme-relative URL to another host, or a planted cookie carrying an absolute or scheme-relative URL, falls back to login-success.
If your implementation is blocking (e.g., you fetch the user credentials from a database in a blocking way to check against the supplied authentication request), implement the ExecutorAuthenticationProvider or HttpRequestExecutorAuthenticationProvider interface. Those APIs specify the executor name, by default TaskExecutors.BLOCKING, where the code gets executed to avoid blocking the main reactive flow.
10.2 Authentication Providers Use Cases
The built-in Login Controller uses every available authentication provider. The first provider that returns a successful authentication response will have its value used as the basis for the JWT token or session state.
Out-of-the-box, Micronaut supports RFC7617 which defines the "Basic" Hypertext Transfer Protocol (HTTP) authentication scheme, which transmits credentials as user-id/password pairs, encoded using Base64.
Basic authentication is enabled by default if you have any Authentication Provider. You can disable it by setting micronaut.security.basic-auth.enabled to false.
The following sequence illustrates the authentication flow:
Below is a sample of a cURL command using basic auth:
SessionLoginHandler issues a new session on every successful login. If the request already carries a session, its attributes are migrated to the new session and the previous session is deleted from the SessionStore. Renewing the session identifier when the privilege level changes protects against session fixation attacks.
SessionLogoutHandler deletes the session from the SessionStore and expires the session cookie on logout, so the session identifier cannot be reused after the user logs out.
These handlers return 303 responses to the urls defined in the Redirection Configuration. Disable redirection configuration with micronaut.security.redirect.enabled=false to respond with 200 responses instead.
11.3 JSON Web Token
The following configuration properties are available to customize token based authentication:
Sets whether the configuration is enabled. Default value true.
micronaut.security.token.roles-name
java.lang.String
Authentication attributes map key for the user’s roles. Default value "roles".
micronaut.security.token.name-key
java.lang.String
Authentication attributes map key for the user’s name. Default value "sub".
micronaut.security.token.roles-separator
java.lang.String
If the entry used for the roles in the Authentication attributes map is a String, you can use the separator to split its value into multiple roles. Default value DEFAULT_ROLES_SEPARATOR.
Micronaut ships with security capabilities based on Json Web Token (JWT).
JWT is an IETF standard which defines a secure way to encapsulate arbitrary data that can be sent over unsecure URL’s.
Using the CLI
If you are creating your project using the Micronaut CLI, supply the security-jwt feature to configure JWT support in your project:
$ mn create-app my-app --features security-jwt
To use the Micronaut’s JWT based authentication capabilities you must have the security-jwt dependency on your classpath. For example:
Depends on the algorithm specified on the header, it can be a digital signature of the base64-encoded header and claims, or an encryption of them.
11.3.1 Reading JWT Token
11.3.1.1 Bearer Token Reader
Micronaut supports the RFC 6750 Bearer Token specification for transmitting JWT tokens. The following sequence illustrates the RFC 6750 authentication flow:
The following configuration properties are available to customize how the Bearer Token will be read:
Set whether to enable bearer token authentication. Default value true.
micronaut.security.token.bearer.prefix
java.lang.String
Sets the prefix to use for the auth token. Default value Bearer.
micronaut.security.token.bearer.header-name
java.lang.String
Sets the header name to use. Default value Authorization.
micronaut.security.token.bearer.header-prefix
java.lang.String
Sending tokens in the request
The code snippet below illustrates how to send a JWT token in the Authorization request header, using the bearerAuth method from MutableHttpRequest method:
Accessing a protected resource using an Authorization request header
Whether the cookie is a session cookie. A session cookie does not have an expiration date. cookie-max-age is ignored if session cookie is set to true. Default value (false).
micronaut.security.token.cookie.cookie-domain
java.lang.String
Sets the domain name of this Cookie.
micronaut.security.token.cookie.cookie-http-only
java.lang.Boolean
Whether the Cookie can only be accessed via HTTP. Default value ({@value #DEFAULT_HTTPONLY}).
micronaut.security.token.cookie.cookie-secure
java.lang.Boolean
Sets whether the cookie is secured. Defaults to the secure status of the request.
Behind a TLS-terminating proxy, set this explicitly to true. With the Netty server, forwarded headers do not change the secure status of the request.
Sets the same-site setting of the cookie. Default value Lax. Allowed values: Strict, Lax or None. An empty or unrecognized value omits the SameSite attribute.
micronaut.security.token.cookie.enabled
boolean
Sets whether JWT cookie configuration is enabled. Default value (true).
Micronaut Security registers a primary composite mapper that delegates to every available AuthenticationMapper bean.
The first mapper that returns a non-null Authentication wins.
If a mapper cannot map the token, it should return null so that another mapper can try.
AuthenticationMapper extends Ordered, so you can control mapper precedence by overriding getOrder() or using Micronaut ordering annotations.
The micronaut-security-jwt module provides a mapper for JWT tokens parsed with Nimbus JOSE + JWT.
NOTE: This mapper only parses the token to extract claims; it does not validate signatures or claims. Validate tokens first (for example with JsonWebTokenValidator).
It maps the token subject claim to the authentication name, resolves roles with RolesFinder, and copies the OpenID Connect profile claims exposed by ProfileClaims into the authentication attributes.
Micronaut security capabilities use signed JWT’s as specified by the
JSON Web Signature specification.
Micronaut’s JWT validation supports multiple signature configurations. Thus, you can validate JSON Web tokens signed by different issuers in the same application.
JsonWebTokenSignatureValidator validates the signature using beans of type SignatureConfiguration.
11.3.5.1 Remote JWKS
A JSON Web Key (JWK) is a JSON object that represents a cryptographic key. You can use a remote JWK Set, A JSON object that represents a set of JWKs, to validate JWT signatures.
You can configure a remote JWKS as a signature validator:
The previous snippet creates a ReactiveJwksSignature bean with a awscognito name qualifier.
If you have the Micronaut HTTP Client on the classpath, then it will be used to retrieve the remote JWK Set. This allows for the configuration settings of the HTTP Client to be applied when fetching the resource. If a service-specific client configuration (micronaut.http.services.<name>.) exists whose name matches the configured JWKS provider name, then a client created from that configuration (and its service url) will be used, otherwise a default HTTP Client instance (with any global configuration settings from micronaut.http.client. applied) will be used. If the Micronaut HTTP Client is not on the classpath, then the implementation will fall back to the internal resource fetching mechanism of the external JWT library dependency.
The default HTTP Client used to retrieve a remote JWK Set never follows redirects, regardless of micronaut.http.client.follow-redirects. A redirect to another address is treated as a failure to load the JWK Set. A named service-specific client configured for a JWKS provider (micronaut.http.services.<name>.*) only contributes its settings: redirects are never followed, even with follow-redirects: true. Client filters scoped to a service id (@Filter(serviceId = "<name>")) are not applied to the client that retrieves the JWK Set.
For example, to use an HTTP proxy for the fetching of the JWK Set from the above example:
Note that the same approach will be applied when using a jwks_uri supplied via Open ID Connect metadata. Such a JWKS is registered as a signature configuration for request tokens only when micronaut.security.authentication is set to idtoken.
Binding a JWKS to an issuer
When an application trusts the key sets of several identity providers, a key trusted for one provider must not be able to sign tokens that claim to be issued by another provider. A JWKS can be bound to an issuer with the issuer property. A bound JWKS only verifies tokens whose iss claim is equal to that issuer, tolerating only the case of the scheme and a trailing slash, the same comparison IssuerClaimValidator applies to ID tokens. A different scheme, suffixes, parent domains and an empty iss never match; tokens issued by anyone else, or without an iss claim, are not verified with its keys, even if their signature validates against one of them.
The JWKS created for the jwks_uri of an Open ID Connect client is always bound to the issuer of that client (the issuer asserted by the provider metadata or, if it asserts none, micronaut.security.oauth2.clients.*.openid.issuer). If neither openid.issuer is configured nor the provider metadata asserts an issuer (for example fetch-configuration: false with openid.jwks-uri), the JWKS is not bound and the application logs a warning at startup. Always set openid.issuer when several providers are trusted. A JWKS configured explicitly without an issuer verifies tokens regardless of their iss claim.
Restricting the key type
By default, every key of the JWKS is used to verify token signatures, whatever its type (kty). If the identity provider publishes keys of several types but tokens must only be accepted when signed with one of them, restrict the JWKS with the key-type property. Only keys of the configured type are then used to verify a token; a token signed with a key of another type is rejected, even if that key is part of the JWKS. The value is case-insensitive and must be RSA, EC, OKP or oct; any other value fails application startup.
The Micronaut HTTP Client based implementation can be explicitly disabled in favor of the JWT library’s internal resource fetching implementation by explicitly setting micronaut.security.token.jwt.signatures.jwks-client.http-client.enabled=false. For example:
Exposing your Application’s Json Web Key Set (JKWS)
If you want to expose your own JWK Set, read the Keys Controller section.
11.3.5.1.1 JWKS Caching
Json Web Key Set (JWKS) fetched from a remote web server are cached. By default, they are cached via the internal bean ReactorCacheJwkSetFetcher using
Project Reactor’s Mono::cacheInvalidateIf. You can configure the cache expiration with micronaut.security.token.jwt.signatures.jwks.*.cache-expiration. It defaults to 60 seconds.
However, we recommend you enable caching via Micronaut Cache. This will be the only option in the future.
If a remote JWK Set cannot be retrieved (for example, the connection is refused, the endpoint responds with a non-2xx status or the body cannot be parsed) or the retrieved JWK Set contains no keys, the JWK Set is not requested again until a back-off elapses. While the back-off lasts, tokens which cannot be verified by another signature configuration are rejected without contacting the JWKS endpoint. This prevents an unauthenticated client from triggering one outbound JWKS request (and one error log entry) per request while the authorization server is unavailable.
The back-off applies to every JwkSetFetcher implementation, including the Micronaut Cache based one. It is keyed by signature configuration name and JWKS url, since each configuration may use its own HTTP client settings, so a failure for one configuration does not prevent another configuration sharing the url from retrieving the JWK Set. You can configure its duration with:
failure-backoff defaults to 10 seconds. Set it to 0s to disable the back-off and retry the retrieval for every token.
Concurrent requests share one retrieval per signature configuration and url. retrieval-timeout (default 30 seconds) bounds that shared retrieval even when the JwksClient has no timeout of its own, so a retrieval which never completes does not block every token for that configuration. A retrieval which times out counts as a failure and starts the back-off. Set it to 0s to disable the timeout.
11.3.5.1.2 Local JWKS
You can specify a path starting with classpath: or file: to serve a JSON JWKS from anywhere on disk or in the classpath. For example to serve static resources from src/main/resources/jwks/certs.json, you would use classpath:jwks/certs.json as the path.
JsonWebTokenValidator will not use remote signature configuration. E.g. it will not validate the signature with remote JWKs.
Only, ReactiveJsonWebTokenValidator implements
TokenValidator.
11.3.7 JWT Token Generation
Micronaut relies on Nimbus JOSE + JWT library to provide JWT token signature and encryption.
The following configuration options are available:
Name the SignatureGeneratorConfiguration generator to make it participate in JWT token generation.
2
Register an additional bean of type RSASignatureGeneratorConfiguration which is injected here
11.3.8 JWT Encryption
Signed claims prevent an attacker from tampering with its contents to introduce malicious data or try a privilege escalation by adding more roles. However, the claims can be decoded just by using Base 64.
If the claims contain sensitive information, you can use a JSON Web Encryption algorithm to prevent them from being decoded.
The built-in JWTClaimsSetGenerator adds the aud claim when the application provides a bean of type ClaimsAudienceProvider.
The value returned by audience() is used as the JWT audience:
@Singleton
class CustomClaimsAudienceProvider implements ClaimsAudienceProvider {
private static final List<String> AUDIENCE = List.of("https://api.example.com");
@Override
public List<String> audience() {
return AUDIENCE;
}
}
@Singleton
class CustomClaimsAudienceProvider(ClaimsAudienceProvider):
def audience(self) -> list[str]:
return AUDIENCE
@Singleton
class CustomClaimsAudienceProvider : ClaimsAudienceProvider {
override fun audience(): List<String> = listOf("https://api.example.com")
}
@Singleton
class CustomClaimsAudienceProvider implements ClaimsAudienceProvider {
private static final ArrayList<String> AUDIENCE = ["https://api.example.com"]
@Override
List<String> audience() {
AUDIENCE
}
}
If another Micronaut application validates the generated JWT, configure the expected audience with micronaut.security.token.jwt.claims-validators.audience:
JWT iss claim matches the expected value. For an http:///https:// value, the claim must be equal to the configured issuer ignoring only the scheme and a single trailing slash; any other value is compared verbatim. Suffixes and parent domains are not accepted; configure the exact iss value of your tokens.
Enabled when the micronaut.security.token.jwt.claims-validators.issuer property is set.
Enabled by default. You can disable it by setting micronaut.security.token.jwt.claims-validators.subject-not-null to false.
If you are using micronaut.security.authentication: idtoken, IdTokenClaimsValidator, a bean of type GenericJwtClaimsValidator, is registered in the bean context as well. IdTokenClaimsValidator validates points 2-5 of the ID Token Validation section of the OpenID Connect Spec. Only enabled OAuth 2.0 clients are considered: an ID token issued to a client configured with micronaut.security.oauth2.clients.*.enabled: false is rejected. You can disable the validator by setting micronaut.security.token.jwt.claims-validators.openid-idtoken to false.
If you wish to customize the previous JSON payload, you may want to provide a bean replacement for BearerTokenRenderer. If that is not enough, check the AccessRefreshTokenLoginHandler to accommodate it to your needs.
11.3.12 Guides
Read the following guides to learn more about JSON Web Token and JSON Web Keys:
LDAP authentication can be globally disabled by setting micronaut.security.ldap.enabled to false, or on a provider
basis, eg micronaut.security.ldap.default.enabled: false.
Each key under micronaut.security.ldap that has nested properties (for example micronaut.security.ldap.default.*) defines one LDAP configuration and one LdapAuthenticationProvider. Single-valued keys directly under micronaut.security.ldap, such as the global switch micronaut.security.ldap.enabled, are not configuration names and never create a configuration or a provider.
Failed authentication responses
LdapAuthenticationProvider does not disclose whether a username exists in the directory. When the search for the username returns no entry, the provider returns the same AuthenticationFailureReason (CREDENTIALS_DO_NOT_MATCH) it returns for a wrong password, so login responses and WWW-Authenticate challenges carry the same message in both cases.
To keep the work done by the application similar as well, the provider performs a bind with the submitted password against a decoy entry. By default the decoy is a random, non-existent entry under the search base (cn=<random uuid>,<search base>), so the directory may log a failed bind for that DN whenever an unknown username is submitted; the random value avoids a fixed fingerprint in audit logs.
Only the client-side cost is equalised. A directory may still answer faster for a non-existent DN than for a wrong password, because it does not check a password hash, update bad-password or lockout counters or apply a password policy delay. Where that difference matters, create a real decoy account with an unmatchable password and set micronaut.security.ldap.default.search.decoy-dn to its DN, for example micronaut.security.ldap.default.search.decoy-dn: uid=decoy,ou=people,dc=example,dc=com. Exclude the decoy account from any account-lockout policy: a locked decoy answers unknown-username binds with a distinct, faster lockout error for the rest of the lockout window, which reopens the gap the decoy is meant to close. Remember too that whatever password a client submits with an unknown username is bound against the decoy entry, so a user who mistypes their username sends their real password to the decoy bind, and the directory may record that failed bind.
11.4.1 Configuration
The LDAP authentication in Micronaut supports configuration of one or more LDAP servers to authenticate with. Each server has it’s own settings and can be enabled or disabled.
Each server is configured under its own name, for example micronaut.security.ldap.default.*. A name only becomes a configuration when it has nested properties; a single-valued key directly under micronaut.security.ldap, such as micronaut.security.ldap.enabled, is not a configuration name.
Sets the DN bound, with the supplied password, when a username matches no directory entry, so that an unknown
username costs the application the same bind round trip as a wrong password. Defaults to a random non-existent
entry under the search base, which equalises only the client-side cost. Point it at a real account with an
unmatchable password, excluded from any lockout policy, to also equalise directory-side work (password hashing,
bad-password counters).
micronaut.security.ldap.*.search.subtree
boolean
Sets if the subtree should be searched. Default true
Sets if the subtree should be searched. Default true
micronaut.security.ldap.*.groups.base
java.lang.String
Sets the base DN to search from.
micronaut.security.ldap.*.groups.filter
java.lang.String
Sets the group search filter. Default "uniquemember={0}"
micronaut.security.ldap.*.groups.attribute
java.lang.String
Sets the group attribute name. Default "cn"
micronaut.security.ldap.*.groups.enabled
boolean
Sets if group search is enabled. Default false
micronaut.security.ldap.*.groups.filter-attribute
java.lang.String
Sets the name of the user attribute to bind to the
group search filter. Defaults to the user’s DN.
To connect to an LDAP server with SSL, set the standard Java system properties to the values appropriate for your server.
-Djavax.net.ssl.trustStore="<path to truststore file>"
-Djavax.net.ssl.trustStorePassword="<passphrase for truststore>"
11.4.2 Extending Default Behavior
This section will outline some common requirements that will require custom code to implement and describe what to do in those cases.
Authentication Data
The authentication object returned from a successful authentication request is by default an instance of Authentication, which only contains the username and any roles associated with the user. You can use Authenticationattributes to store additional data. Replace DefaultContextAuthenticationMapper and provide your own implementation.
MyContextAuthenticationMapper.java
@Singleton
@Replaces(DefaultContextAuthenticationMapper.class) (1)
public class MyContextAuthenticationMapper implements ContextAuthenticationMapper {
@Override
public AuthenticationResponse map(ConvertibleValues<Object> attributes, String username, Set<String> groups) {
// return an Authentication instance (Authentication::build methods) or an AuthenticationFailed object
}
}
1
The usage of @Replaces will allow your bean to replace the default implementation in the context
Groups
By default the groups found in LDAP, if enabled, will be returned as is without any processing. Each value of the group attribute becomes exactly one role, even if it contains a comma: a group named Sales,Marketing results in the single role Sales,Marketing. No additional groups from any other sources will be added to the list. It is a common requirement to retrieve additional groups from other sources, or to normalize the names of the groups in a specific format.
To extend this behavior, it is necessary to create your own implementation of LdapGroupProcessor. Likely it will be desired to extend the default implementation because it has the logic for querying the groups from LDAP and executes the other methods to process the groups and query for additional groups.
MyLdapGroupProcessor.java
@Singleton
@Replaces(DefaultLdapGroupProcessor.class) (1)
public class MyLdapGroupProcessor extends DefaultLdapGroupProcessor {
Set<String> getAdditionalGroups(LdapSearchResult result) { (2)
//Use the result to query another source for additional groups (database, etc)
}
Optional<String> processGroup(String group) { (3)
//convert "Admin" to "ROLE_ADMIN" for example
//return an empty optional to exclude the group
}
}
1
The usage of @Replaces will allow your bean to replace the default implementation in the context
Once you have configured HTTPS in your application, users can install X.509 browser certificates to provide authentication information and access restricted URLs.
When X.509 is enabled, in addition to the client (e.g. browser or API client) verifying that the server certificate is valid (i.e. that it was issued and signed by a trusted certificate authority (CA)), the server can also verify the client with the certificate from the client SSL handshake. If the client certificate is valid and contains a username/principal that corresponds to an application user, access will be granted.
Configuration
There are two configuration options as seen in the following table:
Set the Subject DN regex. Default value "CN=(.*?)(?:,
$)".
micronaut.security.x509.enabled
boolean
Use micronaut.security.x509.enabled to enable X.509 support, or enable per-environment.
Use the micronaut.security.x509.subject-dn-regex property to override the default regular expression used to extract the principal (username) from the certificate. Typically, the principal is stored in the CN (Common Name) property, prefixed with "CN=". The default regular expression "CN=(.*?)(?:,|$)" will extract the text after "CN=" and up to the next (optional) delimiter, but if your certificates are configured differently, override the regex as needed.
In addition to X.509-specific configuration, you must also configure HTTPS for your server, and configure requesting client certificates during the SSL handshake. Set the value of the property micronaut.server.ssl.client-authentication to want or need (depending on whether client certificates are optional or required).
Here’s a sample configuration enabling and configuring HTTPS and X.509:
Read the X.509 Authentication Micronaut Guide to learn about configuring applications to use X.509 and how to create the various certificates for testing.
11.6 Custom Authentication Strategies
All authentication strategies implement the AuthenticationFetcher interface. The contract is designed to return an Authentication from the request. To implement custom logic to retrieve the currently logged in user, simply create a bean that implements the contract and it will be picked up automatically.
For example, if you use a product like SiteMinder that handles authentication for you, you can trust that users access your application are authenticated, and you can access their username via the SM_USER request header and build an Authentication from that:
Micronaut allows the customization of the response that is sent when a request is not authorized to access a resource, or is not authenticated and the resource requires authentication.
Where the user is redirected to after a successful login. Default value ("/").
micronaut.security.redirect.login-failure
java.lang.String
Where the user is redirected to after a failed login. Default value ("/").
micronaut.security.redirect.logout
java.lang.String
URL where the user is redirected after logout. Default value ("/").
micronaut.security.redirect.prior-to-login
boolean
If true, the user should be redirected back to the unauthorized
request that initiated the login flow. Supersedes the <code>login-success</code>
configuration for those cases. Default value false.
micronaut.security.redirect.enabled
boolean
Sets whether Redirection configuration enabled. Default value (true).
For an unauthorized request, a 401 http response will be sent if unauthorized.enabled is false, or the request does not accept text/html.
For a rejected request, a 403 http response will be sent if forbidden.enabled is false, or the request does not accept text/html.
To fully customize the behavior, replace the relevant bean with your own implementation.
The HTTP WWW-Authenticate response header advertises the HTTP authentication methods (or challenges) that might be used to gain access to a specific resource.
If any bean of type WwwAuthenticateChallengeProvider is available, Micronaut Security uses them to populate the WWW-Authenticate header when a 401 Unauthorized response is returned.
If you have basic auth enabled, an entry for "Basic" authentication scheme is added by default. You can disable it setting micronaut.security.basic-auth.www-authenticate to false.
Cross-Site Request Forgery (CSRF) is an attack that forces an end user to execute unwanted actions on a web application in which they’re currently authenticated
13.1 CSRF Dependency
Add the Micronaut Security CSRF dependency to protect against CSRF:
The filter consults the resolvers one at a time, in their order, and stops at the first token which validates.
A resolver which does not find a token, which fails, or whose token does not validate, does not reject the request by itself: the filter moves on to the next resolver.
The request is rejected when no resolver yields a valid token.
The HTTP header resolver runs before the form field resolver. Hence, the request body is not parsed when the HTTP header carries a valid token.
A request without a valid token in the HTTP header still has its body parsed, up to micronaut.server.max-request-size, to look for the token in a form field.
The following configuration options are available for the CSRF Filter:
Filter will only process requests whose method matches any of these methods. Default Value is POST, PUT, DELETE, PATCH.
micronaut.security.csrf.filter.content-types
java.util.Set
Filter will only process requests whose content type matches any of these content types. Default Value is application/x-www-form-urlencoded, multipart/form-data.
micronaut.security.csrf.filter.enabled
boolean
Whether the filter is enabled. Default value true.
micronaut.security.csrf.filter.regex-pattern
java.lang.String
CSRF filter processes only request paths matching this regular expression. Default Value: "^.*$"
13.3 CSRF Mitigations
Ensure your application does not perform state-changing actions via the GET request method. Your application should perform state-changing actions only via POST, PUT, PATCH, or DELETE methods.
In a synchronized token pattern, the server generates a CSRF token and shares it with the client before returning it,
usually through a hidden form parameter for the associated action. On form submission, the server checks the CSRF token against
one stored in the user’s session. If they match, the request is approved; otherwise, it’s rejected
13.3.1.1 CSRF and Session
If you use Session-Based Authentication and Micronaut Security CSRF, a CSRF token is automatically generated upon login and saved into the HTTP Session. Micronaut Session provides an implementation
CsrfTokenRepository which fetches the CSRF token from the user’s HTTP session. Thus, when the application sends new request to the sever with a CSRF token (e.g. in a hidden form field or HTTP Header), the server validates the supplied token against the value stored in the HTTP Session.
SessionCsrfTokenRepository takes precedence over CookieCsrfTokenRepository. When a request carries an HTTP session which holds a CSRF token, the supplied token is only validated against the session token; a CSRF cookie present in the request is ignored. This prevents a CSRF cookie planted in the user’s browser (for example, from a sibling subdomain) from replacing the token stored in the session.
You can disable the CSRF Session repository by setting micronaut.security.csrf.repositories.session.enabled to false.
The session is authoritative only when it holds a CSRF token. If a request carries an HTTP session without a CSRF token attribute (for example, a session created before CSRF was enabled or by a login path which does not run CsrfSessionPopulator), the next repository, such as CookieCsrfTokenRepository, is consulted and a planted CSRF cookie is not neutralized. Make sure every login path which creates a session runs CsrfSessionPopulator. The default SessionLoginHandler does. Setting micronaut.security.csrf.signature-key further limits this case: the HMAC binds the token to the session ID, so a token issued for another session is rejected even when only the cookie repository holds a token.
Repositories are consulted following their getOrder() and the first one holding a CSRF token wins. Custom CsrfTokenRepository beans should declare an explicit getOrder(): at the default order of 0 they tie with CookieCsrfTokenRepository, and the order between tied repositories is then unspecified.
In a double-submit cookie pattern, the server generates a CSRF token, and it sends the CSRF token to the client in a cookie.
Then, the server only needs to verify that following requests cookie’s value matches the CSRF token sent in a request parameter (a hidden form field) or header. This process is stateless, as the server doesn’t need to store any information about the CSRF token.
POST /transfer HTTP/1.1
Host: vulnerable bank
Content-Type: application/x-www-form-urlencoded
Cookie: session=<token>; __Host-csrfToken=o24b65486f506e2cd4403caf0d640024
[...]
amount=100&toUser=intended&csrfToken=o24b65486f506e2cd4403caf0d640024
When you use Micronaut Security Authentication cookie, or
idtoken a CSRF Token is saved in a Cookie upon login.
Signed Double-Submit Cookie. Sign the CSRF Token with to prevent attackers from overriding the cookie value with their own (e.g. with taken-over subdomain attacks) .
To do sign the CSRF Token, set the property micronaut.security.csrf.signature-key.
Whether the cookie is a session cookie. A session cookie does not have an expiration date. cookie-max-age is ignored if session cookie is set to true. Default value (false).
micronaut.security.csrf.signature-key
java.lang.String
The Secret Key that is used to calculate an HMAC as part of a CSRF token generation. Default Value null.
micronaut.security.csrf.http-session-name
java.lang.String
Key to look for the CSRF token in an HTTP Session. Default Value: "csrfToken".
micronaut.security.csrf.random-value-size
int
Random value’s size in bytes. The random value used is used to build a CSRF Token. Default Value: 16.
micronaut.security.csrf.header-name
java.lang.String
HTTP Header name to look for the CSRF token. Default Value: "X-CSRF-TOKEN".
micronaut.security.csrf.field-name
java.lang.String
Field name in a form url encoded submission to look for the CSRF token. Default Value: "csrfToken".
micronaut.security.csrf.enabled
boolean
Whether the CSRF integration is enabled. Default value true.
micronaut.security.csrf.cookie-domain
java.lang.String
Sets the domain name of this Cookie. Default value (null).
micronaut.security.csrf.cookie-secure
java.lang.Boolean
Sets whether the cookie is secured. Defaults to the secure status of the request.
micronaut.security.csrf.cookie-name
java.lang.String
Cookie Name.
micronaut.security.csrf.cookie-path
java.lang.String
Sets the path of the cookie. Default value ("/").
micronaut.security.csrf.cookie-http-only
java.lang.Boolean
Whether the Cookie can only be accessed via HTTP. Default value (true).
micronaut.security.csrf.cookie-max-age
java.time.Duration
Sets the maximum age of the cookie. Default value ({@value AccessTokenConfigurationProperties#DEFAULT_EXPIRATION} seconds).
Micronaut Security CSRF ships a io.micronaut.security.csrf.resolver.HttpHeaderCsrfTokenResolver an implementation of CsrfTokenResolver which looks for a CSRF Token in a Request’s HTTP Header.
POST /transfer HTTP/1.1
Host: vulnerable bank
Content-Type: application/x-www-form-urlencoded
Cookie: session=<token>
X-CSRF-TOKEN: o24b65486f506e2cd4403caf0d640024
[...]
amount=100&toUser=intended
You can disable it by setting micronaut.security.csrf.token-resolvers.http-header.enabled=false
The HTTP Header name used by HttpHeaderCsrfTokenResolvercan be configured.
It is recommended to use a custom HTTP Header Name. By using a custom HTTP Header name, it will not be possible to send them cross-origin without a permissive CORS implementation.
Moreover, If possible, we recommend you to send the CSRF token via an HTTP Header instead of a form field as it is harder to attack.
For example, Turbo sends the CSRF token via a custom HTTP Header upon form submission. You can find information about Micronaut Turbo integration.
13.5.2 Field CSRF Token Resolution
Micronaut Security CSRF ships a io.micronaut.security.csrf.resolver.FieldCsrfTokenResolver an implementation of FutureCsrfTokenResolver which looks for a CSRF Token in a Request’s form-url-encoded field.
POST /transfer HTTP/1.1
Host: vulnerable bank
Content-Type: application/x-www-form-urlencoded
Cookie: session=<token>
[...]
amount=100&toUser=intended&csrfToken=o24b65486f506e2cd4403caf0d640024
You can disable it by setting micronaut.security.csrf.token-resolvers.field.enabled=false
If the form body cannot be decoded (for example, because it contains an invalid percent escape such as %zz), no CSRF token is resolved and the request is rejected like any other request without a valid CSRF token. The raw request body is never logged; the type of the decoding failure is logged at DEBUG level by io.micronaut.security.csrf.resolver.FieldCsrfTokenResolver.
A request body larger than micronaut.server.max-request-size is not treated as a missing token: the request is answered with 413 Request Entity Too Large.
The Reporting API provides a common browser mechanism for delivering reports generated by features such as Content Security Policy and Network Error Logging.
The micronaut-security-reporting module advertises named report destinations in the Reporting-Endpoints response header. It does not receive or persist reports. Applications are responsible for implementing the advertised endpoints and safely processing the report formats produced by the browser feature that uses each endpoint.
Reporting is a best-effort mechanism. Browsers can delay, discard, or decline to deliver reports, so an application must not rely on reporting for security enforcement, auditing completeness, or other critical communication.
The name of each configuration entry is a reporting group. Browser features refer to that name when selecting a destination. Group names must be valid HTTP Structured Fields dictionary keys: they start with a lowercase ASCII letter or and contain only lowercase letters, digits, _, -, ., or .
A browser discards the whole Reporting-Endpoints header when one of its keys is outside that grammar, so the module never serializes an endpoint it cannot advertise:
The application fails to start when a configuration entry has an invalid name.
A configuration entry without a url is left out of the header, and the module logs a warning that names the entry.
A ReportingEndpoint bean with an invalid name or without a URL is also left out and logged.
The Reporting API specification defines an endpoint value as a URI-reference. Therefore, it can be absolute or relative. The browser resolves a relative reference against the URL of the response that supplied the header. After resolution, the endpoint must be potentially trustworthy; browsers ignore non-secure endpoints.
The module sorts entries by group name to produce a deterministic header. It does not add the header when no endpoints are available, and it does not overwrite a Reporting-Endpoints header already supplied by application code.
Sets the absolute or relative reporting endpoint URI.
14.2 Dynamic Reporting Endpoints
You can provide a bean of type ReportingEndpointProvider for dynamic registering reporting endpoints.
The filter combines provider results with endpoints declared in configuration. A provider can return null when it does not contribute an endpoint for a particular request. Endpoint group names must remain unique after all configured and provider-generated endpoints are combined. When two endpoints share a name, the filter keeps the first one and logs a warning for the other. Endpoints declared in configuration or as beans come before provider endpoints, so a provider cannot replace them.
An endpoint returned by a provider must also have a valid group name and a URL. The filter leaves out an endpoint that fails either check and logs a warning naming the provider, so the response is still served with the remaining endpoints.
When this module is present, it contributes an HtmlSanitizer bean backed by OWASP Java HTML Sanitizer. The bean replaces the Core entity-encoding fallback and is secondary to an application-provided HtmlSanitizer bean.
The configured policies define the allowlist for sanitized output: only HTML elements and attributes allowed by those OWASP policies are preserved.
By default, the module combines the OWASP BLOCKS, FORMATTING, and LINKS policies, so sanitized output can include common block elements, formatting elements, and safe links. It does not allow scripts, event-handler attributes, javascript: URLs, CSS style handling, images, or tables by default.
Sets whether the OWASP-backed HTML sanitizer is enabled.
micronaut.security.html-sanitizer.policies
java.util.List
Sets the OWASP sanitizer policies to combine. By default {@code BLOCKS, FORMATTING and LINKS}.
You can opt into additional OWASP policies with configuration. For example, adding IMAGES allows the image elements and attributes defined by the OWASP image policy:
To replace the module completely, provide your own HtmlSanitizer bean. To disable the module without removing the dependency, set micronaut.security.html-sanitizer.enabled=false.
When rendering untrusted HTML, discard the original input and render only the sanitized output returned by HtmlSanitizer. Keep contextual output encoding and template escaping enabled, and do not treat removed tags or attributes as proof that the original input was safe.
16 Password Encoding
Applications that store passwords must store a salted, one-way hash of each password and never the password itself. Micronaut Security defines the PasswordEncoder API for this purpose:
encode returns the value to store. It includes the salt and the parameters required to verify the password later. matches verifies a password against a stored value.
The parameters of both methods are constrained with @NotBlank. A value that is null, empty or contains only whitespace is rejected with a ConstraintViolationException.
Every implementation honours the same contract:
Encoding the same password twice produces different results, and the result never contains the password.
Every character of the password is significant. Implementations do not truncate the password or alter its case or whitespace.
Blank passwords and blank stored values are rejected with a ConstraintViolationException.
matches returns false, instead of throwing an exception, for a stored value that is not blank and that the implementation cannot parse.
Implementations are safe for use by multiple threads.
The API is in its own module and has no dependency on the rest of Micronaut Security:
Compare the supplied password with the stored value. If the user does not exist, compare it with the placeholder, so that the password is hashed in both cases.
3
Return the same failure for a user that does not exist and for a wrong password.
The example hashes the supplied password and returns the same response whether or not the user exists, so neither the response nor the time it takes reveals which usernames are registered. A stored password that was encoded with other parameters than the configured ones still takes a different time to verify.
Because matches rejects blank values with an exception, check for them first if they can reach your code, for example when a user has no stored password.
Multiple password encoders
If the application has more than one PasswordEncoder bean, for example your own encoder next to Argon2id, an injection point without a qualifier is ambiguous and fails with a NonUniqueBeanException. Select the encoder to inject with a name qualifier, such as @Named("bouncycastle").
The Argon2id encoder is named bouncycastle. Give your own encoders a name with @Named.
16.1 Argon2id
Argon2id is a memory-hard password hashing function and the first choice of the OWASP Password Storage Cheat Sheet. To use the Bouncy Castle implementation, add the dependency:
The module contributes a PasswordEncoder bean implemented with Bouncy Castle. The bean is named bouncycastle. Use that name to select it if the application has more than one encoder.
m is the memory cost in kibibytes, t the number of iterations and p the degree of parallelism. The salt and the hash are Base64 encoded without padding. A new random salt is generated for every password.
Size the column that stores the encoded password for the longest value your configuration can produce. With the default configuration an encoded password has 97 characters. With the longest salt and hash, and the largest parameters accepted by default, it has less than 200.
Sets the memory cost, in kibibytes, used to encode passwords. It must be at least eight times
the parallelism and at most the maximum memory. Default value (19456).
micronaut.security.password.argon2.iterations
int
Sets the number of iterations used to encode passwords. It must be at least 1 and at most
the maximum iterations. Default value (2).
micronaut.security.password.argon2.parallelism
int
Sets the degree of parallelism used to encode passwords. It must be between 1 and 255.
Default value (1).
micronaut.security.password.argon2.salt-length
int
Sets the length, in bytes, of the salt generated for each encoded password. It must be
between 8 and 48. Default value (16).
micronaut.security.password.argon2.hash-length
int
Sets the length, in bytes, of the hash generated for each encoded password. It must be
between 12 and 64. Default value (32).
micronaut.security.password.argon2.max-memory
int
Sets the highest memory cost, in kibibytes, accepted when verifying an encoded password. An
encoded password that declares a higher memory cost does not match any password.
Default value (262144).
micronaut.security.password.argon2.max-iterations
int
Sets the highest number of iterations accepted when verifying an encoded password. An
encoded password that declares more iterations does not match any password.
Default value (10).
The defaults are the minimum configuration recommended by OWASP: 19 MiB of memory, two iterations and one degree of parallelism. OWASP lists other configurations that provide the same level of defense and trade CPU for memory. For example, to use 46 MiB of memory and one iteration:
The application fails to start if the configuration is invalid: the memory must be at least eight times the parallelism, the parallelism must be between 1 and 255, the salt length between 8 and 48 bytes, and the hash length between 12 and 64 bytes. The memory and iterations cannot exceed max-memory and max-iterations.
Choosing parameters
Hashing is deliberately expensive. Measure how long encode takes on your production hardware and choose the highest parameters your login latency and concurrency allow.
Each call to encode uses the configured memory, while matches uses the memory declared in the encoded password. Concurrent logins multiply that amount.
Hashing blocks the calling thread. Do not call the encoder on an event loop thread.
Verifying passwords encoded with other parameters
A password is always verified with the parameters stored in its encoded value, not with the configured ones. Passwords encoded before you changed the configuration keep matching.
An encoded password does not match if it declares more memory than max-memory or more iterations than max-iterations. These limits bound the resources a single stored value can consume. If you lower the configured memory or iterations, keep the limits at or above the highest values present in your stored passwords.
Only Argon2id version 19 is supported. Encoded passwords that use Argon2i, Argon2d, version 16, or the optional keyid and data parameters do not match.
Passwords encoded with other algorithms, such as bcrypt, do not match. To migrate them, keep verifying them with the previous library and encode the password with PasswordEncoder the next time the user logs in successfully.
16.2 TCK
Micronaut Security publishes a Technology Compatibility Kit (TCK), a JUnit test suite that verifies that a PasswordEncoder honours the contract of the API. Use it to test your own implementation.
The TCK requires JUnit 6. Add it and the JUnit Platform Suite as test dependencies:
[tool.pyronaut.dependencies]
test = [
"org.junit.platform:junit-platform-suite",
]
Then create a suite that selects the package of the TCK:
import org.junit.platform.suite.api.SelectPackages;
import org.junit.platform.suite.api.Suite;
import org.junit.platform.suite.api.SuiteDisplayName;
@Suite
@SelectPackages("io.micronaut.security.password.tck")
@SuiteDisplayName("My PasswordEncoder TCK")
public class MyPasswordEncoderSuite {
}
The tests start an application context and inject the PasswordEncoder bean, so the test classpath must contain exactly one.
The parameters of PasswordEncoder are constrained with @NotBlank, and the TCK verifies that your implementation enforces those constraints. For Micronaut Validation to apply them, compile your implementation with its annotation processor:
The refresh token functionality has changed dramatically starting in Micronaut Security 2.0. Please read this section if you are upgrading as it now behaves differently.
Refresh tokens can be used to obtain a new access token. By default, refresh tokens are not generated.
The RefreshTokenGenerator API is responsible for generating the token that gets included in the response. The RefreshTokenValidator is responsible for validating the refresh token. Note that this validation step is not related to the persistence of the token, but instead is intended to verify the token is not a random/guessed value.
An implementation of both RefreshTokenGenerator and RefreshTokenValidator has been provided by default. The SignedRefreshTokenGenerator creates and verifies a JWS (JSON web signature) encoded object whose payload is a UUID with a hash-based message authentication code (HMAC). See the following configuration options:
After a token is generated, this library has no knowledge of it. The value is not cached or stored anywhere. It is up to each application to decide how to store the token, support revocation, and retrieve user details when given a token.
In addition to the above requirements, each application must provide an implementation of RefreshTokenPersistence.
The RefreshTokenPersistence implementation will receive an event when a refresh token is generated and then is responsible for persisting the token along with a link to the user that it was generated for. The user information and the token are both available in the RefreshTokenGeneratedEvent.
The refresh token endpoint uses the RefreshTokenValidator API to verify the token matches the format that is expected. SignedRefreshTokenGenerator attempts to verify the signature and returns the payload. Any validator implementations should not be concerned with revocation status, existence, or any other persistence related validation.
If the validator successfully validates the token, it is then passed to a RefreshTokenPersistence implementation, which each application must provide. A new access token is then created from the user details returned by RefreshTokenPersistence::getAuthentication and then sent in the response.
Here is an example of a refresh token request. Send a POST request to the /oauth/access_token endpoint:
Sample HTTP request to obtain an access token
POST /oauth/access_token HTTP/1.1
Host: micronaut.example
Content-Type: application/x-www-form-urlencoded
grant_type=refresh_token&refresh_token=eyJhbGciOiJSU0EtT0FFUCIsImVuYyI6IkEyNTZHQ00ifQ....
As you can see, is a form request with 2 parameters:
grant_type: must be refresh_token always.
refresh_token: the refresh token obtained previously.
This controller can only be enabled if you are using JWT authentication.
A JSON Web Key (JWK) is a JSON object that represents a cryptographic key. The members of the object represent properties of the key, including its value.
Meanwhile, a JWK Set is a JSON object that represents a set of JWKs. The JSON object MUST have a "keys" member, which is an array of JWKs.
Often, you may want to retrieve the authenticated user.
You can bind java.security.Principal as a method parameter in a controller.
import io.micronaut.core.util.CollectionUtils;
import io.micronaut.http.annotation.Controller;
import io.micronaut.http.annotation.Get;
import io.micronaut.security.annotation.Secured;
import org.jspecify.annotations.Nullable;
import java.security.Principal;
import java.util.Collections;
import java.util.Map;
@Controller("/user")
public class UserController {
@Secured("isAnonymous()")
@Get("/myinfo")
public Map<String, Object> myinfo(@Nullable Principal principal) {
if (principal == null) {
return Collections.singletonMap("isLoggedIn", false);
}
return CollectionUtils.mapOf("isLoggedIn", true, "username", principal.getName());
}
}
from java.security import Principal
from micronaut.http.annotation import Controller, Get
from micronaut.security.annotation import Secured
@Controller("/user")
class UserController:
@Secured("isAnonymous()")
@Get("/myinfo")
def myinfo(self, principal: Principal | None) -> dict:
if principal is None:
return {"isLoggedIn": False}
return {"isLoggedIn": True, "username": principal.getName()}
import io.micronaut.http.annotation.Controller
import io.micronaut.http.annotation.Get
import io.micronaut.security.annotation.Secured
import java.security.Principal
@Controller("/user")
class UserController {
@Secured("isAnonymous()")
@Get("/myinfo")
fun myinfo(principal: Principal?): Map<String, Any> {
if (principal == null) {
return mapOf("isLoggedIn" to false)
}
return mapOf("isLoggedIn" to true, "username" to principal.name)
}
}
If you need to access the currently authenticated user outside of a controller, you can inject SecurityService bean, which provides a set of convenient methods related to authentication and authorization.
The default supplier for SecurityContext uses server request attributes. You can replace it by providing an implementation of SecurityContextSupplier via a Java SPI.
Micronaut Security provides integration with Micronaut Data for automatically capturing the identity of the user that created or updated a particular entity.
20.1 Auditing Annotations
The annotations @CreatedBy and @UpdatedBy annotations are provided for application to your Micronaut Data entities. The annotated fields will be automatically populated with the currently authenticated user’s identity. For example:
from dataclasses import dataclass
from typing import Annotated
from jakarta.validation.constraints import NotBlank
from micronaut.data.annotation import GeneratedValue, Id, MappedEntity
from micronaut.security.annotation import CreatedBy, UpdatedBy
@MappedEntity # (1)
@dataclass
class Book:
id: Annotated[int | None, Id, GeneratedValue]
title: Annotated[str, NotBlank]
author: Annotated[str, NotBlank]
creator: Annotated[str | None, CreatedBy] # (2)
editor: Annotated[str | None, UpdatedBy] # (3)
import io.micronaut.data.annotation.GeneratedValue
import io.micronaut.data.annotation.Id
import io.micronaut.data.annotation.MappedEntity
import io.micronaut.security.annotation.CreatedBy
import io.micronaut.security.annotation.UpdatedBy
@MappedEntity // (1)
data class Book(
@field:Id
@field:GeneratedValue(GeneratedValue.Type.AUTO)
var id: Long? = null,
var title: String,
var author: String,
@field:CreatedBy // (2)
var creator: String? = null,
@UpdatedBy // (3)
var editor: String? = null
)
import org.jspecify.annotations.Nullable
import io.micronaut.data.annotation.GeneratedValue
import io.micronaut.data.annotation.Id
import io.micronaut.data.annotation.MappedEntity
import io.micronaut.security.annotation.CreatedBy
import io.micronaut.security.annotation.UpdatedBy
import jakarta.validation.constraints.NotBlank
@MappedEntity // (1)
class Book {
@Id
@GeneratedValue
@Nullable
Long id
@NotBlank
String title
@NotBlank
String author
@CreatedBy // (2)
String creator
@UpdatedBy // (3)
String editor
}
1
The class is mapped and persisted by Micronaut Data
2
The creator field will be populated on save()
3
The editor field will be populated on both save() and update()
20.2 Custom Authentication Mapping
A PrincipalToStringConverter is provided to map the current Authentication object to the annotated String fields. The default implementation maps the value of Principal.getName() to the fields. To customize this mapping, you can provide your own TypeConverter implementation that replaces PrincipalToStringConverter. For example:
Conversion between Authentication and String is implemented
2
The implementation maps a custom attribute to the auto-populated identity
The type conversion mechanism could also be used to map Authentication to more complex field types other than String, such as a custom domain-specific User object.
21 Security Events
Micronaut security classes generate several ApplicationEvents which you can subscribe to.
To learn how to listen for events, see the Context Events section of the documentation.
Micronaut Framework logs every published event at DEBUG level through the io.micronaut.context.event.ApplicationEventPublisher logger using the event’s toString(). The events that carry a token (TokenValidatedEvent, AccessTokenGeneratedEvent and RefreshTokenGeneratedEvent) redact it from their string representation, and the other security events (for example LoginSuccessfulEvent and LogoutEvent) do not print their source, so that enabling DEBUG logging never writes tokens to the log. Listeners obtain the token through getSource() (or getRefreshToken() for the refresh token event). Avoid logging the token yourself in your listeners.
22 OAuth 2.0
Micronaut supports authentication with OAuth 2.0 servers, including support for the OpenID standard.
The easiest way to get started is by configuring a provider that supports OpenID. Platforms such as Okta, Auth0, AWS Cognito, Keycloak, and Google are common examples.
Once you create an application client with a provider, you will get a client id and a client secret. The client id and secret combined with the issuer URL is all that is needed to enable the authentication code grant flow with an OpenID provider.
For normal OAuth 2.0, different steps are required to allow for the authorization code grant flow.
For the full authorization code flow to work there are also some additional requirements. A LoginHandler must be in the context to determine how to respond after a failed or successful login. A custom implementation can, of course, be provided. However, several Login Handlers implementations are available out of the box.
Read the following guides to learn more Secure a Micronaut app with Okta, Cognito, Google.
OpenID Connect 1.0 is a simple identity layer on top of the OAuth 2.0 protocol. It allows Clients to verify the identity of the End-User based on the authentication performed by an Authorization Server, as well as to obtain basic profile information about the End-User in an interoperable and REST-like manner.
If you are new to OpenID Connect, we recommend watching OAuth 2.0 and OpenID Connect to get a better understanding.
To use OpenID client flows, the security-jwt dependency must be in your build because OpenID relies on JWT tokens.
Even though OpenID providers return JWT tokens, that token is not used directly to authorize requests with Micronaut by default. Instead a new token is created if the application is using JWT. This allows for authorization to be standardized across custom authentication providers, normal OAuth 2.0 flows, and OpenID flows. It also allows for purely session based authorization as a result of OpenID authentication. To use the provider token directly, set the authentication mode to idtoken.
Only in idtoken authentication mode is the provider’s JSON Web Key Set (the jwks_uri of the OpenID metadata) registered as a signature configuration to validate request tokens, and IdTokenClaimsValidator then ensures the token was issued to this client. In any other mode, tokens signed by the provider’s keys, including ID tokens issued to other clients, are not accepted as request credentials. If your application is a resource server that must accept the provider’s access tokens, configure the JWKS explicitly with micronaut.security.token.jwt.signatures.jwks.*. The ID token obtained during the authorization code flow is always verified against the issuing provider’s JWKS.
22.3 Flows
22.3.1 Authorization Code
The authorization code grant flow is the most typical authentication flow with OAuth 2.0 and OpenID providers. The same main steps apply to the flow whether or not the provider supports OpenID, and is described in RFC6749 - Authorization Code Grant.
The OAuth 2.0 authorization code flow requires a callback endpoint. In addition, a login endpoint is available to trigger the flow. The URIs are configurable.
Sets whether the OAuth 2.0 support is enabled. Default value (true).
micronaut.security.oauth2.login-uri
java.lang.String
The URI template that is used to initiate an OAuth 2.0
authorization code grant flow. Default value ("/oauth/login{/provider}").
micronaut.security.oauth2.callback-uri
java.lang.String
The URI template that OAuth 2.0 providers can use to
submit an authorization callback request. Default value ("/oauth/callback{/provider}").
micronaut.security.oauth2.default-provider
java.lang.String
The default authentication provider for an OAuth 2.0 authorization code grant flow.
The URI templates for login and callback have a template variable in them {provider}. That variable is used by the route builder to build routes for each provider that is configured. The name provider is special in this context and cannot be changed. The URI may be manipulated however in any way as long as the provider variable is part of the path of the URI.
For example /oauth/login{?provider} is not a valid configuration because Micronaut does not consider the query segment of a URL when routing requests. The provider variable must be part of the path.
It is possible to designate a default provider. The value of the configuration must match one of the client names. The default provider will have the same uri template, but with null passed as the provider parameter. By default that will result in /oauth/login being redirected to the default provider authentication page.
OAuth Login and CSRF
In order to prevent forced login attacks, you must implement CSRF protection on the oauth login endpoints. Because this library is not in control of the forms where login may originate from, we cannot ensure that CSRF is applied. In addition, there is no sensible defaults with regards to how the token is stored or how it should be retrieved. Implementing CSRF is relatively simple.
When rendering the login form where users can choose to login via OAuth, the server should store a value either in state on the server specific to that user (session), or state on the client (http-only cookies, etc), or some other mechanism.
That value gets sent with the response and subsequently included in the request to login with OAuth. The value could be sent as a query parameter, or sent as a cookie, etc.
A server filter is written to compare the value in the user specific state and the value sent in the request. If they do not match, the request is rejected.
It’s possible to configure authorization with an OpenID provider simply with this library because OpenID standardizes how to retrieve user information from the provider. Because a user information endpoint is not part of the OAuth 2.0 specification, it is up to you to provide an implementation to retrieve that information.
Here is a high level diagram of how the authorization code grant flow works with an OAuth 2.0 provider.
22.3.1.1.1 Configuration
The minimum requirements to allow authorization with an OAuth 2.0 provider are:
Additionally, the token endpoint URL and authentication method
auth-method is one of AuthenticationMethod. Choose the one your provider requires.
Authentication methods are not clearly defined in RFC 6749, however most OAuth 2.0 providers either accept client-secret-basic (basic authentication with id and secret), or client-secret-post (client id and secret are sent in the request body).
To disable a specific client for any given environment, set enabled: false within the client configuration.
22.3.1.1.2 User Details Mapper
Beyond configuration, an implementation of OauthAuthenticationMapper is required by the user to be implemented. The implementation must be qualified by name that matches the name present in the client configuration.
The purpose of the user details mapper is to transform the TokenResponse into a Authentication. That will entail calling some endpoint the provider exposes to retrieve the user’s information. Once that information is received, the user details can be populated per your requirements.
Common requirements of a user details mapper may be to combine data from the OAuth 2.0 provider with data from a remote database and/or create new user records. The Authentication object stores three basic properties: username, roles, and arbitrary attributes. All data stored in the user details will be retrievable in controllers that accept an Authentication.
For example, here is how it might be implemented for Github.
Create a class to store the response data:
import tools.jackson.databind.PropertyNamingStrategies;
import tools.jackson.databind.annotation.JsonNaming;
import io.micronaut.core.annotation.Introspected;
@Introspected
@JsonNaming(PropertyNamingStrategies.SnakeCaseStrategy.class)
public class GithubUser {
private String login;
private String name;
private String email;
// getters and setters ...
}
from dataclasses import dataclass
from micronaut.core.annotation import Introspected
from tools.jackson.databind import PropertyNamingStrategies
from tools.jackson.databind.annotation import JsonNaming
@Introspected
@JsonNaming(PropertyNamingStrategies.SnakeCaseStrategy)
@dataclass
class GithubUser:
login: str | None = None
name: str | None = None
email: str | None = None
import tools.jackson.databind.PropertyNamingStrategies
import tools.jackson.databind.annotation.JsonNaming
import io.micronaut.core.annotation.Introspected
@Introspected
@JsonNaming(PropertyNamingStrategies.SnakeCaseStrategy::class)
class GithubUser {
lateinit var login: String
var name: String? = null
var email: String? = null
}
import tools.jackson.databind.PropertyNamingStrategies;
import tools.jackson.databind.annotation.JsonNaming
import io.micronaut.core.annotation.Introspected
@Introspected
@JsonNaming(PropertyNamingStrategies.SnakeCaseStrategy.class)
class GithubUser {
String login
String name
String email
}
Whether the OpenID configuration should be fetched from the discovery endpoint derived from {@link #getIssuer()} and {@link #getConfigurationPath()}. Default value: true.
The value expected in the {@code iss} claim of ID tokens. Set it when it differs from the {@code issuer} used to
fetch the discovery document, for example when discovery is fetched over an internal URL. Defaults to {@code issuer}.
Because the OpenID standard returns a JWT token in the token response, it is possible to retrieve information about the user without having to make an additional call. In addition, the data stored in the JWT is standardized so you can use the same code to retrieve that information across providers.
A default implementation of OpenIdAuthenticationMapper has been provided for you to map the JWT token to a Authentication. The default implementation will carry over any of the specific OpenID JWT claims, as well as potentially include other claims based on configuration. The original provider name will always be included in the JWT with the claim key "oauth2Provider". The following table explains the additional claims.
Set to true if the original refresh token from the provider should be included in the Micronaut JWT.
Default value (false).
Enabling all of the above with cookie JWT storage has been known to cause issues with Keycloak due to their tokens being very large and causing the resulting cookie to be larger than what browsers allow.
Username
The default mapper derives the username returned by Authentication.getName() from the sub claim of the ID token. A sub is only unique within the provider which issued it: two different users at two providers may well share the same sub, especially with providers that let users pick an account name or that issue sequential or e-mail based subjects. For that reason:
When more than one enabled OAuth 2.0 client, other than client-credentials-only clients, is configured under micronaut.security.oauth2.clients, the username is the provider name followed by : and the sub claim, for example okta:248289761001. This is the same convention and the same property used for authentications validated through the UserInfo endpoint, so a user has the same name in a browser login and in a bearer request. The unqualified subject remains available in the sub attribute.
With a single client the username is the bare sub claim.
Set micronaut.security.oauth2.openid.qualify-username-with-provider to true explicitly in any application which keys data on the username. The automatic rule depends on the clients configured, so adding another client later would otherwise rename every user.
micronaut.security.authentication set to idtoken is not covered. In that mode the cookie holds the raw ID token and every request after login is authenticated from its claims, so the username is the bare sub claim whatever the property value and the same sub issued by two providers still maps to the same user. When you configure several providers and key data on the username, do not use idtoken; use cookie or session, or derive the key from the iss and sub claims.
The provider name is always available in the oauth2Provider attribute as well. You can force or disable the qualification with micronaut.security.oauth2.openid.qualify-username-with-provider:
Whether the username of an authentication built from an OpenID provider response, by the default OpenID authentication mapper at login or by the UserInfo endpoint token validator, is the sub claim qualified with the provider name (providerName:subject) instead of the bare sub claim.
The sub claim is only unique within one provider. If not set, the username is qualified only when more than one enabled OAuth 2.0 client, other than client-credentials-only clients, is configured under micronaut.security.oauth2.clients. It does not apply when micronaut.security.authentication is idtoken.
Disabling the qualification while several clients are configured lets a user at one provider act as the user with the same sub at another provider in any application that keys data on the username.
If the default implementation is not sufficient, it is possible to override the global default or provide an implementation specific to a provider.
You cannot use micronaut.security.authentication = idtoken, if you wish to use a custom OpenIdAuthenticationMapper. You should use micronaut.security.authentication = cookie or provide your own implementation of Login Handler and Logout Handler.
To override the user detail mapping behavior for a specific provider, register a bean with a named qualifier with a value equal to the name specified in the client configuration.
The OpenID specification for authorization requests allows for additional parameters beyond what is included in the OAuth 2.0 specification. Some of those parameters make sense to be provided by a bean and are described in this section. Other parameters are able to be controlled through configuration.
Here are the configuration option for authorization request parameters:
By default, this library will include a nonce parameter as described in the OpenID Connect specification in authentication requests.
Because the validation of the nonce requires the nonce to be stored somewhere temporarily, a NoncePersistence bean must be present to retrieve the nonce for validation.
Micronaut ships with two implementations of NoncePersistence. One implementation to store it in a HTTP cookie (CookieNoncePersistence) and another one to persist it with a HTTP Session (SessionNoncePersistence).
Sets the mechanism to persist the nonce for later retrieval for validation.
Supported values ("session", "cookie"). Default value ("cookie").
micronaut.security.oauth2.openid.nonce.enabled
boolean
Sets whether a nonce parameter will be sent. Default (true).
If you use the default implementation, which stores the nonce in a HTTP cookie, you can configure how the cookie is built. See the following configuration options:
Whether the cookie is a session cookie. A session cookie does not have an expiration date. cookie-max-age is ignored if session cookie is set to true. Default value (false).
To override the behavior of any of those beans, provide an implementation and replace the default one.
22.3.1.2.3.2 Login Hint
This library does not include an login hint by default with authorization requests. A LoginHintResolver bean can be registered that will be called when the authorization request is being built.
22.3.1.2.3.3 ID Token Hint
This library does not include an ID Token hint by default with authorization requests. A IdTokenHintResolver bean can be registered that will be called when the authorization request is being built.
22.3.1.2.4 Token Validation
A OpenIdTokenResponseValidator bean is responsible for validating the JWT token. The default implementation follows the guidelines described in the OpenID Connect specification regarding token validation where possible.
To allow for additional or custom validations, register an OpenIdClaimsValidator bean.
Issuer validation
IssuerClaimValidator validates the iss claim of the ID token. The expected issuer is micronaut.security.oauth2.clients..openid.issuer-identifier if set, otherwise micronaut.security.oauth2.clients..openid.issuer. The iss claim must equal it (the only differences tolerated are the case of the scheme and a trailing slash) and must exactly match the Issuer Identifier of the provider metadata.
The issuer announced in the provider’s discovery document is controlled by the provider. Per OpenID Connect Discovery 1.0 section 4.3 it must be identical to the issuer used to retrieve the discovery document. If it does not match the expected issuer, Micronaut Security logs an error, discards the announced issuer and uses the expected issuer as the Issuer Identifier of the provider. Thus, a provider cannot get ID tokens issued by another configured provider accepted by announcing that provider’s issuer.
If the iss claim of the tokens legitimately differs from the URL used to fetch the discovery document, for example because discovery is fetched over a cluster-internal URL while tokens carry the public URL, or with Oracle IDCS, whose tokens carry the provider wide issuer https://identity.oraclecloud.com/, configure the expected value with issuer-identifier. The same value is the expected iss for IdTokenClaimsValidator and ProviderResolver when micronaut.security.authentication=idtoken:
If you do not fetch the discovery document, set openid.issuer to the expected iss value and openid.fetch-configuration to false, instead of disabling issuer validation. If there is neither a configured issuer nor a discovery document, the provider metadata has no issuer and the validator rejects every token.
Issuer validation can be disabled with micronaut.security.oauth2.openid.claims-validation.issuer=false, but doing so removes this protection; prefer issuer-identifier.
22.3.1.3 State Parameter
By default, this library will include a state parameter as described in RFC 6749 to authentication requests. A JSON serialized object is stored that contains a nonce value used for validation.
Because the validation of the state requires the state to be stored somewhere temporarily, a StatePersistence bean must be present to retrieve the state for validation. The default implementation stores the state in an HTTP cookie. To configure how the cookie is built, see the following configuration options:
Whether the cookie is a session cookie. A session cookie does not have an expiration date. cookie-max-age is ignored if session cookie is set to true. Default value (false).
Sets the maximum age of the cookie. Default value (5 minutes).
You can provide your own implementation, however an implementation of state persistence that stores the state in an http session has also been provided.
To override the behavior of any of those beans, provide an implementation and replace the default one.
22.3.1.4 PKCE
Using OpenID Connect Discovery by setting micronaut.security.oauth2.clients.*.openid.issuer and the Authorization server specifies via
code_challenge_methods either plain, S256, or both, Micronaut security automatically sends a code challenge in the authorization request as specified in Proof Key for Code Exchange (PKCE) Spec.
Using manual OAuth 2.0 Client configuration, you can specify the challenge method supported by setting micronaut.security.oauth2.clients.*.authorization.code-challenge-method.
ClientCredentialsClient caches the token response. If the cached access token is expired, they renew it automatically.
22.3.2.1 HTTP Client Filter for Client Credentials
Micronaut Security includes ClientCredentialsHttpClientFilter. This HTTP Client Filter allows you to automatically include an access token to an outgoing request HTTP Header. It obtains the access token via a Client Credentials request.
For example, the next configuration adds an access token to the requests' HTTP Headers done via the HTTP Client inventory. It obtains the access token with a Client Credentials request with the OAuth 2.0 client companyauthserver.
The resource owner password credentials grant is described in RFC 6749. In short, credentials are passed directly to the token endpoint and if authentication succeeds, the token endpoint responds with the appropriate token.
The process that handles the token response onward is the same for both authorization code and password grants. See the following high level flow diagrams:
OAuth 2.0 Provider
OpenID Provider
In Micronaut, the password grant is supported by setting the grant-type configuration option in the client configuration. For example:
This example above is not intended to be a complete configuration reference
When a client is configured for the password grant type, the authorization code endpoints will not be available and instead an AuthenticationProvider will be created that will participate in the normal login flow.
22.4 Endpoints
22.4.1 OpenID End Session
Part of the OpenID Connect specification includes a draft document titled Session Management. Because the specification is a draft, some providers have implemented it differently or not at all. See the following diagram for how end session works with default configuration:
If any configured OpenID provider supports end session behavior, a route will be registered that responds to /oauth/logout and redirects to the provider to log the user out. A parameter is also sent to the provider that indicates what URL the provider should redirect the user to after logging out. The default URL is /logout which will cause the local authentication to also be cleared and a final redirect issued according to the LogoutHandler.
The end session URL advertised by the provider (the end_session_endpoint of its discovery document, or the URL derived from the issuer for providers that do not advertise one) is used as an opaque URI: the logout parameters, such as post_logout_redirect_uri or id_token_hint, are percent-encoded and appended to its query component, and any query component already present in the provider URL is preserved. The provider URL is never expanded as a URI template. The provider URL must be an absolute http or https URL with a host and without user information. If it is empty, takes another form (a relative URL, another scheme, or https://user:password@provider.example/logout) or is not a valid URI, no redirect is issued and /oauth/logout responds with 404.
All of the above is configurable through micronaut.security.oauth2.openid:
Whether the username of an authentication built from an OpenID provider response, by the default OpenID authentication mapper at login or by the UserInfo endpoint token validator, is the sub claim qualified with the provider name (providerName:subject) instead of the bare sub claim.
The sub claim is only unique within one provider. If not set, the username is qualified only when more than one enabled OAuth 2.0 client, other than client-credentials-only clients, is configured under micronaut.security.oauth2.clients. It does not apply when micronaut.security.authentication is idtoken.
The URI the OpenID provider should redirect to after logging out. Default value ("/logout").
To enable the usage of the /logout endpoint, see the section on the Logout Endpoint.
The get-allowed configuration option must be set to true because the OpenID provider will issue a redirect which is a GET request.
This library supports end session for Auth0, AWS Cognito, and Okta out of the box. The EndSessionEndpointResolver is responsible for determining which EndSessionEndpoint will be used for a given provider, if any.
If you are using a custom domain URL for your auth server, instead of inferring it, you can set the authorization server you use by setting the property micronaut.security.oauth2.clients.*.authorization-server.
For Okta and Oracle Cloud, OktaEndSessionEndpoint sends an id_token_hint parameter. It is the ID token obtained during the authorization code flow when that token is available in the authentication attributes. Otherwise, when micronaut.security.authentication is set to idtoken, it is the token which authenticated the current request, that is, the ID token cookie. Other tokens present in the request, such as an Authorization header added by a gateway or reverse proxy, are never sent to the OpenID provider.
Before choosing any of the default providers, the endpoint resolver will first look for an EndSessionEndpoint bean with a named qualifier that matches the name of the client in configuration. If no bean is found then the default endpoints will be matched against the issuer URL.
If for example you are using one of the providers that is supported out of the box and you don’t want the end session support, it is possible to disable it per client.
The end session enabled flag. Default value (true).
22.4.2 Introspection
It is possible to configure the introspection endpoint URL for OAuth 2.0 and OpenID providers, however Micronaut currently does not use this configuration in any way.
It is possible to configure the revocation endpoint URL for OAuth 2.0 and OpenID providers, however Micronaut currently does not use this configuration in any way.
Micronaut Security OAuth2 registers a bean of type TokenValidator for each OpenID provider.
It provides token validation using the remote authorization server’s
UserInfo endpoint.
The UserInfo endpoint URL is obtained automatically from the authorization server’s metadata (obtained by visiting the .well-known/openid-configuration endpoint of the authorization server).
Set micronaut.security.oauth2.userinfo.validator to false to disable UserInfo endpoint token validation.
Provider binding
The Authentication created from a UserInfo response is bound to the provider whose UserInfo endpoint answered:
The attribute oauth2Provider (OauthAuthenticationMapper.PROVIDER_KEY) is always set to the provider name. A value with that key in the UserInfo response is ignored, so ProviderResolver always resolves the provider which validated the token.
The username returned by Authentication.getName() is qualified with the provider name, followed by : and the sub claim, for example okta:248289761001, when micronaut.security.oauth2.openid.qualify-username-with-provider is true. If the property is not set, the username is qualified when more than one enabled OAuth 2.0 client, other than client-credentials-only clients, is configured under micronaut.security.oauth2.clients. The sub attribute still holds the unqualified subject. Set the property explicitly if your application keys data on the name, so adding an unrelated client later does not rename every user. The default OpenIdAuthenticationMapper used at login applies the same rule and the same property, so a user has the same name in a browser login and in a bearer request. See User Details Mapping.
Client names under micronaut.security.oauth2.clients must not contain :. Such a name is not supported by the configuration binding, and the UserInfo validator additionally rejects it with a ConfigurationException when usernames are qualified, because the provider alpha with the subject beta:victim and the provider alpha:beta with the subject victim would both be named alpha:beta:victim. The sub claim may contain :, since the provider name is everything before the first : of a qualified name.
A subject is only unique within its issuer. Without this binding, whoever controls one configured provider could answer a UserInfo request with the subject of a user at another configured provider and your application would treat the request as coming from that user.
Only the identity is bound to the provider. Roles are still resolved from the attributes of the UserInfo response (for example by DefaultRolesFinder reading the roles claim), so a provider you configure is trusted to state the roles of its own users. Only configure providers you trust, and use micronaut.security.token.roles-name or a custom RolesFinder if the claim is not appropriate for a provider.
22.4.5 Protected Resource Metadata
RFC 9728 metadata format that an OAuth 2.0 client or authorization server can use to obtain the information needed to interact with an OAuth 2.0 protected resource.
You can configure whether to expose the protected resource metadata:
Whether /.well-known/oauth-protected-resource is exposed. Default value: true.
A GET endpoint is exposed in /.well-known/oauth-protected-resource. The API to control the metadata is:
ProtectedResourceMetadataProvider
You can create a bean replacement for it if the default implementation does not fit your needs.
22.5 Custom Clients
The center of the OAuth 2.0 authorization code grant support is the OauthClient for standard OAuth 2.0 and OpenIdClient for OpenID. The current implementation builds clients based on configuration. It is possible however to register a custom client and that client will automatically have the routes associated with it to enable the authorization code grant flow.
The OauthClient interface is simple and only requires three methods.
public interface OauthClient {
/**
* @return The provider name
*/
String getName();
/**
* Responsible for redirecting to the authorization endpoint.
*
* @param originating The originating request
* @return A response publisher
*/
Publisher<MutableHttpResponse<?>> authorizationRedirect(HttpRequest<?> originating);
/**
* Responsible for receiving the authorization callback request and returning
* an authentication response.
*
* @param request The callback request
* @return The authentication response
*/
Publisher<AuthenticationResponse> onCallback(HttpRequest<Map<String, Object>> request);
}
The getName method is used to build the URLs used to trigger the client methods
The authorizationRedirect method returns a response that redirects to the provider
The onCallback method receives a callback authorization response and returns a response including either an authentication failure or the user details.
Because of how generic this interface is, it is possible to implement authentication for any provider that follows the redirect / redirect back pattern. For example one could implement support for OAuth 1.0a providers (looking at you, twitter).
22.6 HTTP Clients for the Provider
Micronaut Security creates HTTP clients to talk to the identity provider on behalf of your application:
These clients copy the settings of the default HTTP client configuration (micronaut.http.client.), such as timeouts, proxy or SSL settings, but they *never follow redirects, regardless of micronaut.http.client.follow-redirects. A redirect returned by the provider is never followed: the redirect target is not requested, and since the redirect response is not a valid provider response the operation fails: the token request fails, the provider metadata is not available, the token is not validated against the UserInfo endpoint or the JWK Set is not loaded.
Following a redirect from the identity provider would let a malicious or compromised provider make your application send the token request, together with the client credentials, or the user’s bearer token, to any address your application can reach, such as loopback, internal services or cloud metadata endpoints (Server-Side Request Forgery). The application would then treat whatever JSON it finds at that address as the response of the provider. The OAuth 2.0 and OpenID Connect specifications do not require clients to follow redirects for these endpoints.
If the token endpoint of a provider has moved, update the configuration of the provider (micronaut.security.oauth2.clients..token.url, micronaut.security.oauth2.clients..openid.issuer, etc.) instead of relying on redirects.
A named service-specific client configuration (micronaut.http.services.<name>.) whose name matches the provider name (for the token endpoint) or the JWKS provider name (for JWKS retrieval) only contributes its settings: redirects are never followed, even with follow-redirects: true. An HttpClient bean named after the provider is no longer used to call the token endpoint, because its redirect policy cannot be enforced. Micronaut Security creates a client from the named service configuration, or from the default configuration if there is none, with the load balancer of the service, and logs a warning. Use micronaut.http.services.<provider>. to customize the client of a provider.
The clients Micronaut Security creates have no client id, so client filters scoped to a service id (@Filter(serviceId = "<provider>")) are not applied to them; client filters without a service id are. A relative endpoint url is resolved against micronaut.http.services.<provider>.url; without such a configuration, configure absolute urls.
The programmatic entry points which take an HttpClient, such as ClientCredentialsClient.of(HttpClient, OauthClientConfiguration) or the DefaultTokenEndpointClient(HttpClient) constructor, use the given client as is: the caller is responsible for keeping redirects disabled.
22.7 Proxy .well-known requests to Auth Server
You can proxy GET requests to /.well-known/oauth-authorization-serverRFC8414
and /.well-known/openid-configurationOpen ID Connect Discovery to an authorization server.
To proxy set the following configuration properties to true:
This provider must be configured to authenticate as an OAuth 2.0 client. The client should be mapped to a DATA ROLE or APPLICATION IDENTITY defined in
an Oracle Database.
In the example below, the provider is configured to authenticate via a Client Credentials request against an Azure Entra ID authorization server.
The previous example configures Oracle JDBC to load an EndUserSecurityContextProvider
with the name of this provider: ojdbc-provider-micronaut-end-user-security-context. With this configuration, Oracle JDBC receives an oracle.jdbc.EndUserSecurityContext each time it executes a database operation.
Almost every network request Oracle JDBC sends to the database is considered a database operation. This includes SQL execution, row fetching, commit/rollback,
and LOB data access. When an EndUserSecurityContext is provided to Oracle JDBC, all of these operations become subject to DATA GRANT policies defined in
Oracle Database.
A DATA GRANT policy can apply controls based on which user is accessing the database and which application they are using.
This offers a more granular approach to data security when compared to the traditional model, in which all application users access the database as the
same database user.
23.3 Application Authorization and User Identity
An EndUserSecurityContext provided to Oracle JDBC encapsulates two security tokens:
Database Access Token This token authorizes a Micronaut application to access the database. The provider requests this token by sending an OAuth 2.0 Client Credentials request to the server token endpoint defined by the parameter:
End User Token This token identifies the end user of a Micronaut application. It is typically received in the Authorization header of an incoming HTTP
request. Micronaut Security resolves the token with the TokenResolver API. The provider retrieves this token using Micronaut’s SecurityContextHolder.
These two tokens allow Oracle Database to make authorization decisions based on the application user who is accessing data and the application they are using.
23.4 Application Managed Data Roles and Attributes
The EndUserSecurityContext provided to Oracle JDBC may include application-managed DATA ROLE names or END USER CONTEXT attributes
that are derived from an Authentication present in Micronaut’s SecurityContextHolder.
23.4.1 Application Managed Data Roles
If one or more roles in Authentication begin with a specified prefix, then the provider will
recognize them as application-managed DATA ROLE names that should be enabled for the end user.
The prefix is specified by the parameter:
The default value for this parameter is ORACLE_DATA_ROLE_.
The name of a DATA ROLE should appear after the specified prefix. For example, with the default prefix, if the authenticated user has a role with the value ORACLE_DATA_ROLE_ADMIN, the
provider recognizes a DATA ROLE named ADMIN.
In addition to the role prefix, the provider can also be configured with a fixed set of data role names using the parameter:
You can use the RunAs annotation to grant a DATA ROLE for a method execution:
package example.micronaut.repository;
import example.micronaut.domain.EmployeeEntity;
import example.micronaut.dto.SalaryAggregates;
import io.micronaut.data.annotation.Query;
import io.micronaut.data.jdbc.annotation.JdbcRepository;
import io.micronaut.data.model.query.builder.sql.Dialect;
import io.micronaut.data.repository.CrudRepository;
import io.micronaut.security.annotation.RunAs;
@JdbcRepository(dialect = Dialect.ORACLE)
public interface EmployeeRepository extends CrudRepository<EmployeeEntity, Long> {
@RunAs("ORACLE_DATA_ROLE_COMPENSATION_ANALYST")
@Query("SELECT MIN(salary) AS min, MAX(salary) AS max, SUM(salary) AS sum, COUNT(*) AS count FROM hr.employees")
SalaryAggregates getSalaryAggregates();
}
23.4.3 End User Context Attributes
The provider can read END USER CONTEXT attributes from one or more named attributes of the Authentication.
The attribute names are specified as a comma-separated list by the parameter:
The default value for this parameter is ORACLE_CONTEXT_ATTRIBUTES.
A JSON object containing the attributes of one or more END USER CONTEXT objects can appear as the value of one of the configured authentication attributes. For example, an authentication attribute named ORACLE_CONTEXT_ATTRIBUTES might have the following value:
The provider will recognize that attribute value as the attributes of two END USER CONTEXT objects named user_details and location_info, each declared within a database schema named app_schema.
In addition to authentication attributes, the provider can also be configured with a fixed set of attributes using the parameter:
No default value. A value must be configured for this parameter.
clientId
OAuth 2.0 client identifier.
No default value. A value must be configured for this parameter.
clientSecret
OAuth 2.0 client secret. This parameter is marked as a sensitive OJDBC provider parameter.
No default value. A value must be configured for this parameter.
scope
Optional OAuth 2.0 scope sent with the Client Credentials request.
No default value. This parameter is optional.
dataRoles
A fixed set of DATA ROLE names to enable for all end users. This should be one or more DATA ROLE names, separated by commas: common_user_role, common_app_role, read_only_role
No default value. This parameter is optional.
rolePrefix
The prefix used to match the user’s roles that the provider should recognize as a DATA ROLE. The name of the DATA ROLE should appear after the prefix. For example, this parameter might be set to ORACLE_DATA_ROLE_. For a role named ORACLE_DATA_ROLE_ADMIN, the provider will recognize a DATA ROLE named ADMIN and enable that DATA ROLE for the end user. This should be a unique string that is unlikely to collide with an application role that is not intended to be recognized as a DATA ROLE.
ORACLE_DATA_ROLE_
endUserContextAttributes
Optional JSON object containing fixed Oracle Database END USER CONTEXT attributes. The object keys are END USER CONTEXT names, and each value must be a JSON object containing the attributes for that context.
No default value. This parameter is optional.
attributeNames
A comma-separated list of Micronaut Security authentication attribute names whose values are used to derive END USER CONTEXT attributes from the current authentication. Each named authentication attribute value must be a JSON object value, or a string containing a JSON object. The object keys are END USER CONTEXT names, and each value must be a JSON object containing the attributes for that context.
ORACLE_CONTEXT_ATTRIBUTES
24 Ahead-of-time optimizations
Micronaut AOT is a framework which implements ahead-of-time (AOT) optimizations for Micronaut application and libraries. Those optimizations consist of computing at build time things which would normally be done at runtime]
Micronaut Security offers several ahead-of-time optimizations.
24.1 Micronaut Security AOT Configuration
With Micronaut Gradle Plugin, you can use aotPlugins configuration to declare additional AOT modules to be used:
When you use OpenID Connect in a Micronaut application, the application constructs a URL by appending .well-known/openid-configuration to the value you specify for each OAuth 2.0 client via
micronaut.security.oauth2.clients.*.openid.issuer. It visits the URL to fetch OpenID Connect metadata related to the specified authorization server and configure itself.
However, this is a network request which may be slow. Moreover, the application will probably need to execute this network request to serve the first request.
You can use Micronaut Security ahead-of-time build optimizations to do the request at build-time.
To enable this optimization, add
micronaut.security.openid-configuration.enabled=true to aot.properties.
The application uses the configuration present at the authorization server at build time. The configuration may be out-of-date if the authorization server changes the configuration between the build time and the application startup.
Micronaut security supports JWKS (JSON Web Key Sets) either specifying them directly or via the jwks_uri obtained when fetching the OpenID Connect metadata. Micronaut security uses JWKS to validate the signature of tokens issued by another application or an authorization server.
Micronaut applications need to make a network request to fetch JWKS. You can use Micronaut Security ahead-of-time build optimizations to make the request at build-time.
To enable this optimization, add
micronaut.security.jwks.enabled.enabled=true to aot.properties.
The application uses the JWKS exposed by the authorization server at build time. The JWKS may be out-of-date if the authorization server changes them between build time and the application startup. You can clear keys with JwksSignature::clear or JwkSetFetcher::clearCache.