ballerina/auth module
Module Overview
This module provides a set of default authentication provider configurations that can be extended to create new authentication providers.
Authentication Provider
An authentication provider defines an authentication scheme that could be used to authenticate endpoints. The auth:AuthStoreProvider
acts as the interface for all the authentication providers. Any type of implementation such as LDAP, JDBC, and file-based should be object-equivalent.
By default, there are three implementations of the auth:AuthProvider
. They are:
- The
auth:ConfigAuthStoreProvider
, which authenticates based on usernames and passwords stored in a configuration file. - The
auth:JWTAuthProvider
, which authenticates by validating a JWT. - The
auth:LdapAuthStoreProvider
, which authenticates based on the user credentials stored in an active directory or an LDAP.
When creating a new authentication provider, there is a function that needs to be implemented.
authenticate
: Authenticates the user based on a credential, which can be username/password, or a token such as JWT.
Config Auth Store Provider
The auth:ConfigAuthStoreProvider
is an implementation of the auth:AuthProvider
interface, which uses the Ballerina configuration file to store usernames, passwords, scopes, and relevant associations.
A user is denoted by a section in the configuration file. The password and the scopes assigned to the user are denoted as keys under the relevant user section as shown below.
[b7a.users.<username>]
password="<password>"
scopes="<comma_separated_scopes>"
LDAP Auth Store Provider
The auth:LdapAuthStoreProvider
is another implementation of the auth:AuthProvider
interface. This connects to an active directory or an LDAP, retrieves the necessary user information, and performs authentication and authorization.
JWT Auth Provider
The auth:JWTAuthProvider
is another implementation of the auth:AuthProvider
interface, which authenticates by validating a JWT.
Type Definitions
Type | Values | Description | |
---|---|---|---|
JwtSigningAlgorithm | RS512 | RS384 | RS256 | NONE | The key algorithms supported by crypto module. |
Records Summary
Record | Description | ||
---|---|---|---|
CachedJwt | Represents parsed and cached JWT. | ||
InferredJwtIssuerConfig | Represents authentication provider configurations that supports generating JWT for client interactions. | ||
JWTAuthProviderConfig | Represents JWT validator configurations. | ||
JWTIssuerConfig | Represents JWT issuer configurations. | ||
JWTValidatorConfig | Represents JWT validator configurations. | ||
JwtHeader | Represents a JWT header. | ||
JwtPayload | Represents a JWT payload. | ||
LdapAuthStoreProviderConfig | Represents configurations that required for LDAP auth store. | ||
SecureClientSocket | Configures the SSL/TLS options to be used for LDAP communication. |
Objects Summary
Object | Description | ||
---|---|---|---|
AuthProvider | Represents the auth provider. Any type of implementation, such as LDAP, JDBC, file based, etc. should be object-wise similar |
||
ConfigAuthStoreProvider | Represents Ballerina configuration file based auth store provider. |
||
JWTAuthProvider | Represents a JWT Authenticator. |
||
LdapAuthStoreProvider | Represents Ballerina configuration for LDAP based auth store provider. |
Functions Summary
Return Type | Function and Description | ||
---|---|---|---|
initLdapConnectionContext(auth:LdapAuthStoreProvider ldapAuthStoreProvider, string instanceId) Initailizes LDAP connection context. |
|||
string|error<> | issueJwt(auth:JwtHeader header, auth:JwtPayload payload, auth:JWTIssuerConfig? config) Issue a JWT token based on provided header and payload. JWT will be signed (JWS) if |
||
JwtPayload|error<> | validateJwt(string jwtToken, auth:JWTValidatorConfig config) Validity given JWT string. |
Constants
Name | Data Type | Value | Description | |
---|---|---|---|---|
RS256 | RS256 | The |
||
RS384 | RS384 | The |
||
RS512 | RS512 | The |
||
NONE | NONE | Unsecured JWTs (no signing) |
||
AUTH_ERROR_CODE | {ballerina/auth}AuthError | Constant for the auth error code. |
||
DEFAULT_CHARSET | string | UTF-8 | Default charset to be used with password hashing. |
|
CONFIG_PREFIX | string | @ | Prefix used to denote special configuration values. |
|
CONFIG_PREFIX_SHA256 | string | @sha256: | Prefix used to denote that the config value is a SHA-256 hash. |
|
CONFIG_PREFIX_SHA384 | string | @sha384: | Prefix used to denote that the config value is a SHA-384 hash. |
|
CONFIG_PREFIX_SHA512 | string | @sha512: | Prefix used to denote that the config value is a SHA-512 hash. |
public type CachedJwt record
Represents parsed and cached JWT.
Field Name | Data Type | Default Value | Description |
---|---|---|---|
jwtPayload | auth:JwtPayload | Parsed JWT payload |
|
expiryTime | int | Expiry time of the JWT |
public type InferredJwtIssuerConfig record
Represents authentication provider configurations that supports generating JWT for client interactions.
Field Name | Data Type | Default Value | Description |
---|---|---|---|
issuer | string | Expected JWT token issuer |
|
audience | string[] | Expected JWT token audience |
|
expTime | int | 300 | Expiry time for newly issued JWT tokens |
keyStore | crypto:KeyStore | Keystore containing the signing key |
|
keyAlias | string | Key alias for signing newly issued JWT tokens |
|
keyPassword | string | Key password for signing newly issued JWT tokens |
|
signingAlg | RS256|RS384|RS512|NONE | RS256 | Signing algorithm for signing newly issued JWT tokens |
public type JWTAuthProviderConfig record
Represents JWT validator configurations.
Field Name | Data Type | Default Value | Description |
---|---|---|---|
issuer | string | Identifier of the token issuer |
|
audience | string[] | Identifier of the token recipients |
|
clockSkew | int | 0 | Time in seconds to mitigate clock skew |
trustStore | crypto:TrustStore | Trust store used for signature verification |
|
certificateAlias | string | Token signed key alias |
|
validateCertificate | boolean | Validate public key certificate notBefore and notAfter periods |
|
jwtCache | cache:Cache | BLangTypeInit: new null ([]) | Cache used to store parsed JWT information as CachedJwt |
public type JWTIssuerConfig record
Represents JWT issuer configurations.
Field Name | Data Type | Default Value | Description |
---|---|---|---|
keyStore | crypto:KeyStore | Keystore to be used in JWT signing |
|
keyAlias | string | Signing key alias |
|
keyPassword | string | Signing key password |
|
audienceAsArray | boolean | false | Always represent audience as an array (even when there is single audience) |
public type JWTValidatorConfig record
Represents JWT validator configurations.
Field Name | Data Type | Default Value | Description |
---|---|---|---|
issuer | string | Expected issuer |
|
audience | string[] | Expected audience |
|
clockSkew | int | 0 | Clock skew in seconds |
trustStore | crypto:TrustStore | Trust store used for signature verification |
|
certificateAlias | string | Token signed public key certificate alias |
|
validateCertificate | boolean | Validate public key certificate notBefore and notAfter periods |
public type JwtHeader record
Represents a JWT header.
Field Name | Data Type | Default Value | Description |
---|---|---|---|
alg | RS256|RS384|RS512|NONE | Signing algorithm |
|
typ | string | Media type of the JWT |
|
cty | string | Content type, convey structural information about the JWT |
|
kid | string | Key ID, hint indicating which key was used to secure the JWS |
public type JwtPayload record
Represents a JWT payload.
Field Name | Data Type | Default Value | Description |
---|---|---|---|
iss | string | Issuer, identifies the principal that issued the JWT |
|
sub | string | Subject, identifies the principal that is the subject of the JWT |
|
aud | string[] | Audience, identifies the recipients that the JWT is intended for |
|
jti | string | JWT ID, unique identifier for the JWT |
|
exp | int | Expiration time, identifies the expiration time on or after which the JWT must not be accepted |
|
nbf | int | Not before, identifies the time before which the JWT must not be accepted |
|
iat | int | Issued at, identifies the time at which the JWT was issued |
|
customClaims | map |
Map of custom claims |
public type LdapAuthStoreProviderConfig record
Represents configurations that required for LDAP auth store.
Field Name | Data Type | Default Value | Description |
---|---|---|---|
domainName | string | Unique name to identify the user store |
|
connectionURL | string | Connection URL to the LDAP server |
|
connectionName | string | The username used to connect to the LDAP server |
|
connectionPassword | string | Password for the ConnectionName user |
|
userSearchBase | string | DN of the context or object under which the user entries are stored in the LDAP server |
|
userEntryObjectClass | string | Object class used to construct user entries |
|
userNameAttribute | string | The attribute used for uniquely identifying a user entry |
|
userNameSearchFilter | string | Filtering criteria used to search for a particular user entry |
|
userNameListFilter | string | Filtering criteria for searching user entries in the LDAP server |
|
groupSearchBase | string[] | DN of the context or object under which the group entries are stored in the LDAP server |
|
groupEntryObjectClass | string | Object class used to construct group entries |
|
groupNameAttribute | string | The attribute used for uniquely identifying a group entry |
|
groupNameSearchFilter | string | Filtering criteria used to search for a particular group entry |
|
groupNameListFilter | string | Filtering criteria for searching group entries in the LDAP server |
|
membershipAttribute | string | Define the attribute that contains the distinguished names (DN) of user objects that are in a group |
|
userRolesCacheEnabled | boolean | false | To indicate whether to cache the role list of a user |
connectionPoolingEnabled | boolean | true | Define whether LDAP connection pooling is enabled |
ldapConnectionTimeout | int | 5000 | Timeout in making the initial LDAP connection |
readTimeout | int | 60000 | The value of this property is the read timeout in milliseconds for LDAP operations |
retryAttempts | int | 0 | Retry the authentication request if a timeout happened |
secureClientSocket | auth:SecureClientSocket? | () | The SSL configurations for the ldap client socket. This needs to be configured in order to communicate through ldaps. |
public type SecureClientSocket record
Configures the SSL/TLS options to be used for LDAP communication.
Field Name | Data Type | Default Value | Description |
---|---|---|---|
trustStore | crypto:TrustStore? | () | Configures the trust store to be used |
trustedCertFile | string | A file containing a list of certificates or a single certificate that the client trusts |
public function initLdapConnectionContext(auth:LdapAuthStoreProvider ldapAuthStoreProvider, string instanceId)
Initailizes LDAP connection context.
Parameter Name | Data Type | Default Value | Description |
---|---|---|---|
ldapAuthStoreProvider | auth:LdapAuthStoreProvider | LdapAuthStoreProvider provider object |
|
instanceId | string | Unique id generated to identify an endpoint |
public function issueJwt(auth:JwtHeader header, auth:JwtPayload payload, auth:JWTIssuerConfig? config) returns (string|error<>)
Issue a JWT token based on provided header and payload. JWT will be signed (JWS) if keyStore
information is provided
in the JWTIssuerConfig
and the alg
field of JwtHeader
is not NONE
.
Parameter Name | Data Type | Default Value | Description |
---|---|---|---|
header | auth:JwtHeader | JwtHeader object |
|
payload | auth:JwtPayload | JwtPayload object |
|
config | auth:JWTIssuerConfig? | JWT issuer config record |
Return Type | Description | ||
---|---|---|---|
string|error<> | JWT token string or an error if token validation fails |
public function validateJwt(string jwtToken, auth:JWTValidatorConfig config) returns (JwtPayload|error<>)
Validity given JWT string.
Parameter Name | Data Type | Default Value | Description |
---|---|---|---|
jwtToken | string | JWT token that need to validate |
|
config | auth:JWTValidatorConfig | JWT validator config record |
Return Type | Description | ||
---|---|---|---|
JwtPayload|error<> | If JWT token is valied return the JWT payload. An error if token validation fails. |
public type AuthProvider object
Represents the auth provider. Any type of implementation, such as LDAP, JDBC, file based, etc. should be object-wise similar
-
<AuthProvider> authenticate(string credential) returns (boolean|error<>)
Authenticate with credential value passed.
Parameter Name Data Type Default Value Description credential string Credential value
Return Type Description boolean|error<> True if authentication is a success, else false or
error
occurred
public type ConfigAuthStoreProvider object
Represents Ballerina configuration file based auth store provider.
-
<ConfigAuthStoreProvider> authenticate(string credential) returns (boolean|error<>)
Attempts to authenticate with credential.
Parameter Name Data Type Default Value Description credential string Credential
Return Type Description boolean|error<> true
if authentication is successful, otherwisefalse
orerror
occured while extracting credentials -
<ConfigAuthStoreProvider> getScopes(string username) returns (string[])
Reads the scope(s) for the user with the given username.
Parameter Name Data Type Default Value Description username string Username
Return Type Description string[] Array of groups for the user denoted by the username
public type JWTAuthProvider object
Represents a JWT Authenticator.
Field Name | Data Type | Default Value | Description |
---|---|---|---|
jwtAuthProviderConfig | auth:JWTAuthProviderConfig | JWT auth provider configurations |
-
<JWTAuthProvider> __init(auth:JWTAuthProviderConfig jwtAuthProviderConfig)
Provides authentication based on the provided jwt token.
Parameter Name Data Type Default Value Description jwtAuthProviderConfig auth:JWTAuthProviderConfig JWT authentication provider configurations
-
<JWTAuthProvider> authenticate(string jwtToken) returns (boolean|error<>)
Authenticate with a jwt token.
Parameter Name Data Type Default Value Description jwtToken string Jwt token extracted from the authentication header
Return Type Description boolean|error<> true
if authentication is successful, othewisefalse
orerror
occured during jwt validation
public type LdapAuthStoreProvider object
Represents Ballerina configuration for LDAP based auth store provider.
Field Name | Data Type | Default Value | Description |
---|---|---|---|
ldapAuthStoreProviderConfig | auth:LdapAuthStoreProviderConfig | LDAP auth store configurations |
|
instanceId | string | Endpoint instance id |
-
<LdapAuthStoreProvider> __init(auth:LdapAuthStoreProviderConfig ldapAuthStoreProviderConfig, string instanceId)
Create an LDAP auth store with the given configurations.
Parameter Name Data Type Default Value Description ldapAuthStoreProviderConfig auth:LdapAuthStoreProviderConfig LDAP auth store configurations
instanceId string Endpoint instance id
-
<LdapAuthStoreProvider> authenticate(string credential) returns (boolean|error<>)
Authenticate with username and password.
Parameter Name Data Type Default Value Description credential string Credential value
Return Type Description boolean|error<> true
if authentication is successful, otherwisefalse
orerror
occured while extracting credentials -
<LdapAuthStoreProvider> getScopes(string username) returns (string[])
Reads the scope(s) for the user with the given username.
Parameter Name Data Type Default Value Description username string Username
Return Type Description string[] Array of groups for the user denoted by the username
-
<LdapAuthStoreProvider> doAuthenticate(string username, string password) returns (boolean)
Authenticate with username and password.
Parameter Name Data Type Default Value Description username string Username
password string Password
Return Type Description boolean true if authentication is a success, else false