On this page
Security
Micronaut Security is a fully featured and customizable security solution for your applications.
|
Note
|
Micronaut Security 3.x requires Micronaut 3.x. |
For this project, you can find a list of releases (with release notes) here:
Micronaut Security includes the following new features and improvements.
What’s New in Micronaut Security 3
-
Improvements to many APIs
-
Consolidated authentication state into a single interface
-
The SecurityRule API is now reactive
-
A
getRolesmethod was added to Authentication -
New static methods on Authentication and AuthenticationResponse have been added to help create authentication related objects
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 4.18 breaking changes
-
Signed CSRF tokens (
micronaut.security.csrf.signature-key) are now bound to the name of the authenticated user in addition to the session identifier. CSRF tokens issued by a previous version are rejected after upgrading; users have to log in again to obtain a new CSRF token. The user name bound into the token isAuthentication#getName(), which is thesubclaim of the token issued at login, so custom authentication mappers (for example anOpenIdAuthenticationMapper#getUsernameoverride) are supported as long as the token issued at login carries that name. Principals qualified with a provider name which share a rawsubattribute, such as users validated via the UserInfo endpoints of several OpenID providers, are bound separately. Withmicronaut.security.authentication=idtokenthe cookie carries the provider’s ID token, which Micronaut Security does not issue, and requests are named after itssubclaim (or thename-keyclaim) rather than after the user name returned by theOpenIdAuthenticationMapper, whichDefaultOpenIdAuthenticationMapperqualifies with the provider name when several clients are enabled. IdTokenLoginHandler therefore binds the CSRF cookie to the name resolved from the ID token, so the CSRF token issued at login is accepted on later requests whatever the user name of the mapper. The login handlers issuing a JWT supply the LoginCookieProvider beans with the authentication named as token based authentication names the user from the issued token (themicronaut.security.token.name-keyclaim, falling back to the principal name), so the binding matches on later requests; the attribute itself is never bound, which keeps users of different providers sharing aname-keyvalue apart. -
CsrfTokenGenerator has a new method
generateCsrfToken(request, authentication)and LoginCookieProvider has a new methodprovideCookie(request, authentication). Both have default implementations which delegate to the existing methods. Implementations issuing values which should be bound to the authenticated user should override them, since the login request does not carry the authentication yet. -
The method
TokenCookieLoginHandler#getCookies(AccessRefreshToken, HttpRequest)has been deprecated. UseTokenCookieLoginHandler#getCookies(Authentication, AccessRefreshToken, HttpRequest)instead. An override of the deprecated method is still invoked on login (including token refresh), and the values of the cookies supplied by LoginCookieProvider beans are then replaced with the ones bound to the authenticated user, so such an override keeps its customizations and the CSRF cookie stays bound. A warning is logged at startup if the deprecated method is overridden; move the override to the new method before the deprecated one is removed. -
Starting with 4.18.2, the password grant flow of an OpenID client maps the ID token with the application’s global OpenIdAuthenticationMapper when no mapper is registered for the client, as the authorization code flow does. Previously it always used DefaultOpenIdAuthenticationMapper, even when a bean replaced it or another mapper was marked
@Primary. Users such a mapper rejects can no longer log in through/loginor HTTP Basic authentication, and admitted users receive the name, roles and attributes the mapper assigns instead of the ID token subject with no roles.In the password grant, the global mapper is the OpenIdAuthenticationMapper bean without a qualifier (a
@Primarybean counts as such). A mapper registered with a@Namedqualifier for another client is never used by the password grant of a client without its own mapper: when no unqualified mapper exists, for example because the default mapper is replaced by a@Namedmapper, the password grant of that client is disabled and every login through it fails, whereas previously the replaced default mapper was used. When several unqualified mappers exist and none is@Primary, Micronaut selects DefaultOpenIdAuthenticationMapper if it is still present (it is the@DefaultImplementationof the interface, so a plain@Singletonmapper that neither replaces it nor is@Primaryis silently ignored), otherwise the application fails to start; replace the default mapper with@Replacesor mark your mapper@Primary. Annotate the global mapper with@Primaryor register a named mapper for every OpenID client using the password grant. -
Starting with 4.18.2, the OpenID authorization code flow maps the ID token of a client without a provider-specific OpenIdAuthenticationMapper with the global mapper: the
OpenIdAuthenticationMapperbean without a qualifier (a@Primarybean counts as such). Previously the global mapper was resolved with an unqualified lookup, which returns a mapper registered with a@Namedqualifier for another client when it is the only mapper, for example because it replaces the default mapper; that other client’s mapper then decided who was authenticated through the client without a mapper, and with which name and roles. When DefaultOpenIdAuthorizationResponseHandler is in use, an OpenIdClient is now only created when a mapper named after the client or an unqualified mapper exists; otherwise the client is skipped and its/oauth/login/<name>route is not available. Applications with a custom OpenIdAuthorizationResponseHandler (including a subclass of the default handler which overrideshandle), which may authenticate without a mapper, are not affected by this requirement. When several unqualified mappers exist and none is@Primary, the application fails to start. A replaced default mapper together with a@Namedmapper for a different client, a setup which previously failed to start, now works: the unqualified mapper is the global one. -
The constructor
DefaultOpenIdAuthorizationResponseHandler(ReactiveOpenIdTokenResponseValidator, OpenIdAuthenticationMapper, TokenEndpointClient, OauthRouteUrlBuilder, StateValidator, PkcePersistence)has been deprecated and is no longer the injection point. UseDefaultOpenIdAuthorizationResponseHandler(ReactiveOpenIdTokenResponseValidator, BeanContext, TokenEndpointClient, OauthRouteUrlBuilder, StateValidator, PkcePersistence)instead, which resolves the global mapper among the beans without a qualifier. -
Starting with 4.18.2, a HEAD request answered by the HEAD route the router derives from a
@Getmethod is subject to the intercept URL map entries restricted to the HTTP methodGET, unless an entry restricted toHEADmatches the request URI. Previously, a HEAD request only matched entries restricted toHEADor entries without a method, so an entry such aspattern: /admin/, httpMethod: GET, access: isAuthenticated()followed bypattern: /, access: isAnonymous()let anonymous clients run the@Getroute or read the headers of a static resource by sending a HEAD request. Conversely, withpattern: /v1/myResource/, httpMethod: GET, access: isAnonymous()followed bypattern: /v1/myResource/, access: isAuthenticated(), anonymous HEAD requests are now allowed as GET requests are. The same applies to a request of any method that no route matches, which is the case of a request answered with a static resource: it is subject to the entries restricted toGET, unless an entry restricted to its own method matches. A HEAD request answered by an explicitly declared@Headmethod keeps matching the entries restricted toHEADand then the entries without a method. Define an entry withhttpMethod: HEADto apply different access rules to HEAD requests. -
When
micronaut.security.oauth2.clients..proxy-well-known-openid-configurationormicronaut.security.oauth2.clients..proxy-well-known-oauth-authorization-serveris enabled, the proxied request to the authorization server no longer carries the headers (for exampleCookieandAuthorization), cookies or query string of the incoming request. Only a successful JSON response from the authorization server is relayed, with only itsContent-Type,Content-Length,Cache-Control,Expires,ETagandLast-Modifiedheaders; other responses are answered with502 Bad Gateway. Anonymous access is granted only to the well-known path which is actually proxied; a well-known path whose proxy property isfalseis secured as any other route. -
Starting with 4.18.2, token validation via the OpenID provider’s
UserInfoendpoint is disabled by default. AUserInfoendpoint accepts every access token the provider issued, including access tokens issued to other clients, so an application that relied on this validator accepted other clients' access tokens as bearer tokens. Setmicronaut.security.oauth2.userinfo.validatortotrueto enable it. See the UserInfo Endpoint section. -
Authenticator evaluates the authentication providers one at a time in precedence order instead of subscribing to all of them concurrently. With the default
micronaut.security.authentication-provider-strategy: ANY, the response of the highest precedence provider that accepts the credentials is used, regardless of how fast the other providers answer, and lower precedence providers are not subscribed to once a provider has accepted the credentials. Previously the response of the fastest provider was used, so a user accepted by several providers could be granted the roles of a lower precedence provider. With theALLstrategy the providers are still all evaluated, sequentially, and the response of the first provider in precedence order that accepts the credentials is used. -
Starting with 4.18.2, issuer claim matching is stricter. Previously, the
issclaim was accepted when the expected issuer (micronaut.security.token.jwt.claims-validators.issuer, ormicronaut.security.oauth2.clients..openid.issuerfor IdTokenClaimsValidator and DefaultProviderResolver) merely ended with the claim value once the scheme and trailing slash were removed, so for a configured issueradmin-portalvalues such asportal,l,/,https://or an empty string passed validation, and forhttps://idcs-abc.identity.oraclecloud.comthe parent domainhttps://identity.oraclecloud.com/did. Now theissclaim must be equal to the expected issuer. Suffixes and parent domains are never accepted. Formicronaut.security.token.jwt.claims-validators.issuer(IssuerJwtClaimsValidator), a value starting withhttp://orhttps://is compared after removing the scheme and a single trailing slash; the scheme is now matched case-insensitively (HTTPS://equalshttps://), 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 opaqueStringOrURIand is compared verbatim, soadmin-portal/no longer matchesadmin-portal. Surrounding whitespace in the claim is not ignored. Ifmicronaut.security.token.jwt.claims-validators.issueris present but has no value (for exampleissuer:in YAML), IssuerJwtClaimsValidator now rejects every token and logs a warning at startup; previously it accepted anyissclaim. For the OpenID client validators (IdTokenClaimsValidator and DefaultProviderResolver), theissclaim must be identical to the expected issuer (micronaut.security.oauth2.clients..openid.issuer-identifierif set, otherwiseopenid.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 anhttp://claim no longer matches anhttps://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 whoseissdiffers from the configured issuer, configure the exactissvalue:claims-validators.issuerfor IssuerJwtClaimsValidator, andopenid.issuer-identifierfor the OpenID client validators (for examplehttps://identity.oraclecloud.com/for Oracle IDCS, whose tenant specificopenid.issueris only the discovery URL). -
ClaimsUtils.endsWithIgnoringProtocolAndTrailingSlash(String, String)has been deprecated and now delegates toClaimsUtils.equalsIgnoringProtocolAndTrailingSlash(String, String), which implements the rule above. -
Starting with 4.18.2, when
micronaut.security.authenticationis set toidtoken, IdTokenClaimsValidator ignores OAuth 2.0 clients configured withmicronaut.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 withmicronaut.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 theaudclaim. Keep IdTokenClaimsValidator, or an equivalent custom GenericJwtClaimsValidator, active to isolate clients that share an OpenID provider. Inidtokenauthentication 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 constructorDefaultProviderResolver(List<OpenIdClientConfiguration>)has been deprecated. UseDefaultProviderResolver(List<OpenIdClientConfiguration>, Collection<OauthClientConfiguration>)instead. -
The LDAP manager context no longer uses the JNDI LDAP connection pool by default. The JDK pool is shared by the whole JVM and, unless the
com.sun.jndi.ldap.connect.pool.system properties say otherwise, it is unbounded and never closes idle connections, which let a burst of failed login attempts exhaust the connections of the directory and lock valid users out. Setmicronaut.security.ldap..context.pooledtotrueto restore pooling. The pool is then bounded bymicronaut.security.ldap..context.pool.max-size(default 20),pref-size(default 5) andidle-timeout(default 5 minutes), which Micronaut applies as thecom.sun.jndi.ldap.connect.pool.maxsize,prefsizeandtimeoutsystem properties: a value set in configuration always wins, a value not set in configuration keeps a system property already set on the command line and otherwise falls back to the default. A login waits at mostconnect-timeout(default 10 seconds) for a pooled connection when the pool is saturated. Negative values are rejected. Acom.sun.jndi.ldap.connect.poolentry undermicronaut.security.ldap..context.propertiesis now ignored: contexts bound with user credentials are never pooled. -
With
micronaut.security.reject-not-found: false, SecurityFilter now rejects a request that matches no route but resolves to a static resource when no SecurityRule allows it. Previously such static resources were served to anonymous clients. Applications that relied on this behavior must allow the static resources explicitly, for example with an intercept URL map entrypattern: /assets/**andaccess: isAnonymous(). -
The constructor
SecurityFilter(Collection, Collection, SecurityConfiguration)has been deprecated. UseSecurityFilter(Collection, Collection, SecurityConfiguration, StaticResourceMatcher)instead. A SecurityFilter created with the deprecated constructor has no StaticResourceMatcher and fails closed: withmicronaut.security.reject-not-found: falseit now rejects every request that matches no route and that no security rule allows, instead of letting it through, and logs a warning at startup. This only affects applications that instantiate the filter themselves, or that extend it (for example with@Replaces(SecurityFilter.class)) and call the deprecatedsuper(…)constructor; call the constructor that takes aStaticResourceMatcherinstead. The filter created by Micronaut Framework receives the matcher, whose default implementation resolves the request path with the server’sStaticResourceResolver. -
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,Marketingto the single roleSales,Marketinginstead of the two rolesSalesandMarketing. 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 atDEBUGlevel with its string representation, which wrote these values to the log. UsegetSource()orgetRefreshToken()to obtain the value in your listeners. -
SignedRefreshTokenGenerator no longer includes the token being validated in its
WARNlog 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 atDEBUGwithout the token. -
Log statements no longer include credentials, tokens or claim values: the
Authorizationheader (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
UserInfoendpoint 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-patternsas a regular expression. An entry made only of hexadecimal digits, dots, colons and(for example127.0.0.1or192.168.1.) is now an IP wildcard whose dots and colons match literally. Previously192.168.1.was the regular expression192.168.1., which also admitted192.168.10.5or192.168.100.5. Entries containing any other character (for example192\.168\.1\.\d+), and entries starting with a dot (for example the "allow all" regular expression.), keep being compiled as regular expressions. Ain the middle of a wildcard matches within a single address segment (192.168..1does not match192.168.2.3.1), while a trailingmatches the rest of the address. To allow every address use0.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
Orderedorder 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. -
An ExecutorAuthenticationProvider or HttpRequestExecutorAuthenticationProvider whose
getExecutorName()returns a name other thanblockingoriois now subscribed on the executor it names. Previously such a provider was treated as non-blocking andauthenticate()ran on the calling thread, the Netty event loop in a running server, so a slow credential check could stall unrelated requests. If noExecutorServicebean with the returned name exists, the provider now runs on theblockingexecutor and a warning is logged. Imperative authentication providers whoseauthenticatemethod, or whose class, is annotated with@Blockingare now also run on theblockingexecutor, as their javadoc documents. The annotation is read from the compile-time bean definition metadata, so it is honoured for providers created by the bean context, not for instances registered at runtime. -
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 thesubclaim. The unqualified subject is kept in thesubattribute. The username of authentications created from an ID token withmicronaut.security.authenticationset toidtokenis not qualified. Applications with several clients which key data on the username must migrate those keys, or setmicronaut.security.oauth2.openid.qualify-username-with-providertofalseto restore the previous (unsafe) behavior. See User Details Mapping. -
JWTClaimsSetGenerator now writes the
subclaim after the authentication attributes, so thesubclaim of a generated JWT is alwaysAuthentication.getName(). Previously an authentication attribute namedsubreplaced the principal name in the token, which turned a provider-qualified username back into the bare subject on every later request.JWTClaimsSetGenerator#populateSubcan be overridden to issue another subject, but then the user name resolved from the token on later requests no longer matchesAuthentication#getName()at login, and signed CSRF tokens issued at login (micronaut.security.csrf.signature-key) are rejected. -
The constructor
DefaultOpenIdAuthenticationMapper(OpenIdAdditionalClaimsConfiguration, AuthenticationModeConfiguration)has been deprecated. UseDefaultOpenIdAuthenticationMapper(OpenIdAdditionalClaimsConfiguration, AuthenticationModeConfiguration, OpenIdConfiguration, Collection<OauthClientConfiguration>)instead. -
Starting with 4.18.2,
micronaut.security.token.jwt.signatures.jwks.*.key-typeis 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 akey-typenow only verifies tokens signed with a key of that type. The setting no longer defaults toRSA; unless it is configured, keys of any type are matched, which preserves the previous behavior for applications that do not set it.JwksSignatureConfigurationProperties.DEFAULT_KEYTYPEis deprecated, andJwksSignatureConfiguration.getKeyType()returnsnullfor a JWKS without a configuredkey-type. Thekey-typevalue is case-insensitive and must be one ofRSA,EC,OKPoroct; any other value now fails application startup with aConfigurationException. A key published in the JWKS with an explicitalgis only used to verify tokens whose header declares that algorithm; keys withoutalgmatch 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)returnsnulland/oauth/logoutdoes not redirect, instead of throwing or redirecting to a malformed URL. The provider URL must be an absolutehttporhttpsURL with a host and without user information: a relative URL, another scheme, an empty or non-ASCII host, orhttps://user:password@provider.example/logoutnow 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 to0sto restore the previous behavior. Concurrent requests share one retrieval per signature configuration and url, bounded bymicronaut.security.token.jwt.signatures.jwks-client.retrieval-timeout(default 30 seconds); a retrieval which exceeds it is treated as a failure. -
JwkSetFetcher
clearCache(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 wholejwkscache, 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. UseDefaultJwkSetFetcher(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 tomicronaut.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_uriparameter of the authorization code grant token request. Previously the value stored in thestateparameter of the authorization response was used, which allowed anyone redirecting the browser to the callback endpoint to choose theredirect_urisent 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. UseDefaultOauthAuthorizationResponseHandler(TokenEndpointClient, OauthRouteUrlBuilder, StateValidator, PkcePersistence)instead. -
The constructor
OauthCodeTokenRequestContext(AuthorizationResponse, SecureEndpoint, OauthClientConfiguration, String)has been deprecated. UseOauthCodeTokenRequestContext(AuthorizationResponse, OauthRouteUrlBuilder, SecureEndpoint, OauthClientConfiguration, String)instead. A context created with the deprecated constructor no longer sends aredirect_uriparameter to the token endpoint. -
Starting with 4.18.2, the JSON Web Key Set published at the
jwks_uriof an OpenID provider is registered as a signature configuration for request tokens only whenmicronaut.security.authenticationis set toidtoken, as it was before Micronaut Security 4.8.0. Incookie,sessionandbearermodes, 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 withmicronaut.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.
-
Starting with 4.18.2, in
idtokenauthentication mode the JWKS signature configuration of an enabled OpenID client is registered as soon as the client is configured, even if the provider’s discovery document cannot be fetched when the application starts. Previously a provider unreachable at startup left the application without that signature configuration, so an application relying on an OpenID client as its only source of verification keys accepted unsigned (alg=none) tokens until it was restarted. Thejwks_uriand the issuer are now resolved from the provider metadata on demand, bounded bymicronaut.security.token.jwt.signatures.jwks-client.failure-backoff; tokens signed with the provider’s keys are rejected while the metadata is unavailable. TheJwksSignatureConfigurationbean of an OpenID client is no longer aJwksSignatureConfigurationPropertiesinstance, andgetUrl()throws anIllegalStateExceptionwhile the provider metadata is unavailable. -
Single-valued keys directly under
micronaut.security.ldap, such as the global switchmicronaut.security.ldap.enabled, no longer create an LdapConfiguration named after the key. Previouslymicronaut.security.ldap.enabled: truecreated a configuration and an LdapAuthenticationProvider namedenabledwith no server, whose failures turned login attempts for unknown usernames into HTTP 500 responses and allowed username enumeration. Only keys with nested properties, for examplemicronaut.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. AnHttpClientbean 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 configurationmicronaut.http.services.<provider>.*, or from the default client configuration, instead. See HTTP Clients for the Provider. -
The constructor
OpenIdProviderMetadataFetcherFactory()has been replaced byOpenIdProviderMetadataFetcherFactory(BeanContext, HttpClientConfiguration)and the factory methodcreateOpenIdProviderMetadataFetcher(OpenIdClientConfiguration, HttpClient)bycreateOpenIdProviderMetadataFetcher(OpenIdClientConfiguration). The class is internal API. -
Starting with 4.18.2, the JSON Web Key Set registered for the
jwks_uriof an OpenID client is bound to the issuer of that client (theissuerasserted by the provider metadata or, if it asserts none,micronaut.security.oauth2.clients..openid.issuer). Tokens whoseissclaim is not equal to the issuer (tolerating only the case of the scheme and a trailing slash), or that have no or an emptyissclaim, 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 withmicronaut.security.token.jwt.signatures.jwks..url, optionally bound to the expected issuer withmicronaut.security.token.jwt.signatures.jwks.*.issuer. -
LdapAuthenticationProvider no longer returns
AuthenticationFailureReason.USER_NOT_FOUNDwhen the username does not match any directory entry. It returnsCREDENTIALS_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 withmicronaut.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. -
micronaut.security.ldap.*.context.propertiesis now bound as a flat map with verbatim keys, so an entry such asjava.naming.security.protocol: sslreaches JNDI as a single property name. Previously the dotted keys were split into nested maps and silently ignored by JNDI, which meant TLS requested throughcontext.propertieswas never applied and binds were sent in clear text. Code that readLdapConfiguration.ContextConfiguration#getProperties()and expected nested maps must use the flat keys instead. The connection keys managed by Micronaut Security (java.naming.factory.initial,java.naming.provider.url,java.naming.security.authentication,java.naming.security.principal,java.naming.security.credentialsandcom.sun.jndi.ldap.connect.pool) are ignored, with a warning, when set incontext.properties; they cannot be overridden. -
The Authentication created by the
UserInfoendpoint token validator is bound to the provider which answered. The attributeoauth2Provideris always set to the provider name, and whenmicronaut.security.oauth2.openid.qualify-username-with-provideristrue, or it is not set and more than one enabled OAuth 2.0 client is configured undermicronaut.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 onAuthentication.getName()forUserInfo-validated requests must migrate those keys. Client names undermicronaut.security.oauth2.clientscontaining:are not supported by the configuration binding, and theUserInfovalidator additionally rejects them with aConfigurationExceptionwhen usernames are qualified, since they would make the qualified name ambiguous. See the UserInfo Endpoint section. -
With
micronaut.security.authenticationset toidtoken, OktaEndSessionEndpoint (used for Okta and Oracle Cloud) only sends asid_token_hintthe token which authenticated the request, as recorded in the SecurityContext. Previously, it sent the first token found in the request, which could be an unrelatedAuthorization: Bearerheader added by a gateway rather than the ID token cookie. If no token authenticated the request and the authentication has noopenIdTokenattribute, noid_token_hintis sent. -
DefaultProviderResolver no longer picks the first OpenID client whose issuer matches the
issclaim when the claim matches several enabled clients. Theaudclaim (and theazpclaim for multi-audience tokens) must identify exactly one of them byclient-id; otherwise no provider is resolved and/oauth/logoutdoes not redirect to any provider. Previously the user, and with Oracle Cloud or Okta their ID token, could be sent to the wrong provider’s end session endpoint, for example when two Oracle Cloud identity domains, whose ID tokens share the issuerhttps://identity.oraclecloud.com/, are configured. Moreover, withmicronaut.security.authenticationset toidtoken, IdTokenClaimsValidator rejects ID tokens carrying a claim namedoauth2ProvideroropenIdToken. Those names are reserved for the authentication attributes the application sets during the authorization code flow and in theUserInfotoken validator, which/oauth/logouttrusts to pick the provider; since the attributes of an authentication created from an ID token are the claims of the token, a provider emitting such a claim could otherwise have the token sent to another client’s end session endpoint. The validator also compares theazpclaim with the client id case-sensitively; previously the comparison ignored case. See End Session. -
Starting with 4.18.2, IssuerClaimValidator requires the
issclaim 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 ismicronaut.security.oauth2.clients..openid.issuer, ormicronaut.security.oauth2.clients..openid.issuer-identifierwhen set. The comparison is exact, tolerating only the case of the scheme and a trailing slash. Moreover, anissuerannounced 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 whoseissclaim only matched the issuer announced by the provider are now rejected. If the provider issues tokens with anissthat differs from the URL used to fetch the discovery document (for example, discovery over a cluster-internal URL, or Oracle IDCS with a tenant specificissuerand the provider wide issuerhttps://identity.oraclecloud.com/), setmicronaut.security.oauth2.clients.*.openid.issuer-identifierto the expectedissvalue. -
The
UserInfoendpoint token validator no longer sends every bearer token to theUserInfoendpoint of every configured OpenID provider. A JWT is only sent to the provider whose expected issuer (micronaut.security.oauth2.clients..openid.issuer-identifierif set, otherwiseopenid.issuer; the issuer announced by the discovery document is only used when neither is configured) is equal to itsissclaim, tolerating only the case of the scheme and a trailing slash. Tokens which cannot be attributed to exactly one provider (opaque tokens, JWTs withoutiss, or JWTs of an issuer expected by several providers) are only sent when a single enabled OpenID client is configured, or when the provider setsmicronaut.security.oauth2.clients..openid.user-info.validate-opaque-tokenstotrue. Applications with several OpenID providers that rely on opaque access tokens, or whose providers share an issuer (for example several Oracle IDCS tenants), must opt in per provider. See the UserInfo Endpoint section. -
The record UserInfoClientTokenValidatorConfiguration has two new components,
issuerandvalidateOpaqueTokens. The previous constructors are still available and leave both unset.
Micronaut Security 4.0 breaking changes
-
SecurityRule
checkmethod no longer contains the argumentRouteMatch. You can easily retrieve aRouteMatchwith theHttpRequestmethod argument withrequest.getAttribute(HttpAttributes.ROUTE_MATCH).orElse(null). -
For applications with
micronaut.security.authenticationset tocookieandmicronaut.security.redirect.enabledset tofalse, the server responds with 401 HTTP Status code instead of 200 for login failed attempts. -
micronaut.security.intercept-url-map-prepend-pattern-with-context-pathdefaults totrue. 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 ofAuthenticationProvider, you should useAuthenticationProvider<HttpRequest<?>>.
Configuration Changes
Some configuration keys have changed.
| Old | New |
|---|---|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
Classes relocated
Some classes have been renamed and moved from io.micronaut.security:micronaut-security-jwt to io.micronaut.security:micronaut.security.
| Old Pkg | New Pkg |
|---|---|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
Annotation Mappers Removed
The mappers for javax.annotation.security annotations – DenyAll, PermitAll, RolesAllowed – have been removed. Use the Jakarta versions for jakarta.annotation.security annotations instead.
| Removed | Retained |
|---|---|
io.micronaut.security.annotation.DenyAllAnnotationMapper |
io.micronaut.security.annotation.JakartaDenyAllAnnotationMapper |
io.micronaut.security.annotation.PermitAllAnnotationMapper |
io.micronaut.security.annotation.JakartaPermitAllAnnotationMapper |
io.micronaut.security.annotation.RolesAllowedAnnotationMapper |
io.micronaut.security.annotation.JakartaRolesAllowedAnnotationMapper |
Reactive OpenIdAuthenticationMapper
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:
|
Note
|
The previous functionality allows any authenticated user, no matter their role to view sensitive endpoints. |
imports
import io.micronaut.context.annotation.Replaces;
import io.micronaut.context.annotation.Requires;
import io.micronaut.core.annotation.NonNull;
import io.micronaut.http.HttpRequest;
import io.micronaut.inject.ExecutableMethod;
import io.micronaut.management.endpoint.EndpointSensitivityProcessor;
import io.micronaut.security.authentication.Authentication;
import io.micronaut.security.rules.SecurityRuleResult;
import io.micronaut.security.rules.SensitiveEndpointRule;
import jakarta.inject.Singleton;
import org.reactivestreams.Publisher;
import reactor.core.publisher.Mono;@Singleton
@Replaces(SensitiveEndpointRule.class)
class SensitiveEndpointRuleReplacement extends SensitiveEndpointRule {
SensitiveEndpointRuleReplacement(EndpointSensitivityProcessor endpointSensitivityProcessor) {
super(endpointSensitivityProcessor);
}
@Override
@NonNull
protected Publisher<SecurityRuleResult> checkSensitiveAuthenticated(@NonNull HttpRequest<?> request,
@NonNull Authentication authentication,
@NonNull ExecutableMethod<?, ?> method) {
return Mono.just(SecurityRuleResult.ALLOWED);
}
}Micronaut Security 3.1 breaking changes
Micronaut security no longer exposes micronaut-management dependency.
Micronaut Security 3.0 breaking changes
User Details Removal
The UserDetails class has been removed and all usages should be replaced with Authentication.
Affected APIs
Classes Renamed
| Old | New |
|---|---|
io.micronaut.security.oauth2.endpoint.token.response.OauthUserDetailsMapper |
io.micronaut.security.oauth2.endpoint.token.response.OauthAuthenticationMapper |
io.micronaut.security.oauth2.endpoint.token.response.OpenIdUserDetailsMapper |
io.micronaut.security.oauth2.endpoint.token.response.OpenIdAuthenticationMapper |
io.micronaut.security.oauth2.endpoint.token.response.DefaultOpenIdUserDetailsMapper |
io.micronaut.security.oauth2.endpoint.token.response.DefaultOpenIdAuthenticationMapper |
Other Changes
-
The LoginSuccessfulEvent that gets emitted when a user logs in will now be created with an instance of Authentication.
-
The
AuthenticationUserDetailsAdapterclass 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.
Micronaut 2 API:
SecurityRuleResult check(HttpRequest<?> request, @Nullable RouteMatch<?> routeMatch, @Nullable Map<String, Object> claims);
Micronaut 3 API:
Publisher<SecurityRuleResult> check(HttpRequest<?> request, @Nullable RouteMatch<?> routeMatch, @Nullable Authentication authentication);
LDAP Package Change
All classes in the io.micronaut.configuration.security.ldap have been moved to the io.micronaut.security.ldap package.
SecurityFilter
The security filter no longer extends deprecated OncePerRequestHttpServerFilter because it has been deprecated in Micronaut 3.
Cookie Secure Configuration
The following properties' default value has been removed in Micronaut Security 3.0.0:
-
micronaut.security.oauth2.openid.nonce.cookie.cookie-secure -
micronaut.security.oauth2.state.cookie.cookie-secure -
micronaut.security.token.jwt.cookie.cookie-secure -
micronaut.security.token.refresh.cookie.cookie-secure`
|
Note
|
If the cookie-secure setting is not set, cookies will be secure if the request is determined to be HTTPS.
|
Deprecations Removal
Most if not all deprecated classes constructors, and methods have been removed.
Other Changes
-
The constructor of DefaultJwtAuthenticationFactory has changed
-
The constructor of IdTokenLoginHandler has changed
-
The constructor of SessionLoginHandler has changed
-
The constructor of BasicAuthAuthenticationFetcher has changed
-
The RolesFinder method
findInClaimshas been deprecated and usages should be replaced withresolveRoles(@Nullable Map<String, Object> attributes).
|
Tip
|
Using the CLI
If you are creating your project using the Micronaut CLI, supply either |
To use the Micronaut’s security capabilities you must have the security dependency on your classpath:
annotationProcessor("io.micronaut.security:micronaut-security-annotations")implementation("io.micronaut.security:micronaut-security")|
Note
|
The micronaut-security-annotations 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.
When you add the micronaut-security dependency, it contributes a Micronaut HTTP Server Filter - the SecurityFilter.
For each request, the filter evaluates the request against every bean of type AuthenticationFetcher. That evaluation may result in an instance of type Authentication being resolved.
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.
You can write your own bean of type AuthenticationFetcher. However, Micronaut Security ships with several built-in authentication fetchers:
Bean |
Description |
It parses the credentials from an HTTP Request, which uses Basic Authentication. Then, it invokes every Authentication Provider using the parsed credentials. |
|
It attempts to retrieve a token from the HTTP Request, and then it tries to validate the token. |
|
It attempts to retrieve an Authentication from an HTTP session. |
|
Creates an Authentication if an X.509 client certificate is present and a name (CN) can be extracted. |
BasicAuthAuthenticationFetcher parses the credentials from an HTTP Request using Basic Authentication. Then, it invokes every Authentication Provider using the parsed credentials.
TokenAuthenticationFetcher attempts to retrieve a token from the HTTP Request via the TokenResolver API, and then it tries to validate the token via the TokenValidator API.
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.
|
Tip
|
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. |
You can write your own bean of type TokenReader. However, Micronaut Security ships with several built-in beans of type TokenReader.
BearerTokenReader attempts to read a RFC 6750 Bearer Token.
The following configuration properties are available to customize how the Bearer Token will be read:
CookieTokenReader attempts to read token from a request cookie.
The following configuration properties are available to customize how the token will be read from a cookie:
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.
| Result | Description |
|---|---|
Access to the resource should be granted and no further rules will be considered. |
|
Access to the resource should be rejected and no further rules will be considered. |
|
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. |
|
Important
|
If all security rules return UNKNOWN, the request will be rejected!
|
|
Important
|
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.
| Rule | Order | ACCEPT condition | REJECT condition | UNKNOWN confition |
|---|---|---|---|---|
-300 |
Never |
None of the IP patterns matched the hostaddress |
The address matches at least one of the patterns or no address could be resolved |
|
-200 |
At least one required role is granted to the authenticated user |
None of the required roles is granted to the authenticated user |
No secured annotation is specified on the requested method |
|
-100 |
At least one required role is granted to the authenticated user |
None of the required roles is granted to the authenticated user |
No path pattern is matched |
|
0 |
User is authenticated |
User is not authenticated |
Path is not a sensitive one |
|
Warning
|
Do not execute any blocking operations in the rule implementation without offloading those operations to another thread pool. |
|
Warning
|
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. |
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:
micronaut.security.ip-patterns[0]=127.0.0.1
micronaut.security.ip-patterns[1]=192.168.1.*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 example127.0.0.1,192.168.1.orfe80:*) is an IP wildcard. Dots and colons match literally. Ainside the pattern matches within one address segment (192.168..1matches192.168.2.1but not192.168.2.3.1), and a trailingmatches the rest of the address, so192.168.1.matches192.168.1.0to192.168.1.255and does not match192.168.10.5. Hexadecimal digits match regardless of case, soFE80:*andfe80:*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 contains192.168.1.together with other characters (for example192.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.
As illustrated below, you can use the @Secured annotation to control access to controllers or controller methods.
Alternatively, you can use Jakarta Annotations:
-
jakarta.annotation.security.PermitAll -
jakarta.annotation.security.RolesAllowed -
jakarta.annotation.security.DenyAll
|
Note
|
The use of JSR 250 annotations requires io.micronaut.security:micronaut-security-annotations to be in the annotation processor classpath (annotationProcessor, kapt, compileOnly) respectively for Java, Kotlin, Groovy.
|
|
Important
|
When the @Secured annotation has a set of roles, the SecuredAnnotationRule grants access to a user if they have any of the roles. |
|
Warning
|
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.
|
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 of type Authentication
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.
Moreover, you can configure endpoint authentication and authorization access with an Intercept URL Map:
micronaut.security.intercept-url-map[0].pattern=/images/*
micronaut.security.intercept-url-map[0].http-method=GET
micronaut.security.intercept-url-map[0].access[0]=isAnonymous()
micronaut.security.intercept-url-map[1].pattern=/books
micronaut.security.intercept-url-map[1].access[0]=isAuthenticated()
micronaut.security.intercept-url-map[2].pattern=/books/grails
micronaut.security.intercept-url-map[2].http-method=POST
micronaut.security.intercept-url-map[2].access[0]=ROLE_GRAILS
micronaut.security.intercept-url-map[2].access[1]=ROLE_GROOVY
micronaut.security.intercept-url-map[3].pattern=/books/grails
micronaut.security.intercept-url-map[3].http-method=PUT
micronaut.security.intercept-url-map[3].access[0]=ROLE_ADMIN-
pattern
/images/*enables access to authenticated and not authenticated users -
pattern
/booksenables access for everyone authenticated -
pattern
/books/grailsenables 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.
The router declares a HEAD route for every @Get method (unless headRoute = false) and answers it with the @Get method, and a static resource is served for any HTTP method when no route matches the request. Thus, a HEAD request answered by such an implicit HEAD route, and any request that no route matches, is subject to the mappings that specify the HTTP method GET, unless a mapping that specifies the HTTP method of the request (for example HEAD) matches the request URI. In the example below, a HEAD request to /v1/myResource/** does not require authentication either. A HEAD request answered by an explicitly declared @Head method is matched like any other request: by the mappings that specify HEAD, then by the mappings without a method. To apply different access rules to HEAD requests, define a mapping with httpMethod: HEAD. Do not rely on httpMethod: GET alone to protect static resources: omit the HTTP method from the mapping to protect a static resource whatever the 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.
micronaut.security.intercept-url-map[0].pattern=/v1/myResource/**
micronaut.security.intercept-url-map[0].httpMethod=GET
micronaut.security.intercept-url-map[0].access[0]=isAnonymous()
micronaut.security.intercept-url-map[1].pattern=/v1/myResource/**
micronaut.security.intercept-url-map[1].access[0]=isAuthenticated()-
accessing
/v1/myResource/**with a GET request does not require authentication -
accessing
/v1/myResource/**with a request that isn’t GET requires authentication
|
Note
|
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/*.
|
|
Note
|
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.
|
|
Important
|
When the @Secured annotation has a set of roles, the SecuredAnnotationRule grants access to a user if they have any of the roles. |
When you turn on security, Built-in endpoints are secured depending on their sensitive value.
endpoints.beans.enabled=true
endpoints.beans.sensitive=true
endpoints.info.enabled=true
endpoints.info.sensitive=false-
the
/beansendpoint is secured -
the
/infoendpoint 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:
imports
import io.micronaut.context.annotation.Replaces;
import io.micronaut.context.annotation.Requires;
import io.micronaut.core.annotation.NonNull;
import io.micronaut.http.HttpRequest;
import io.micronaut.inject.ExecutableMethod;
import io.micronaut.management.endpoint.EndpointSensitivityProcessor;
import io.micronaut.security.authentication.Authentication;
import io.micronaut.security.rules.SecurityRuleResult;
import io.micronaut.security.rules.SensitiveEndpointRule;
import io.micronaut.security.token.RolesFinder;
import jakarta.inject.Singleton;
import java.util.Collections;
import org.reactivestreams.Publisher;
import reactor.core.publisher.Mono;@Replaces(SensitiveEndpointRule.class)
@Singleton
public class SensitiveEndpointRuleReplacement extends SensitiveEndpointRule {
private final RolesFinder rolesFinder;
public SensitiveEndpointRuleReplacement(EndpointSensitivityProcessor endpointSensitivityProcessor,
RolesFinder rolesFinder) {
super(endpointSensitivityProcessor);
this.rolesFinder = rolesFinder;
}
@Override
@NonNull
protected Publisher<SecurityRuleResult> checkSensitiveAuthenticated(@NonNull HttpRequest<?> request,
@NonNull Authentication authentication,
@NonNull ExecutableMethod<?, ?> method) {
return Mono.just(rolesFinder.hasAnyRequiredRoles(Collections.singletonList("ROLE_SYSTEM"), authentication.getRoles())
? SecurityRuleResult.ALLOWED : SecurityRuleResult.REJECTED);
}
}Micronaut Security ships with several built-in Exception Handlers:
Exception |
Handler |
You may need to replace some of those beans to customize Micronaut Security exception handling to your needs.
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.
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.
You can configure the LoginController with:
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.
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.
You can configure the logout endpoint with:
|
Tip
|
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.
|
The LogoutHandler API defines how to respond to a logout attempt. For example, with the Logout Controller.
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
micronaut.security.authentication Value |
Required Module | Login Handler | Logout Handler |
|---|---|---|---|
|
|
||
|
|
||
|
|
||
|
|
These handlers allow you to set the following scenarios:
When you set micronaut.security.authentication=bearer, AccessRefreshTokenLoginHandler a bean of type LoginHandler is enabled.
When you set micronaut.security.authentication=session, SessionLoginHandler a bean of type LoginHandler and SessionLogoutHandler a bean of type LogoutHandler are enabled.
When you set micronaut.security.authentication=cookie, TokenCookieLoginHandler a bean of type LoginHandler and JwtCookieClearerLogoutHandler a bean of type LogoutHandler are enabled.
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.
The following global configuration options are available:
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.
micronaut.security.reject-not-found: false only affects requests that no security rule decides and that the server cannot serve. A request that matches no route but resolves to a static resource is still rejected with 401 or 403 unless a security rule, for example an intercept URL map entry, allows it.
The filter fails closed. The Netty runtime resolves static resources from the decoded request path and the servlet runtime from the raw, percent-encoded path, so a percent-encoded request is rejected when either form resolves to a static resource. In that case the filter may answer 401 or 403 for a request the active runtime would have answered with 404.
|
Warning
|
Setting micronaut.security.reject-not-found: false never makes a static resource public. To serve static resources anonymously, add an intercept URL map entry such as pattern: /assets/** with access: isAnonymous().
|
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.
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.
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:
|
Important
|
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.
To authenticate users you must provide implementations of ReactiveAuthenticationProvider or HttpRequestReactiveAuthenticationProvider.
The following code snippet illustrates a naive implementation:
@Singleton
class CustomAuthenticationProvider<B> implements HttpRequestReactiveAuthenticationProvider<B> {
@Override
@SingleResult
public Publisher<AuthenticationResponse> authenticate(HttpRequest<B> requestContext, AuthenticationRequest<String, String> authRequest) {
AuthenticationResponse rsp = authRequest.getIdentity().equals("user") && authRequest.getSecret().equals("password")
? AuthenticationResponse.success("user")
: AuthenticationResponse.failure(AuthenticationFailureReason.CREDENTIALS_DO_NOT_MATCH);
return Mono.create(emitter -> {
emitter.success(rsp);
});
}
}The ReactiveAuthenticationProvider interface is a reactive API. If you prefer an imperative style, you can instead implement the AuthenticationProvider or HttpRequestAuthenticationProvider interface:
@Singleton
class CustomAuthenticationProvider<B> implements HttpRequestAuthenticationProvider<B> {
@Override
public AuthenticationResponse authenticate(HttpRequest<B> requestContext, AuthenticationRequest<String, String> authRequest) {
return (authRequest.getIdentity().equals("user") && authRequest.getSecret().equals("password"))
? AuthenticationResponse.success("user")
: AuthenticationResponse.failure(AuthenticationFailureReason.CREDENTIALS_DO_NOT_MATCH);
}
}|
Important
|
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.
|
You can override getExecutorName() to return the name of any ExecutorService bean, for example one you configured under micronaut.executors. The provider is always invoked on the executor it names, never on the server event loop. If no ExecutorService bean with that name exists, the provider runs on the TaskExecutors.BLOCKING executor instead and a warning is logged.
Alternatively, annotate the authenticate method (or the provider class) with @Blocking. Such a provider is always invoked on the TaskExecutors.BLOCKING executor.
The built-in Login Controller uses every available authentication provider. Providers are evaluated one at a time in precedence order. To control that order, override getOrder(): both AuthenticationProvider and ReactiveAuthenticationProvider extend Ordered, so the @Order annotation is ignored and the default order is 0. The first provider in precedence order that returns a successful authentication response will have its value used as the basis for the JWT token or session state; lower precedence providers are not consulted once a provider accepts the credentials.
Basic authentication which is implemented as an AuthenticationFetcher will also trigger the available AuthenticationProviders.
Micronaut comes with authentication providers for LDAP (LdapAuthenticationProvider) and the OAuth 2.0 password grant authentication flow (OauthPasswordAuthenticationProvider and OpenIdPasswordAuthenticationProvider). For any custom authentication, an authentication provider must be created.
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:
curl "http://localhost:8080/info" \
-u 'user:password'After credentials are read from the HTTP Header, they are feed into an Authenticator which attempts to validate them.
The code snippet below illustrates how to send credentials using the basicAuth method from MutableHttpRequest method:
HttpRequest request = HttpRequest.GET("/home").basicAuth('sherlock', 'password')|
Tip
|
Read the Basic Authentication Micronaut Guide to learn more. |
Micronaut supports Session based authentication.
|
Tip
|
Using the CLI
If you are creating your project using the Micronaut CLI, supply either the |
To use the Micronaut’s session based authentication capabilities, you must have the security-session dependency on your classpath. For example:
annotationProcessor("io.micronaut.security:micronaut-security-annotations")implementation("io.micronaut.security:micronaut-security-session")|
Note
|
The micronaut-security-annotations dependency is only required to use JSR 250 annotations
|
The following sequence illustrates the authentication flow:
Check the Redirection configuration to customize session based authentication behaviour.
Example of Session-Based Authentication configuration
micronaut.security.authentication=session
micronaut.security.redirect.login-failure=/login/authFailedRead the following guides to learn more about session based authentication:
Session lifecycle
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.
Session-based authentication without redirection
When you set micronaut.security.authentication to session, you enable SessionLoginHandler and SessionLogoutHandler.
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.
The following configuration properties are available to customize token based authentication:
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.
|
Tip
|
Using the CLI
If you are creating your project using the Micronaut CLI, supply the |
To use the Micronaut’s JWT based authentication capabilities you must have the security-jwt dependency on your classpath. For example:
annotationProcessor("io.micronaut.security:micronaut-security-annotations")implementation("io.micronaut.security:micronaut-security-jwt")|
Note
|
The micronaut-security-annotations dependency is only required to use JSR 250 annotations
|
The following configuration properties are available to customize JWT based authentication behaviour:
What does a JWT look like?
Header
A base64-encoded JSON like:
{
"alg": "HS256",
"typ": "JWT"
}Claims
A base64-encoded JSON like:
{
"exp": 1422990129,
"sub": "jimi",
"roles": [
"ROLE_ADMIN",
"ROLE_USER"
],
"iat": 1422986529
}Signature
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.
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:
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:
String accessToken = rsp.body().accessToken
List<Book> books = gatewayClient.toBlocking().retrieve(HttpRequest.GET("/api/gateway")
.bearerAuth(accessToken), Argument.listOf(Book))GET /protectedResource HTTP/1.1
Host: micronaut.example`
Authorization: Bearer eyJhbGciOiJIUzI1NiJ9.eyJleHAiOjE0MjI5OTU5MjIsInN1YiI6ImppbWkiLCJyb2xlcyI6WyJST0xFX0FETUlOIiwiUk9MRV9VU0VSIl0sImlhdCI6MTQyMjk5MjMyMn0.rA7A2Gwt14LaYMpxNRtrCdO24RGrfHtZXY9fIjV8x8o|
Tip
|
Check out the Micronaut JWT authentication for a tutorial on Micronaut’s JWT support. |
You can send/read a JWT token from a Cookie too.
The following sequence illustrates the authentication flow:
Reading tokens from Cookies is disabled by default. Note that using JWT tokens from cookies requires JWT Authentication to be enabled.
|
Tip
|
Read the Micronaut JWT Authentication with Cookies to learn more. |
You can inject a bean of type The JsonWebTokenParser to parse a JWT token. The parser decrypts the token if encrypted.
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.
To verify the signature of JWT tokens, you need beans of type SignatureConfiguration or ReactiveSignatureConfiguration
The easiest way is to create a bean of type SignatureConfiguration is to have in your app a bean of type RSASignatureConfiguration,
ECSignatureConfiguration, or
SecretSignatureConfiguration which must be qualified with @Named since the configuration beans are used by factories (html,
ECSignatureConfiguration) or other beans (SecretSignature) which use
@EachBean to drive configuration.
The APIs JsonWebTokenSignatureValidator, and ReactiveJsonWebTokenSignatureValidator allows you to validate the signature of a JWT token.
ReactiveJsonWebTokenSignatureValidator validates the signature using both SignatureConfiguration or ReactiveSignatureConfiguration.
JsonWebTokenSignatureValidator validates the signature using beans of type SignatureConfiguration.
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:
micronaut.security.token.jwt.signatures.jwks.awscognito.url=https://cognito-idp.eu-west-1.amazonaws.com/eu-west-XXXX/.well-known/jwks.jsonThe 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.
|
Important
|
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:
micronaut.http.services.awscognito.url=https://cognito-idp.eu-west-1.amazonaws.com
micronaut.http.services.awscognito.proxy-type=http
micronaut.http.services.awscognito.proxy-address=proxy.company.net:8080
micronaut.security.token.jwt.signatures.jwks.awscognito.url=/eu-west-XXXX/.well-known/jwks.jsonNote 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.
|
Note
|
The signature configuration for the jwks_uri of an OpenID client is registered as soon as the client is configured, even if the provider’s discovery document could not be fetched when the application started. While the provider metadata is unavailable, tokens signed with the provider’s keys are rejected, and unsigned tokens are rejected as always when a signature configuration exists. The metadata is fetched again on demand, at most once per micronaut.security.token.jwt.signatures.jwks-client.failure-backoff (default 10 seconds) and never on the thread verifying a token, so signed tokens are accepted once the provider becomes reachable, without restarting the application.
|
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.
micronaut.security.token.jwt.signatures.jwks.awscognito.url=https://cognito-idp.eu-west-1.amazonaws.com/eu-west-XXXXX/.well-known/jwks.json
micronaut.security.token.jwt.signatures.jwks.awscognito.issuer=https://cognito-idp.eu-west-1.amazonaws.com/eu-west-XXXXXThe 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 once the provider metadata is resolved. 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.
micronaut.security.token.jwt.signatures.jwks.awscognito.url=https://cognito-idp.eu-west-1.amazonaws.com/eu-west-XXXXX/.well-known/jwks.json
micronaut.security.token.jwt.signatures.jwks.awscognito.key-type=RSAThe 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:
micronaut.security.token.jwt.signatures.jwks-client.http-client.enabled=false
micronaut.security.token.jwt.signatures.jwks.awscognito.url=/eu-west-XXXX/.well-known/jwks.jsonExposing your Application’s Json Web Key Set (JKWS)
If you want to expose your own JWK Set, read the Keys Controller section.
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.
|
Note
|
However, we recommend you enable caching via Micronaut Cache. This will be the only option in the future. |
Caching via Micronaut Cache
To cache JWKS with Micronaut Cache, you need to add an implementation of Micronaut Cache (E.g. Caffeine, Redis, Ehcache, Hazelcast, Coherence, Infinispan, EclipseStore, or MicroStream) and configure the expiration.
For example, you could add Caffeine implementation:
implementation("io.micronaut.cache:micronaut-cache-caffeine")The cache name is jwks. You can configure the cache expiration with:
micronaut.caches.jwks.expire-after-write=24hFailure back-off
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:
micronaut.security.token.jwt.signatures.jwks-client.failure-backoff=10s
micronaut.security.token.jwt.signatures.jwks-client.retrieval-timeout=30sfailure-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.
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.
micronaut.security.token.jwt.signatures.jwks-static.google.path=classpath:jwks/certs.jsonThe APIs JsonWebTokenValidator, and ReactiveJsonWebTokenValidator allows you to validate a JWT token.
The validation performs the following steps:
-
- Parses the Token (if encrypted, it decrypts).
-
- Validates the Signature
-
- Validates the Claims with beans of type GenericJwtClaimsValidator.
JsonWebTokenValidator will not use remote signature configuration. E.g. it will not validate the signature with remote JWKs.
Only, ReactiveJsonWebTokenValidator implements
TokenValidator.
Micronaut relies on Nimbus JOSE + JWT library to provide JWT token signature and encryption.
The following configuration options are available:
To generate a signed JWT you need to have in your app a bean of type
RSASignatureGeneratorConfiguration,
ECSignatureGeneratorConfiguration,
, or
SecretSignatureConfiguration which must be qualified with @Named generator since the configuration beans are used by factories (
RSASignatureGeneratorFactory,
ECSignatureGeneratorFactory) or other beans (SecretSignature) which use
@EachBean to drive configuration.
|
Important
|
Remember to qualify with @Named generator your signature configuration beans which you wish to use to sign your JSON web tokens.
|
You can setup a SecretSignatureConfiguration qualified with @Named generator easily via configuration:
micronaut.security.token.jwt.signatures.secret.generator.secret=pleaseChangeThisSecretForANewOne
micronaut.security.token.jwt.signatures.secret.generator.jws-algorithm=HS256-
Change the
secretproperty to your own secret and keep it safe. -
jws-algorithmspecifies the Json Web Token Signature name. In this example, HMAC using SHA-256 hash algorithm.
You can supply the secret with Base64 encoding.
micronaut.security.token.jwt.signatures.secret.generator.secret=cGxlYXNlQ2hhbmdlVGhpc1NlY3JldEZvckFOZXdPbmU=
micronaut.security.token.jwt.signatures.secret.generator.base64=true
micronaut.security.token.jwt.signatures.secret.generator.jws-algorithm=HS256-
This example of
secretis Base64 encoded -
Set
base64to signal that the secret is Base64 encoded
A programmatic setup of a RSA signature generation may look like
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.
Micronaut’s JWT validation supports multiple encryption configurations.
Beans of type RSAEncryptionConfiguration, ECEncryptionConfiguration, SecretEncryptionConfiguration participate as encryption configurations in the JWT validation.
Those beans need to be qualified with @Named since the configuration beans are used by factories (RSAEncryptionFactory,
ECEncryptionFactory) or other beans (SecretEncryptionFactory) which use
@EachBean to drive configuration.
Use generator as the @Named qualifier if you want to use encryption configuration in the tokens your app generates.
The API JsonWebTokenEncryption allows you to decrypt an encrypted token.
You can setup a SecretEncryptionConfiguration qualified with @Named generator easily via configuration:
micronaut.security.token.jwt.encryptions.secret.generator.secret=pleaseChangeThisSecretForANewOne
micronaut.security.token.jwt.encryptions.secret.generator.jwe-algorithm=dir
micronaut.security.token.jwt.encryptions.secret.generator.encryption-method=A256GCM-
Change the
secretproperty to your own secret and keep it safe. -
jwe-algorithmspecifies the JSON Web Encryption algorithm. In this example,dir(Direct Encryption with a Shared Symmetric Key). -
encryption-methodspecifies the encryption method. In this example,A256GCM(AES GCM using 256-bit key).
You can supply the secret with Base64 encoding.
micronaut.security.token.jwt.encryptions.secret.generator.secret=cGxlYXNlQ2hhbmdlVGhpc1NlY3JldEZvckFOZXdPbmU=
micronaut.security.token.jwt.encryptions.secret.generator.base64=true
micronaut.security.token.jwt.encryptions.secret.generator.jwe-algorithm=dir
micronaut.security.token.jwt.encryptions.secret.generator.encryption-method=A256GCM-
This example of
secretis Base64 encoded -
Set
base64to signal that the secret is Base64 encoded
Setup a SecretSignatureConfiguration through configuration properties
micronaut.security.token.jwt.signatures.secret.generator.secret=pleaseChangeThisSecretForANewOne
micronaut.security.token.jwt.signatures.secret.generator.jws-algorithm=HS256
pem.path=/home/user/rsa-2048bit-key-pair.pem-
Name the Signature configuration
generatorto make it participate in JWT token generation. -
pem.pathspecifies the location of PEM file
Generate a 2048-bit RSA private + public key pair:
openssl genrsa -out rsa-2048bit-key-pair.pem 2048@Named("generator") //
@Singleton
class RSAOAEPEncryptionConfiguration implements RSAEncryptionConfiguration {
private RSAPrivateKey rsaPrivateKey
private RSAPublicKey rsaPublicKey
JWEAlgorithm jweAlgorithm = JWEAlgorithm.RSA_OAEP_256
EncryptionMethod encryptionMethod = EncryptionMethod.A128GCM
RSAOAEPEncryptionConfiguration(@Value('${pem.path}') String pemPath) {
Optional<KeyPair> keyPair = KeyPairProvider.keyPair(pemPath)
if (keyPair.isPresent()) {
this.rsaPublicKey = (RSAPublicKey) keyPair.get().getPublic()
this.rsaPrivateKey = (RSAPrivateKey) keyPair.get().getPrivate()
}
}
@Override
RSAPublicKey getPublicKey() {
return rsaPublicKey
}
@Override
RSAPrivateKey getPrivateKey() {
return rsaPrivateKey
}
@Override
JWEAlgorithm getJweAlgorithm() {
return jweAlgorithm
}
@Override
EncryptionMethod getEncryptionMethod() {
return encryptionMethod
}
}-
Name Bean
generatorto designate this bean as participant in the JWT Token Generation.
To parse the PEM key, use a collaborator as described in OpenSSL key generation.
@Slf4j
class KeyPairProvider {
/**
*
* @param pemPath Full path to PEM file.
* @return returns KeyPair if successfully for PEM files.
*/
static Optional<KeyPair> keyPair(String pemPath) {
// Load BouncyCastle as JCA provider
Security.addProvider(new BouncyCastleProvider())
// Parse the EC key pair
PEMParser pemParser
try {
pemParser = new PEMParser(new InputStreamReader(Files.newInputStream(Paths.get(pemPath))))
PEMKeyPair pemKeyPair = (PEMKeyPair) pemParser.readObject()
// Convert to Java (JCA) format
JcaPEMKeyConverter converter = new JcaPEMKeyConverter()
KeyPair keyPair = converter.getKeyPair(pemKeyPair)
pemParser.close()
return Optional.of(keyPair)
} catch (FileNotFoundException e) {
log.warn("file not found: {}", pemPath)
} catch (PEMException e) {
log.warn("PEMException {}", e.getMessage())
} catch (IOException e) {
log.warn("IOException {}", e.getMessage())
}
return Optional.empty()
}
}If the built-in JWTClaimsSetGenerator, does not fulfil your needs you can provide your own replacement of ClaimsGenerator.
The claims of a JSON Web Token are validated using every bean of type GenericJwtClaimsValidator.
Micronaut Security includes some validators by default:
Bean |
Description |
Enabled |
JWT |
Enabled when the |
|
JWT is not expired. It uses the |
Enabled by default. You can disable it by setting |
|
JWT |
Enabled when the |
|
If the JWT |
Disabled by default. Enabled when the |
|
JWT |
Enabled by default. You can disable it by setting |
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.
When you use bearer authentication and the built-in LoginController,
the JWT tokens are returned to the client as part of an OAuth 2.0 RFC6749 access token response.
An example of such a response is:
HTTP/1.1 200 OK
Content-Type: application/json;charset=UTF-8
Cache-Control: no-store
Pragma: no-cache
{
"access_token":"eyJhbGciOiJIUzI1NiJ9...",
"token_type":"Bearer",
"expires_in":3600,
"refresh_token":"tGzv3JOkF0XG5Qx2TlKWIA...",
"username": "euler",
"roles": [
"ROLE_USER"
],
}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.
Read the following guides to learn more about JSON Web Token and JSON Web Keys:
Micronaut supports authentication with LDAP out of the box. To get started, add the security-ldap dependency to your application.
compile "io.micronaut.security:micronaut-security-ldap"|
Tip
|
Read the LDAP and Database authentication providers to see an example. |
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.
|
Important
|
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.
|
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.
Connecting with TLS
Without TLS, the manager credentials and every user’s password are sent to the directory as clear-text LDAP simple binds. Use an ldaps:// URL, or keep an ldap:// URL and turn on TLS through the JNDI environment property java.naming.security.protocol. JNDI then opens a TLS connection to the port in the URL, or to 636 when the URL has no port; it does not negotiate StartTLS on the clear-text port.
micronaut.security.ldap.default.context.server=ldap://ldap.example.com:636
micronaut.security.ldap.default.context.manager-dn=cn=manager,dc=example,dc=com
micronaut.security.ldap.default.context.manager-password=${LDAP_MANAGER_PASSWORD}
micronaut.security.ldap.default.context.properties.java.naming.security.protocol=sslThe entries under micronaut.security.ldap.*.context.properties are passed verbatim to ContextBuilder, and from there to javax.naming.directory.InitialDirContext. Keys keep the exact spelling you write (for example java.naming.ldap.derefAliases or com.sun.jndi.ldap.connect.timeout) and are never split into nested maps or renamed. Scalar values such as numbers and booleans are passed as strings, which is what the LDAP provider of the JDK expects. Only entries which take a string can be set this way. An entry which takes an object, such as com.sun.jndi.ldap.trace.ber (an OutputStream) or java.naming.ldap.control.connect (an array of controls), cannot be expressed in configuration; set in configuration, it makes every bind fail with a NamingException. Supply such entries through a custom ContextSettings instead.
|
Warning
|
Be careful with java.naming.referral. By default JNDI ignores referrals returned by the directory. With java.naming.referral: follow, JNDI opens a connection to every server a referral names and reuses the whole environment for it, including the manager DN and password and, during a login, the DN and password the user submitted. Those credentials are therefore sent to whichever server the directory points to. TLS enabled through java.naming.security.protocol: ssl also applies to the referral connections, but TLS enabled only through an ldaps:// server URL does not: a referral to an ldap:// URL is then followed in clear text. java.naming.referral: follow-scheme does not prevent this downgrade: the LDAP provider of the JDK then follows only referrals whose URL starts with ldap:, whatever the scheme of the server URL, so ldaps:// referrals are dropped while ldap:// referrals are still followed. Only follow referrals when every server the directory can refer to is trusted, and enable TLS through java.naming.security.protocol, which is the only setting that keeps every referral connection encrypted.
|
|
Tip
|
To trust the certificate presented by the directory, 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>"Connection Pooling
The manager context, which Micronaut binds with manager-dn and manager-password to search for the user, does not use the JNDI LDAP connection pool unless micronaut.security.ldap..context.pooled is true. Contexts bound with the credentials of the user who is logging in are never pooled. pooled is the only supported switch: the com.sun.jndi.ldap.connect.pool key is ignored if set through micronaut.security.ldap..context.properties.
The JNDI LDAP connection pool (com.sun.jndi.ldap.connect.pool) is shared by the whole JVM and the JDK configures it with system properties only. Left unbounded, a single burst of anonymous requests with bogus credentials grows the pool to the width of the burst and the connections stay open afterwards. If that exhausts the connections the directory is willing to serve, user binds fail and valid users cannot log in until the application restarts. For that reason, when pooling is enabled, Micronaut bounds the pool with the values under micronaut.security.ldap.*.context.pool:
micronaut.security.ldap.default.context.server=ldap://localhost:389
micronaut.security.ldap.default.context.manager-dn=cn=admin,dc=example,dc=com
micronaut.security.ldap.default.context.manager-password=password
micronaut.security.ldap.default.context.pooled=true
micronaut.security.ldap.default.context.pool.max-size=20
micronaut.security.ldap.default.context.pool.pref-size=5
micronaut.security.ldap.default.context.pool.idle-timeout=5m
micronaut.security.ldap.default.context.pool.connect-timeout=10sWhen an LDAP configuration with pooled: true is created, which happens before the first pooled connection is opened, Micronaut applies these values as the com.sun.jndi.ldap.connect.pool.maxsize, com.sun.jndi.ldap.connect.pool.prefsize and com.sun.jndi.ldap.connect.pool.timeout system properties. A value set under pool always wins. For a value not set under pool, a system property that is already set, for example with -Dcom.sun.jndi.ldap.connect.pool.maxsize=50 on the command line, is kept; otherwise the default applies: a maximum of 20 connections, a preferred size of 5 and an idle timeout of 5 minutes. Setting max-size: 0 or idle-timeout: 0 restores the unbounded JDK behaviour; Micronaut logs a warning in that case.
Once the pool holds max-size connections, a login waits for a pooled connection to be released instead of opening a new one. The manager context is closed as soon as the user has been searched, so the wait is normally short, but the JDK would wait indefinitely if a hung directory operation held every pooled connection. connect-timeout (default 10 seconds) bounds that wait, and the time allowed to open a new pooled connection: it is applied as the com.sun.jndi.ldap.connect.timeout JNDI environment property of the pooled manager context, unless micronaut.security.ldap.*.context.properties already sets that key. A login that waits longer fails with UNKNOWN instead of hanging. connect-timeout must be positive, because the JDK waits forever for 0; a negative max-size, pref-size or idle-timeout is rejected as well. Contexts bound with user credentials are not pooled and keep the JDK defaults.
|
Note
|
The JDK pools only plain (unencrypted) connections unless the com.sun.jndi.ldap.connect.pool.protocol system property lists ssl as well, for example -Dcom.sun.jndi.ldap.connect.pool.protocol="plain ssl", and it never pools connections opened through a custom java.naming.ldap.factory.socket whose class does not implement java.util.Comparator. With an ldaps:// server URL, or java.naming.security.protocol: ssl in micronaut.security.ldap.*.context.properties, pooled: true therefore has no effect until that system property is set: the manager context is opened and closed per login as if pooling were off.
|
|
Warning
|
The JDK reads these system properties once, when the first pooled JNDI LDAP connection of the JVM is opened, and the pool is shared by every LDAP configuration. If another library opens a pooled connection before Micronaut Security creates its first LDAP configuration, or if several LDAP configurations enable pooling with different bounds, the values the JDK read first stay in effect. Set the system properties on the command line in that case. |
|
Note
|
Neither disabling pooling nor bounding the pool limits the number of concurrent login attempts that reach the directory. Limiting the rate of login attempts is a separate concern, for example with a rate limiter in front of the login endpoint. |
See the JNDI LDAP provider documentation for the full list of pool system properties.
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 Authentication attributes to store additional data. Replace DefaultContextAuthenticationMapper and provide your own implementation.
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.
Search Logic
To customize how LDAP searches are done, replace the default implementation with your own. See LdapSearchService.
@Singleton
@Replaces(DefaultLdapSearchService.class)
public class MyLdapSearchService implements LdapSearchService {
}Context Building
To customize how the LDAP context is built, replace the default implementation with your own. See ContextBuilder.
@Singleton
@Replaces(DefaultContextBuilder.class)
public class MyContextBuilder implements ContextBuilder {
}|
Tip
|
Read LDAP and database authentication providers to learn more about LDAP Authentication: |
Micronaut Security supports using X.509 client certificates with HTTPS to enable mutual authentication.
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:
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:
micronaut.application.name=your_application_name
micronaut.security.x509.enabled=true
micronaut.ssl.enabled=true
micronaut.server.ssl.client-authentication=want
micronaut.server.ssl.key-store.path=classpath:ssl/keystore.p12
micronaut.server.ssl.key-store.password=your_keystore_password
micronaut.server.ssl.key-store.type=PKCS12
micronaut.server.ssl.trust-store.path=classpath:ssl/truststore.jks
micronaut.server.ssl.trust-store.password=your_truststore_password
micronaut.server.ssl.trust-store.type=JKS|
Tip
|
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. |
All authorization 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:
imports
import io.micronaut.context.annotation.Requires;
import io.micronaut.core.util.StringUtils;
import io.micronaut.http.HttpRequest;
import io.micronaut.security.authentication.Authentication;
import io.micronaut.security.filters.AuthenticationFetcher;
import jakarta.inject.Singleton;
import java.util.Collection;
import java.util.Collections;
import org.reactivestreams.Publisher;
import reactor.core.publisher.Mono;@Singleton
public class SiteminderAuthenticationFetcher implements AuthenticationFetcher<HttpRequest<?>> {
public static final String SITEMINDER_USER_HEADER = "SM_USER";
@Override
public Publisher<Authentication> fetchAuthentication(HttpRequest<?> request) {
return Mono.<Authentication>create(emitter -> {
String siteminderUser = request.getHeaders().get(SITEMINDER_USER_HEADER);
if (StringUtils.isEmpty(siteminderUser)) {
emitter.success();
return;
}
Collection<String> roles = Collections.singleton("ROLE_USER");
emitter.success(Authentication.build(siteminderUser, roles));
});
}
}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.
When a request is rejected, the security filter emits an AuthorizationException. The default implementation (DefaultAuthorizationExceptionHandler) redirects based on the redirect configuration only if the request accepts text/html:
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.
For example:
imports
import io.micronaut.context.annotation.Replaces;
import io.micronaut.context.annotation.Requires;
import io.micronaut.core.annotation.Nullable;
import io.micronaut.http.HttpRequest;
import io.micronaut.http.MutableHttpResponse;
import io.micronaut.http.server.exceptions.response.ErrorResponseProcessor;
import io.micronaut.security.authentication.AuthorizationException;
import io.micronaut.security.authentication.DefaultAuthorizationExceptionHandler;
import io.micronaut.security.config.RedirectConfiguration;
import io.micronaut.security.config.RedirectService;
import io.micronaut.security.errors.PriorToLoginPersistence;
import jakarta.inject.Singleton;@Singleton
@Replaces(DefaultAuthorizationExceptionHandler.class)
public class MyRejectionHandler extends DefaultAuthorizationExceptionHandler {
public MyRejectionHandler(ErrorResponseProcessor<?> errorResponseProcessor,
RedirectConfiguration redirectConfiguration,
RedirectService redirectService,
@Nullable PriorToLoginPersistence priorToLoginPersistence) {
super(errorResponseProcessor, redirectConfiguration, redirectService, priorToLoginPersistence);
}
@Override
public MutableHttpResponse<?> handle(HttpRequest request, AuthorizationException exception) {
//Let the DefaultAuthorizationExceptionHandler create the initial response
//then add a header
return super.handle(request, exception).header("X-Reason", "Example Header");
}
}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 <<basicAuth, 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.
If you have <<protectedResourceMetadata, Resource Metadata> enabled, an entry as defined in the WWW-Authenticate Response section of RFC9728 is added
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
Add the Micronaut Security CSRF dependency to protect against CSRF:
implementation("io.micronaut.security:micronaut-security-csrf")The core of Micronaut Security CSRF implementation is io.micronaut.security.csrf.filter.CsrfFilter.
A Server Filter which attempts to resolve a CSRF Token with
every bean of type CsrfTokenResolver and validates it with beans of type CsrfTokenValidator.
The following configuration options are available for the CSRF Filter:
|
Important
|
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
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=o24b65486f506e2cd4403caf0d640024When you use Micronaut Security Authentication cookie, or
idtoken a CSRF Token is saved in a Cookie upon login.
You can configure different cookie attributes. For example, by default the cookie name uses a __Host- Cookie prefix, can extend security protections against CSRF Attacks.
|
Important
|
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.
micronaut.security.csrf.signature-key=pleaseChangeThisSecretForANewOnekoqQ-EstJQLr_T-1qS0gZH75aKtMN3Yj0iPS4hcgUuTwjAzZr1Z9CAowThe HMAC of a signed CSRF token binds the token to the session identifier resolved via SessionIdResolver (for example, the HTTP session id or the jti claim of a JWT) and to the name of the authenticated user. A token issued to one user, for example upon login, is therefore not valid for a request authenticated as another user, even if an attacker manages to write the token into the victim’s CSRF cookie.
If you generate a CSRF token yourself with CsrfTokenGenerator, use generateCsrfToken(request, authentication) when the request does not carry the authentication yet, for example while handling a login. generateCsrfToken(request) binds the token to the user authenticated in the request, if any.
The bound name is Authentication#getName(), the canonical name of the principal. Attributes of the authentication are not used, because distinct principals may share attribute values: users validated via the UserInfo endpoint of several OpenID providers are named <provider>:<sub> and may share the raw sub or the email attribute, and they do not share CSRF tokens. The login handlers which issue a JWT (TokenCookieLoginHandler and IdTokenLoginHandler) supply the LoginCookieProvider beans with the authentication named as token based authentication names the user from the issued token: the value of the micronaut.security.token.name-key claim (default sub, which is the principal name), falling back to the principal name. The value computed at login therefore matches the one computed on later requests. Custom authentication mappers (for example a custom OpenIdAuthenticationMapper#getUsername) keep working as long as the issued token carries the name. A request authenticated without a name is treated like an anonymous one.
The following configuration options are available for CSRF:
Micronaut Security CSRF resolves a CSRF Token with beans of type CsrfTokenResolver
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=intendedYou can disable it by setting micronaut.security.csrf.token-resolvers.http-header.enabled=false
The HTTP Header name used by HttpHeaderCsrfTokenResolver can 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.
Micronaut Security CSRF ships a io.micronaut.security.csrf.resolver.FieldCsrfTokenResolver an implementation of CsrfTokenResolver 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=o24b65486f506e2cd4403caf0d640024You 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 main APIs for CSRF protection are:
Imagine you have a Gateway microservice which consumes three other microservices:
If the incoming request localhost:8080/api/books contains a valid JWT token, you may want to propagate
that token to other requests in your network.
You can configure token propagation to achieve that.
micronaut.application.name=gateway
micronaut.security.token.jwt.signatures.secret.generator.secret=pleaseChangeThisSecretForANewOne
micronaut.security.token.jwt.signatures.secret.generator.jws-algorithm=HS256
micronaut.security.token.propagation.header.enabled=true
micronaut.security.token.propagation.header.headerName=Authorization
micronaut.security.token.propagation.header.prefix=Bearer
micronaut.security.token.propagation.enabled=true
micronaut.security.token.propagation.service-id-regex=http://localhost:(8083|8081|8082)The previous configuration, configures a HttpHeaderTokenPropagator and a propagation filter, TokenPropagationHttpClientFilter, which will propagate the security token seamlessly.
If you use Service Discovery features, you can use the service id in your service id regular expression:
micronaut.security.token.propagation.service-id-regex="catalogue|recommendations|inventory"Several configuration options are available:
For propagation via an HTTP Header, you can configure:
|
Tip
|
Read the Token Propagation tutorial to learn more. |
|
Important
|
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:
To enable it, you must provide a secret:
micronaut.security.token.jwt.generator.refresh-token.secret=pleaseChangeThisSecretForANewOneAfter 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.
Refreshing the Token
Micronaut security comes with a controller to allow for the refresh of access tokens. The context loads the OauthController if your context contains beans of type: AccessRefreshTokenGenerator, RefreshTokenPersistence, RefreshTokenValidator
Moreover, the controller can be configured with:
The controller exposes an endpoint as defined by section 6 of the OAuth 2.0 spec - Refreshing an Access Token.
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:
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.
|
Tip
|
Refresh tokens must be securely stored in your client application. See section 10.4 of the OAuth 2.0 spec for more information. |
|
Note
|
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.
To enable the KeysController you have to provide at least a bean of type: JwkProvider.
Moreover, you can configure it with:
The Introspection endpoint exposes an endpoint to inquire the current state of a token.
POST /token_info
Accept: application/json
Content-Type: application/x-www-form-urlencoded
Authorization: Basic dXNlcjpwYXNzd29yZA==
token=eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4gRG9lIiwiYWRtaW4iOnRydWUsImp0aSI6IjM1NjhjM2EzLWFlMmMtNDFiMy1hYzU5LTU0ZTkxODVkM2ViOCIsImlhdCI6MTYwMTA0OTU5OCwiZXhwIjoxNjAxMDUzMTk4fQ.Sc5Xh7jI6e_F3FAUo3n3AUCHNSxWH8t-WlM6JxeHZGI&token_type_hint=access_tokenMoreover, you can access a secured GET endpoint which responds the introspection response for the authenticated user:
GET /token_info
Accept: application/json
Authorization: Bearer eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4gRG9lIiwiYWRtaW4iOnRydWUsImp0aSI6IjM1NjhjM2EzLWFlMmMtNDFiMy1hYzU5LTU0ZTkxODVkM2ViOCIsImlhdCI6MTYwMTA0OTU5OCwiZXhwIjoxNjAxMDUzMTk4fQ.Sc5Xh7jI6e_F3FAUo3n3AUCHNSxWH8t-WlM6JxeHZGIresponds:
{
"active": false
"username": "1234567890",
"sub": "1234567890",
"name": "John Doe",
"admin": true,
"jti": "3568c3a3-ae2c-41b3-ac59-54e9185d3eb8",
"iat": 1601049598,
"exp": 1601053198
}Often you may want to retrieve the authenticated user.
You can bind java.security.Principal as a method’s parameter in a controller.
imports
import io.micronaut.core.annotation.Nullable
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 java.security.Principal@Controller("/user")
public class UserController {
@Secured("isAnonymous()")
@Get("/myinfo")
public Map myinfo(@Nullable Principal principal) {
if (principal == null) {
return Collections.singletonMap("isLoggedIn", false);
}
return CollectionUtils.mapOf("isLoggedIn", true, "username", principal.getName());
}
}If you need a greater level of detail, you can bind Authentication as a method’s parameter in a controller.
imports
import io.micronaut.core.annotation.Nullable
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 io.micronaut.security.authentication.Authentication@Controller("/user")
class UserController {
@Secured("isAnonymous()")
@Get("/myinfo")
Map myinfo(@Nullable Authentication authentication) {
if (authentication == null) {
return Collections.singletonMap("isLoggedIn", false);
}
return CollectionUtils.mapOf("isLoggedIn", true,
"username", authentication.getName(),
"roles", authentication.getRoles()
);
}
}When using WebSocket Servers, you can bind the authenticated user in a method annotated with @OnMessage or @OnOpen.
@OnOpen
void onOpen(WebSocketSession session, Authentication authentication) {
broadcaster.broadcastSync("joined! " + authentication.getName(), isValid(session));
}You can create a custom argument binder to bind the authenticated user to a custom class tailored to your application needs.
If, in your application, the authenticated user has an email address, you can create a class such as:
imports
package io.micronaut.security.docs.customauthentication;
import io.micronaut.security.authentication.Authentication;
import io.micronaut.serde.annotation.Serdeable;@Serdeable
public record AuthenticationWithEmail(String username,
String email) {
public static AuthenticationWithEmail of(Authentication authentication) {
Object obj = authentication.getAttributes().get("email");
String email = obj == null ? null : obj.toString();
return new AuthenticationWithEmail(authentication.getName(), email);
}
}and then a TypedRequestArgumentBinder:
imports
package io.micronaut.security.docs.customauthentication;
import io.micronaut.context.annotation.Requires;
import io.micronaut.core.convert.ArgumentConversionContext;
import io.micronaut.core.type.Argument;
import io.micronaut.http.HttpRequest;
import io.micronaut.http.bind.binders.TypedRequestArgumentBinder;
import io.micronaut.security.authentication.Authentication;
import io.micronaut.security.filters.SecurityFilter;
import jakarta.inject.Singleton;
import java.util.Optional;@Requires(property = "spec.name", value = "CustomAuthenticationTest")
@Singleton
public class AuthenticationWithEmailArgumentBinder implements TypedRequestArgumentBinder<AuthenticationWithEmail> {
private final Argument<AuthenticationWithEmail> argumentType;
public AuthenticationWithEmailArgumentBinder() {
argumentType = Argument.of(AuthenticationWithEmail.class);
}
@Override
public Argument<AuthenticationWithEmail> argumentType() {
return argumentType;
}
@Override
public BindingResult<AuthenticationWithEmail> bind(ArgumentConversionContext<AuthenticationWithEmail> context, HttpRequest<?> source) {
if (!source.getAttributes().contains(SecurityFilter.KEY)) {
return BindingResult.UNSATISFIED;
}
final Optional<Authentication> existing = source.getUserPrincipal(Authentication.class);
return existing.isPresent() ? (() -> existing.map(AuthenticationWithEmail::of)) : BindingResult.EMPTY;
}
}Then you can bind it in a controller method parameter:
@Secured(SecurityRule.IS_AUTHENTICATED)
@Produces(MediaType.TEXT_PLAIN)
@Get("/custom-authentication")
String index(AuthenticationWithEmail authentication) {
return authentication.email();
}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.
Under the hood, it uses the SecurityContextHolder and SecurityContext APIs.
The default supplier for SecurityContext uses server request attributes. You can replace it by providing an implementation of SecurityContextSupplier via a Java SPI.
SecurityService with Project Reactor
If you use Micronaut Reactor and access SecurityService within a reactive chain, add the following dependency to handle the Reactor Context Propagation.
implementation("io.micrometer:context-propagation")Micronaut Security provides integration with Micronaut Data for automatically capturing the identity of the user that created or updated a particular entity.
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:
imports
import io.micronaut.core.annotation.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
public record Book(
@Id
@GeneratedValue
@Nullable
Long id,
@NotBlank
String title,
@NotBlank
String author,
@Nullable
@CreatedBy //2
String creator,
@Nullable
@UpdatedBy //3
String editor) {
}-
The class is mapped and persisted by Micronaut Data
-
The creator field will be populated on
save() -
The editor field will be populated on both
save()andupdate()
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:
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.
Micronaut security classes generate several ApplicationEvents which you can subscribe to.
Event Name |
Description |
Triggered when an unsuccessful login takes place. |
|
Triggered when a successful login takes place. |
|
Triggered when the user logs out. |
|
Triggered when a token is validated. |
|
Triggered when a JWT access token is generated. |
|
Triggered when a JWT refresh token is generated. |
To learn how to listen for events, see the Context Events section of the documentation.
|
Note
|
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.
|
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 example, to configure Google as a provider:
micronaut.security.oauth2.clients.google.client-secret=<<your client secret>>
micronaut.security.oauth2.clients.google.client-id=<<your client id>>
micronaut.security.oauth2.clients.google.openid.issuer=https://accounts.google.comFor 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.
implementation("io.micronaut.security:micronaut-security-oauth2")To use the BUILD-SNAPSHOT version of this library, check the documentation to use snapshots.
Code can be found at the micronaut-security repository.
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.
|
Note
|
To use OpenID client flows, the security-jwt dependency must be in your build because OpenID relies on JWT tokens.
|
implementation("io.micronaut.security:micronaut-security-jwt")|
Important
|
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.
|
|
Important
|
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.
|
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.
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.
|
Tip
|
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.
Here is an example:
imports
import io.micronaut.context.annotation.Requires;
import io.micronaut.core.async.publisher.Publishers;
import io.micronaut.http.HttpRequest;
import io.micronaut.http.HttpResponse;
import io.micronaut.http.HttpStatus;
import io.micronaut.http.MutableHttpResponse;
import io.micronaut.http.annotation.Filter;
import io.micronaut.http.cookie.Cookie;
import io.micronaut.http.filter.HttpServerFilter;
import io.micronaut.http.filter.ServerFilterChain;
import org.reactivestreams.Publisher;@Filter(value = {"/oauth/login", "/oauth/login/*"})
public class OAuthCsrfFilter implements HttpServerFilter {
@Override
public Publisher<MutableHttpResponse<?>> doFilter(HttpRequest<?> request, ServerFilterChain chain) {
String requestParameter = request.getParameters().get("_csrf");
String cookieValue = request.getCookies().findCookie("_csrf").map(Cookie::getValue).orElse(null);
if (cookieValue == null || !cookieValue.equals(requestParameter)) {
return Publishers.just(HttpResponse.status(HttpStatus.FORBIDDEN));
}
return chain.proceed(request);
}
}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.
The minimum requirements to allow authorization with an OAuth 2.0 provider are:
-
Configuration of the authorization endpoint
-
Configuration of the token endpoint
-
Configuration of the client id and secret
-
An implementation of OauthAuthenticationMapper
Configuration is quite simple. For example to configure authorization with Github:
micronaut.security.oauth2.clients.github.client-id=<<my client id>>
micronaut.security.oauth2.clients.github.client-secret=<<my client secret>>
micronaut.security.oauth2.clients.github.scopes[0]=user:email
micronaut.security.oauth2.clients.github.scopes[1]=read:user
micronaut.security.oauth2.clients.github.authorization.url=https://github.com/login/oauth/authorize
micronaut.security.oauth2.clients.github.token.url=https://github.com/login/oauth/access_token
micronaut.security.oauth2.clients.github.token.auth-method=client-secret-post-
Configure a client. The name
githubis arbitrary -
Provide values for
client-idandclient-secret -
Optionally specify desired
scopes -
Provide an
authorizationendpoint URL -
Additionally, the
tokenendpoint URL and authentication method -
auth-methodis 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).
|
Tip
|
To disable a specific client for any given environment, set enabled: false within the client configuration.
|
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:
imports
import com.fasterxml.jackson.databind.PropertyNamingStrategies;
import com.fasterxml.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 ...
}Create an HTTP client to make the request:
imports
import io.micronaut.http.annotation.Get;
import io.micronaut.http.annotation.Header;
import io.micronaut.http.client.annotation.Client;
import org.reactivestreams.Publisher;@Header(name = "User-Agent", value = "Micronaut")
@Client("https://api.github.com")
public interface GithubApiClient {
@Get("/user")
Publisher<GithubUser> getUser(@Header("Authorization") String authorization);
}Create the user details mapper that pulls it together:
Adding support for authorization code flow with an OpenID provider is extremely easy with Micronaut.
Here is a high level diagram of how the authorization code grant flow works with an OpenID provider.
The requirements to allow authorization with an OpenID provider are:
-
Configuration of the client id and secret
-
Configuration of the issuer
micronaut.security.oauth2.clients.okta.client-id=<<my client id>>
micronaut.security.oauth2.clients.okta.client-secret=<<my client secret>>
micronaut.security.oauth2.clients.okta.openid.issuer=<<my openid issuer>>-
Configure a client. The name
oktais arbitrary -
Provide values for
client-idandclient-secret -
Specify an OpenID provider issuer url
The issuer URL will be used to discover the endpoints exposed by the provider.
|
Tip
|
To disable a specific client for any given environment, set enabled: false within the client configuration.
|
See the following tables for the configuration options:
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.
|
Important
|
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 thesubclaim, for exampleokta: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 thesubattribute. -
With a single client the username is the bare
subclaim.
|
Tip
|
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.
|
|
Note
|
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:
|
Warning
|
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.
|
Important
|
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 global default mapper, register a bean that replaces DefaultOpenIdAuthenticationMapper. The global mapper is the OpenIdAuthenticationMapper bean without a qualifier (or the one marked @Primary), and it is used by every OpenID client without a provider-specific mapper, for both the authorization code flow and the password grant.
imports
import io.micronaut.context.annotation.Replaces;
import io.micronaut.core.annotation.NonNull;
import io.micronaut.core.annotation.Nullable;
import io.micronaut.security.authentication.AuthenticationResponse;
import io.micronaut.security.oauth2.endpoint.authorization.state.State;
import io.micronaut.security.oauth2.endpoint.token.response.DefaultOpenIdAuthenticationMapper;
import io.micronaut.security.oauth2.endpoint.token.response.OpenIdAuthenticationMapper;
import io.micronaut.security.oauth2.endpoint.token.response.OpenIdClaims;
import io.micronaut.security.oauth2.endpoint.token.response.OpenIdTokenResponse;
import jakarta.inject.Singleton;
import org.reactivestreams.Publisher;
import reactor.core.publisher.Flux;@Singleton
@Replaces(DefaultOpenIdAuthenticationMapper.class)
public class GlobalOpenIdAuthenticationMapper implements OpenIdAuthenticationMapper {
@Override
@NonNull
public Publisher<AuthenticationResponse> createAuthenticationResponse(String providerName, OpenIdTokenResponse tokenResponse, OpenIdClaims openIdClaims, @Nullable State state) {
return Flux.just(AuthenticationResponse.success("name"));
}
}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.
|
Note
|
A provider-specific mapper is only used for the client of that name, never as the global mapper of the other clients. If the only mapper of the application is registered with a @Named qualifier, for example because it replaces the default mapper, the clients without a mapper of their own cannot authenticate anyone: in the authorization code flow the OpenIdClient is not created (unless a custom OpenIdAuthorizationResponseHandler is registered), and in the password grant no authentication provider is created for the client. Register an unqualified (or @Primary) global mapper for them, or a named mapper for every client.
|
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).
You can configure which implementation to use:
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:
To use (SessionNoncePersistence`). which stores the nonce in a HTTP session:
-
Add a dependency to
micronaut-sessionimplementation("io.micronaut.security:micronaut-session") -
Set the nonce persistence to
sessionmicronaut.security.oauth2.nonce.persistence=sessionNoteYou can provide your own implementation of NoncePersistence
|
Warning
|
If nonce validation fails, the user will not be authenticated. |
Customization
There are several interfaces that implementations can be provided for to override how the nonce parameter is handled.
Interface |
Responsibility |
Default Implementation |
Builds a |
||
Validates an OpenID token response (including the nonce). |
||
Validates the nonce claim in the token response |
||
Stores the nonce to be retrieved later to allow validation |
To override the behavior of any of those beans, provide an implementation and replace the default one.
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.
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.
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.
By default all implementations of GenericJwtClaimsValidator and OpenIdClaimsValidator are used to validate the token.
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:
micronaut.security.oauth2.clients.keycloak.openid.issuer=http://keycloak:8080/realms/app
micronaut.security.oauth2.clients.keycloak.openid.issuer-identifier=https://sso.example.com/realms/appIf 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.
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:
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 enable state persistence with an http session:
-
Add a dependency to
micronaut-sessionimplementation("io.micronaut.security:micronaut-session") -
Set the state persistence to
sessionmicronaut.security.oauth2.state.persistence=sessionIf state validation fails, the user will not be authenticated.
Customization
There are several interfaces that implementations can be provided for to override how the state parameter is handled.
Interface |
Responsibility |
Default Implementation |
Builds a State |
||
Serializes and de-serializes the state object for use in the authorization request |
||
Validates the state received in the authorization response |
||
Stores the state to be retrieved later to allow validation |
To override the behavior of any of those beans, provide an implementation and replace the default one.
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.
If the built-in implementation does not fulfill your needs, you can provide a replacement of bean CodeVerifierGenerator or PkceGenerator.
You can obtain a bean of type ClientCredentialsClient to request an access token via a Client Credentials Grant for your OAuth 2.0 Clients.
For example:
micronaut.security.oauth2.clients.companyauthserver.client-id=XXX
micronaut.security.oauth2.clients.companyauthserver.client-secret=YYY
micronaut.security.oauth2.clients.companyauthserver.token.url=https://foo.bar/token
micronaut.security.oauth2.clients.companyauthserver.token.auth-method=client_secret_basic
micronaut.security.oauth2.clients.google.client-id=ZZZZ
micronaut.security.oauth2.clients.google.client-secret=PPPP
micronaut.security.oauth2.clients.google.openid.issuer=https://accounts.google.comYou can obtain a bean of type ClientCredentialsClient for any of the OAuth 2.0 clients using a Name Qualifier.
public MyClass(@Named("google") ClientCredentialsClient googleClientCredentialclient) {
...
}or
...
beanContext.getBean(ClientCredentialsClient.class, Qualifiers.byName("companyauthserver"))ClientCredentialsClient caches the token response. If the cached access token is expired, they renew it automatically.
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.
micronaut.security.oauth2.clients.companyauthserver.client-id=XXX
micronaut.security.oauth2.clients.companyauthserver.client-secret=YYY
micronaut.security.oauth2.clients.companyauthserver.client-credentials.service-id-regex=inventory
micronaut.security.oauth2.clients.companyauthserver.token.url=https://foo.bar/token
micronaut.security.oauth2.clients.companyauthserver.token.auth-method=client_secret_basicThe following configuration options are available per OAuth 2.0 client:
Read the following guides to learn more abut Client Credentials Flow:
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:
micronaut.security.oauth2.clients.github.grant-type=password|
Note
|
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.
For an OpenID provider, the ID token returned by the token endpoint is mapped to an Authentication with the same OpenIdAuthenticationMapper the authorization code flow uses: a mapper registered with a named qualifier matching the client name takes precedence, otherwise the global mapper, the one without a qualifier, is used. A mapper registered for another client is never used; if neither exists, the password grant of the client is disabled. See OpenID Authentication Mapper. A user the mapper rejects cannot log in through the password grant, and the name, roles and attributes the mapper assigns are those of the resulting authentication.
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:
To enable the usage of the /logout endpoint, see the section on the Logout Endpoint.
|
Important
|
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.
|
Warning
|
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.
When several OpenID clients are configured, the /oauth/logout route has to decide which provider to redirect the user to. The ProviderResolver (by default DefaultProviderResolver) uses the provider name stored in the authentication attributes when the user logged in through the authorization code flow. With micronaut.security.authentication=idtoken the attributes of the authentication are the claims of the ID token which authenticated the request; IdTokenClaimsValidator rejects tokens carrying an oauth2Provider or openIdToken claim, since those names are reserved for attributes set by the application, so the provider is resolved from the token claims. In that case, it compares the iss claim with the expected issuer of each enabled OpenID client (micronaut.security.oauth2.clients.*.openid.issuer-identifier if set, otherwise openid.issuer), tolerating only the case of the scheme and a trailing slash. If the iss claim matches more than one client (two Oracle Cloud identity domains, whose ID tokens share the issuer https://identity.oraclecloud.com/ configured as their issuer-identifier, is a common example), the aud claim, and for multi-audience tokens the azp claim, must identify exactly one client by its client-id. When no single client can be determined no redirect is issued, so the ID token is never sent as id_token_hint to another provider’s end session endpoint.
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.
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.
See the following configuration table:
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.
See the following configuration table:
Micronaut Security OAuth2 can register a bean of type TokenValidator for each OpenID provider.
It provides token validation using the remote authorization server’s
UserInfo endpoint.
UserInfo endpoint token validation is disabled by default. To enable it, set micronaut.security.oauth2.userinfo.validator to true:
micronaut.security.oauth2.userinfo.validator=true|
Warning
|
A UserInfo endpoint returns the claims of the user for every access token the provider issued, regardless of the client the token was issued to. The UserInfo endpoint response does not contain an audience, so when this validator is enabled, an access token issued by the same provider to a different client is accepted by your application and the request is authenticated as that token’s user. Enable this validator only when every client registered with the OpenID provider is trusted (for example, a provider or realm dedicated to your application).
|
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).
However, you can set it also via configuration:
Which provider receives the token
A bearer token is only sent to the UserInfo endpoint of the provider which issued it, so that an access token issued by one provider is never disclosed to another provider:
-
If the token is a JWT, its
issclaim must be equal to the expected issuer of the provider:micronaut.security.oauth2.clients..openid.issuer-identifierif set, otherwisemicronaut.security.oauth2.clients..openid.issuer. The issuer announced by the discovery document is only used when neither is configured, since a provider must not be able to claim the issuer of another provider. The comparison is exact and tolerates only the case of the scheme and a trailing slash, the same rule IdTokenClaimsValidator applies. Theissclaim is read without verifying the token, which is left to the provider. A JWT issued by somebody else is never sent to theUserInfoendpoint, not even when only one provider is configured. -
If several providers expect the same issuer but have distinct
UserInfoendpoints (for example two Oracle IDCS tenants, which both issue tokens with the provider wide issuerhttps://identity.oraclecloud.com/), a JWT of that issuer cannot be attributed to one of them. It is handled like an opaque token: sent only to the providers which opt in withvalidate-opaque-tokens: true. A warning naming the providers is logged the first time such a token is checked. -
If no issuer is known for a provider (neither configured nor announced by its discovery document, for example with
fetch-configuration: falseand a manually configureduser-info.url), its validator cannot tell its own JWTs apart from those of other issuers and treats every JWT like an opaque token. A warning is logged at startup; configureopenid.issueroropenid.issuer-identifierto bind the endpoint to an issuer. -
If the token cannot be attributed to a provider (an opaque token, an encrypted JWT, or a JWT without an
issclaim), it is sent to theUserInfoendpoint only when that provider is the only one known to the application (the only enabled OpenID client configured undermicronaut.security.oauth2.clientsand the only UserInfoClientTokenValidatorConfiguration bean, counted together by name), or when the provider explicitly opts in withmicronaut.security.oauth2.clients.*.openid.user-info.validate-opaque-tokens: true. Set the property tofalseto never send such tokens to a provider. The implicit allowance depends on the configured clients, not on which of them were reachable at startup: a provider whose discovery document could not be fetched still counts, so a temporary outage of one provider never routes its tokens to another. A JWT of an issuer shared by several providers is never covered by this implicit allowance; it always requires the explicit opt-in.
|
Warning
|
Enabling validate-opaque-tokens for several providers sends every opaque token to each of them. Only do so if you trust every one of those providers with the tokens of the others.
|
If you register UserInfoClientTokenValidatorConfiguration beans yourself, set issuer and, if needed, validateOpaqueTokens on the builder to get the same behavior.
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 theUserInforesponse 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 thesubclaim, for exampleokta:248289761001, whenmicronaut.security.oauth2.openid.qualify-username-with-provideristrue. 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 undermicronaut.security.oauth2.clients. Thesubattribute 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.clientsmust not contain:. Such a name is not supported by the configuration binding, and theUserInfovalidator additionally rejects it with aConfigurationExceptionwhen usernames are qualified, because the provideralphawith the subjectbeta:victimand the provideralpha:betawith the subjectvictimwould both be namedalpha:beta:victim. Thesubclaim 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.
|
Note
|
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.
|
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:
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.
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
getNamemethod is used to build the URLs used to trigger the client methods -
The
authorizationRedirectmethod returns a response that redirects to the provider -
The
onCallbackmethod 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).
Micronaut Security creates HTTP clients to talk to the identity provider on behalf of your application:
-
DefaultTokenEndpointClient sends the token request (with the client credentials) to the token endpoint.
-
DefaultOpenIdProviderMetadataFetcher retrieves the OpenID provider metadata from the issuer’s discovery document.
-
The UserInfo token validator sends the bearer token to the UserInfo endpoint.
-
HttpClientJwksClient retrieves the JWK Set that verifies the token signatures.
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.
You can proxy GET requests to /.well-known/oauth-authorization-server RFC8414
and /.well-known/openid-configuration Open ID Connect Discovery to an authorization server.
To proxy set the following configuration properties to true:
Path to proxy |
Property |
|
|
|
|
The request sent to the authorization server is a fresh GET for the well-known path at the issuer’s origin: headers (such as Cookie or Authorization), cookies and the query string of the incoming request are not forwarded.
Only a successful (2xx) JSON response from the authorization server is relayed to the caller, and only its Content-Type, Content-Length, Cache-Control, Expires, ETag and Last-Modified headers are copied; every other header, notably Set-Cookie, is dropped and X-Content-Type-Options: nosniff is added. Any other response from the authorization server (an error status or a non-JSON body) is answered with 502 Bad Gateway and an empty body.
Anonymous access is granted only to the well-known paths which are actually proxied. A well-known path whose proxy property is false is secured as any other route of your application.
Read the following guides to learn more abut OAuth:
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.
With Micronaut Gradle Plugin, you can use aotPlugins configuration to declare additional AOT modules to be used:
dependencies {
...
..
//http://github.com/micronaut-projects/micronaut-security/releases
aotPlugins("io.micronaut.security:micronaut-security-aot:3.9.0")
}for Micronaut Maven Plugin you will need to do:
<build>
<plugins>
<plugin>
<groupId>io.micronaut.build</groupId>
<artifactId>micronaut-maven-plugin</artifactId>
<configuration>
<aotDependencies>
<dependency>
<groupId>io.micronaut.security</groupId>
<artifactId>micronaut-security-aot</artifactId>
<version>3.9.0</version>
</dependency>
...
</aotDependencies>
</configuration>
</plugin>
</plugins>
</build>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.
|
Warning
|
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.
|
Warning
|
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.
|
You can find the source code of this project in this repository: