ballerina/auth module
Module Overview
This module provides a set of default authentication store providers that can be extended to create new authentication store providers.
Authentication Store Provider
An authentication store provider defines an authentication scheme that could be used to protect endpoints. The auth:AuthStoreProvider
type acts as the interface for all the authentication providers. Any type of implementation, such as LDAP, JDBC, and file based, should be object-wise similar.
By default, there are three implementations of the auth:AuthStoreProvider
. 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, and finally 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 are two functions that need to be implemented.
authenticate
: Authenticates the user based on a credential, which can be username/password, or a token such as JWT.getScopes
: Provides the scopes associated with the user. Scopes are primarily permissions that are required to access a protected resource.
Config Auth Store Provider
ConfigAuthStoreProvider
is an implementation of the AuthStoreProvider
interface, which uses the Ballerina configuration file to store usernames, passwords, scopes and the 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 seen below.
[b7a.users.<username>]
password="<password>"
scopes="<comma_separated_scopes>"
LDAP Auth Store Provider
LdapAuthStoreProvider
is another implementation of the AuthStoreProvider
interface, which connects to an active
directory or an LDAP to retrieve the necessary user information to perform authentication and authorization.
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 | ||
ConfigAuthProviderConfig | Represents configurations that required for Config auth store. | ||
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. | ||
LdapAuthProviderConfig | Represents configurations that required for LDAP auth store. | ||
SecureClientSocket | Configures the SSL/TLS options to be used for LDAP communication. |
Objects Summary
Object | Description | ||
---|---|---|---|
AuthStoreProvider | Represents the auth store 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 | |||
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 | |
---|---|---|---|---|
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. |
|
RS256 | RS256 | The |
||
RS384 | RS384 | The |
||
RS512 | RS512 | The |
||
NONE | NONE | Unsecured JWTs (no signing) |
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 ConfigAuthProviderConfig record
Represents configurations that required for Config auth store.
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 LdapAuthProviderConfig 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 AuthStoreProvider object
Represents the auth store provider. Any type of implementation, such as LDAP, JDBC, file based, etc. should be object-wise similar
-
<AuthStoreProvider> authenticate(string username, string password) returns (boolean)
Authenticate with username and password
Parameter Name Data Type Default Value Description username string user name
password string password
Return Type Description boolean true if authentication is a success, else false
-
<AuthStoreProvider> 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 user name
Return Type Description string[] array of groups for the user denoted by the username
public type ConfigAuthStoreProvider object
Represents Ballerina configuration file based auth store provider.
Field Name | Data Type | Default Value | Description |
---|---|---|---|
configAuthProviderConfig | auth:ConfigAuthProviderConfig | Config auth store configurations |
-
<ConfigAuthStoreProvider> __init(auth:ConfigAuthProviderConfig configAuthProviderConfig)
Create an Config auth store with the given configurations.
Parameter Name Data Type Default Value Description configAuthProviderConfig auth:ConfigAuthProviderConfig Config auth store configurations
-
<ConfigAuthStoreProvider> authenticate(string user, string password) returns (boolean)
Attempts to authenticate with username and password.
Parameter Name Data Type Default Value Description user string user name
password string password
Return Type Description boolean true if authentication is a success, else false
-
<ConfigAuthStoreProvider> extractHash(string configValue) returns (string)
Extract password hash from the configuration file.
Parameter Name Data Type Default Value Description configValue string config value to extract the password from
Return Type Description string password hash extracted from the configuration field
-
<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
-
<ConfigAuthStoreProvider> readPassword(string username) returns (string)
Reads the password hash for a user.
Parameter Name Data Type Default Value Description username string username
Return Type Description string password hash read from userstore, or nil if not found
-
<ConfigAuthStoreProvider> getConfigAuthValue(string instanceId, string property) returns (string)
Parameter Name Data Type Default Value Description instanceId string property string Return Type Description string -
<ConfigAuthStoreProvider> getArray(string groupString) returns (string[])
Construct an array of groups from the comma separed group string passed.
Parameter Name Data Type Default Value Description groupString string comma separated string of groups
Return Type Description string[] array of groups, nil if the groups string is empty/nil
public type JWTAuthProvider object
Field Name | Data Type | Default Value | Description |
---|---|---|---|
jwtAuthProviderConfig | auth:JWTAuthProviderConfig |
-
<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, false otherwise. If an error occur during authentication, the error will be returned.
public type LdapAuthStoreProvider object
Represents Ballerina configuration for LDAP based auth store provider
Field Name | Data Type | Default Value | Description |
---|---|---|---|
ldapAuthProviderConfig | auth:LdapAuthProviderConfig | LDAP auth store configurations |
|
instanceId | string | Endpoint instance id |
-
<LdapAuthStoreProvider> __init(auth:LdapAuthProviderConfig ldapAuthProviderConfig, string instanceId)
Create an LDAP auth store with the given configurations.
Parameter Name Data Type Default Value Description ldapAuthProviderConfig auth:LdapAuthProviderConfig LDAP auth store configurations
instanceId string Endpoint instance id
-
<LdapAuthStoreProvider> authenticate(string username, string password) returns (boolean)
Authenticate with username and password
Parameter Name Data Type Default Value Description username string user name
password string password
Return Type Description boolean true if authentication is a success, else false
-
<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 user name
password string password
Return Type Description boolean true if authentication is a success, else false
-
<LdapAuthStoreProvider> getScopesOfUser(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