- Elasticsearch Guide: other versions:
- What is Elasticsearch?
- What’s new in 8.5
- Set up Elasticsearch
- Installing Elasticsearch
- Run Elasticsearch locally
- Configuring Elasticsearch
- Important Elasticsearch configuration
- Secure settings
- Auditing settings
- Circuit breaker settings
- Cluster-level shard allocation and routing settings
- Miscellaneous cluster settings
- Cross-cluster replication settings
- Discovery and cluster formation settings
- Field data cache settings
- Health Diagnostic settings
- Index lifecycle management settings
- Index management settings
- Index recovery settings
- Indexing buffer settings
- License settings
- Local gateway settings
- Logging
- Machine learning settings
- Monitoring settings
- Node
- Networking
- Node query cache settings
- Search settings
- Security settings
- Shard request cache settings
- Snapshot and restore settings
- Transforms settings
- Thread pools
- Watcher settings
- Advanced configuration
- Important system configuration
- Bootstrap Checks
- Heap size check
- File descriptor check
- Memory lock check
- Maximum number of threads check
- Max file size check
- Maximum size virtual memory check
- Maximum map count check
- Client JVM check
- Use serial collector check
- System call filter check
- OnError and OnOutOfMemoryError checks
- Early-access check
- G1GC check
- All permission check
- Discovery configuration check
- Bootstrap Checks for X-Pack
- Starting Elasticsearch
- Stopping Elasticsearch
- Discovery and cluster formation
- Add and remove nodes in your cluster
- Full-cluster restart and rolling restart
- Remote clusters
- Plugins
- Upgrade Elasticsearch
- Index modules
- Mapping
- Text analysis
- Overview
- Concepts
- Configure text analysis
- Built-in analyzer reference
- Tokenizer reference
- Token filter reference
- Apostrophe
- ASCII folding
- CJK bigram
- CJK width
- Classic
- Common grams
- Conditional
- Decimal digit
- Delimited payload
- Dictionary decompounder
- Edge n-gram
- Elision
- Fingerprint
- Flatten graph
- Hunspell
- Hyphenation decompounder
- Keep types
- Keep words
- Keyword marker
- Keyword repeat
- KStem
- Length
- Limit token count
- Lowercase
- MinHash
- Multiplexer
- N-gram
- Normalization
- Pattern capture
- Pattern replace
- Phonetic
- Porter stem
- Predicate script
- Remove duplicates
- Reverse
- Shingle
- Snowball
- Stemmer
- Stemmer override
- Stop
- Synonym
- Synonym graph
- Trim
- Truncate
- Unique
- Uppercase
- Word delimiter
- Word delimiter graph
- Character filters reference
- Normalizers
- Index templates
- Data streams
- Ingest pipelines
- Example: Parse logs
- Enrich your data
- Processor reference
- Append
- Attachment
- Bytes
- Circle
- Community ID
- Convert
- CSV
- Date
- Date index name
- Dissect
- Dot expander
- Drop
- Enrich
- Fail
- Fingerprint
- Foreach
- GeoIP
- Grok
- Gsub
- HTML strip
- Inference
- Join
- JSON
- KV
- Lowercase
- Network direction
- Pipeline
- Registered domain
- Remove
- Rename
- Script
- Set
- Set security user
- Sort
- Split
- Trim
- Uppercase
- URL decode
- URI parts
- User agent
- Aliases
- Search your data
- Collapse search results
- Filter search results
- Highlighting
- Long-running searches
- Near real-time search
- Paginate search results
- Retrieve inner hits
- Retrieve selected fields
- Search across clusters
- Search multiple data streams and indices
- Search shard routing
- Search templates
- Sort search results
- kNN search
- Query DSL
- Aggregations
- Bucket aggregations
- Adjacency matrix
- Auto-interval date histogram
- Categorize text
- Children
- Composite
- Date histogram
- Date range
- Diversified sampler
- Filter
- Filters
- Frequent items
- Geo-distance
- Geohash grid
- Geohex grid
- Geotile grid
- Global
- Histogram
- IP prefix
- IP range
- Missing
- Multi Terms
- Nested
- Parent
- Random sampler
- Range
- Rare terms
- Reverse nested
- Sampler
- Significant terms
- Significant text
- Terms
- Variable width histogram
- Subtleties of bucketing range fields
- Metrics aggregations
- Pipeline aggregations
- Average bucket
- Bucket script
- Bucket count K-S test
- Bucket correlation
- Bucket selector
- Bucket sort
- Change point
- Cumulative cardinality
- Cumulative sum
- Derivative
- Extended stats bucket
- Inference bucket
- Max bucket
- Min bucket
- Moving function
- Moving percentiles
- Normalize
- Percentiles bucket
- Serial differencing
- Stats bucket
- Sum bucket
- Bucket aggregations
- EQL
- SQL
- Overview
- Getting Started with SQL
- Conventions and Terminology
- Security
- SQL REST API
- SQL Translate API
- SQL CLI
- SQL JDBC
- SQL ODBC
- SQL Client Applications
- SQL Language
- Functions and Operators
- Comparison Operators
- Logical Operators
- Math Operators
- Cast Operators
- LIKE and RLIKE Operators
- Aggregate Functions
- Grouping Functions
- Date/Time and Interval Functions and Operators
- Full-Text Search Functions
- Mathematical Functions
- String Functions
- Type Conversion Functions
- Geo Functions
- Conditional Functions And Expressions
- System Functions
- Reserved keywords
- SQL Limitations
- Scripting
- Data management
- ILM: Manage the index lifecycle
- Tutorial: Customize built-in policies
- Tutorial: Automate rollover
- Index management in Kibana
- Overview
- Concepts
- Index lifecycle actions
- Configure a lifecycle policy
- Migrate index allocation filters to node roles
- Troubleshooting index lifecycle management errors
- Start and stop index lifecycle management
- Manage existing indices
- Skip rollover
- Restore a managed data stream or index
- Data tiers
- Autoscaling
- Monitor a cluster
- Roll up or transform your data
- Set up a cluster for high availability
- Snapshot and restore
- Secure the Elastic Stack
- Elasticsearch security principles
- Start the Elastic Stack with security enabled automatically
- Manually configure security
- Updating node security certificates
- User authentication
- Built-in users
- Service accounts
- Internal users
- Token-based authentication services
- User profiles
- Realms
- Realm chains
- Security domains
- Active Directory user authentication
- File-based user authentication
- LDAP user authentication
- Native user authentication
- OpenID Connect authentication
- PKI user authentication
- SAML authentication
- Kerberos authentication
- JWT authentication
- Integrating with other authentication systems
- Enabling anonymous access
- Looking up users without authentication
- Controlling the user cache
- Configuring SAML single-sign-on on the Elastic Stack
- Configuring single sign-on to the Elastic Stack using OpenID Connect
- User authorization
- Built-in roles
- Defining roles
- Security privileges
- Document level security
- Field level security
- Granting privileges for data streams and aliases
- Mapping users and groups to roles
- Setting up field and document level security
- Submitting requests on behalf of other users
- Configuring authorization delegation
- Customizing roles and authorization
- Enable audit logging
- Restricting connections with IP filtering
- Securing clients and integrations
- Operator privileges
- Troubleshooting
- Some settings are not returned via the nodes settings API
- Authorization exceptions
- Users command fails due to extra arguments
- Users are frequently locked out of Active Directory
- Certificate verification fails for curl on Mac
- SSLHandshakeException causes connections to fail
- Common SSL/TLS exceptions
- Common Kerberos exceptions
- Common SAML issues
- Internal Server Error in Kibana
- Setup-passwords command fails due to connection failure
- Failures due to relocation of the configuration files
- Limitations
- Watcher
- Command line tools
- elasticsearch-certgen
- elasticsearch-certutil
- elasticsearch-create-enrollment-token
- elasticsearch-croneval
- elasticsearch-keystore
- elasticsearch-node
- elasticsearch-reconfigure-node
- elasticsearch-reset-password
- elasticsearch-saml-metadata
- elasticsearch-service-tokens
- elasticsearch-setup-passwords
- elasticsearch-shard
- elasticsearch-syskeygen
- elasticsearch-users
- How to
- Troubleshooting
- Fix common cluster issues
- Diagnose unassigned shards
- Add a missing tier to the system
- Allow Elasticsearch to allocate the data in the system
- Allow Elasticsearch to allocate the index
- Indices mix index allocation filters with data tiers node roles to move through data tiers
- Not enough nodes to allocate all shard replicas
- Total number of shards for an index on a single node exceeded
- Total number of shards per node has been reached
- Troubleshooting corruption
- Fix data nodes out of disk
- Fix master nodes out of disk
- Fix other role nodes out of disk
- Start index lifecycle management
- Start Snapshot Lifecycle Management
- Restore from snapshot
- Multiple deployments writing to the same snapshot repository
- Addressing repeated snapshot policy failures
- Troubleshooting discovery
- Troubleshooting monitoring
- Troubleshooting transforms
- Troubleshooting Watcher
- Troubleshooting searches
- REST APIs
- API conventions
- Common options
- REST API compatibility
- Autoscaling APIs
- Compact and aligned text (CAT) APIs
- cat aliases
- cat allocation
- cat anomaly detectors
- cat count
- cat data frame analytics
- cat datafeeds
- cat fielddata
- cat health
- cat indices
- cat master
- cat nodeattrs
- cat nodes
- cat pending tasks
- cat plugins
- cat recovery
- cat repositories
- cat segments
- cat shards
- cat snapshots
- cat task management
- cat templates
- cat thread pool
- cat trained model
- cat transforms
- Cluster APIs
- Cluster allocation explain
- Cluster get settings
- Cluster health
- Health
- Cluster reroute
- Cluster state
- Cluster stats
- Cluster update settings
- Nodes feature usage
- Nodes hot threads
- Nodes info
- Nodes reload secure settings
- Nodes stats
- Pending cluster tasks
- Remote cluster info
- Task management
- Voting configuration exclusions
- Create or update desired nodes
- Get desired nodes
- Delete desired nodes
- Cross-cluster replication APIs
- Data stream APIs
- Document APIs
- Enrich APIs
- EQL APIs
- Features APIs
- Fleet APIs
- Find structure API
- Graph explore API
- Index APIs
- Alias exists
- Aliases
- Analyze
- Analyze index disk usage
- Clear cache
- Clone index
- Close index
- Create index
- Create or update alias
- Create or update component template
- Create or update index template
- Create or update index template (legacy)
- Delete component template
- Delete dangling index
- Delete alias
- Delete index
- Delete index template
- Delete index template (legacy)
- Exists
- Field usage stats
- Flush
- Force merge
- Get alias
- Get component template
- Get field mapping
- Get index
- Get index settings
- Get index template
- Get index template (legacy)
- Get mapping
- Import dangling index
- Index recovery
- Index segments
- Index shard stores
- Index stats
- Index template exists (legacy)
- List dangling indices
- Open index
- Refresh
- Resolve index
- Rollover
- Shrink index
- Simulate index
- Simulate template
- Split index
- Unfreeze index
- Update index settings
- Update mapping
- Index lifecycle management APIs
- Create or update lifecycle policy
- Get policy
- Delete policy
- Move to step
- Remove policy
- Retry policy
- Get index lifecycle management status
- Explain lifecycle
- Start index lifecycle management
- Stop index lifecycle management
- Migrate indices, ILM policies, and legacy, composable and component templates to data tiers routing
- Ingest APIs
- Info API
- Licensing APIs
- Logstash APIs
- Machine learning APIs
- Machine learning anomaly detection APIs
- Add events to calendar
- Add jobs to calendar
- Close jobs
- Create jobs
- Create calendars
- Create datafeeds
- Create filters
- Delete calendars
- Delete datafeeds
- Delete events from calendar
- Delete filters
- Delete forecasts
- Delete jobs
- Delete jobs from calendar
- Delete model snapshots
- Delete expired data
- Estimate model memory
- Flush jobs
- Forecast jobs
- Get buckets
- Get calendars
- Get categories
- Get datafeeds
- Get datafeed statistics
- Get influencers
- Get jobs
- Get job statistics
- Get model snapshots
- Get model snapshot upgrade statistics
- Get overall buckets
- Get scheduled events
- Get filters
- Get records
- Open jobs
- Post data to jobs
- Preview datafeeds
- Reset jobs
- Revert model snapshots
- Start datafeeds
- Stop datafeeds
- Update datafeeds
- Update filters
- Update jobs
- Update model snapshots
- Upgrade model snapshots
- Machine learning data frame analytics APIs
- Create data frame analytics jobs
- Delete data frame analytics jobs
- Evaluate data frame analytics
- Explain data frame analytics
- Get data frame analytics jobs
- Get data frame analytics jobs stats
- Preview data frame analytics
- Start data frame analytics jobs
- Stop data frame analytics jobs
- Update data frame analytics jobs
- Machine learning trained model APIs
- Clear trained model deployment cache
- Create or update trained model aliases
- Create part of a trained model
- Create trained models
- Create trained model vocabulary
- Delete trained model aliases
- Delete trained models
- Get trained models
- Get trained models stats
- Infer trained model
- Start trained model deployment
- Stop trained model deployment
- Migration APIs
- Node lifecycle APIs
- Reload search analyzers API
- Repositories metering APIs
- Rollup APIs
- Script APIs
- Search APIs
- Searchable snapshots APIs
- Security APIs
- Authenticate
- Change passwords
- Clear cache
- Clear roles cache
- Clear privileges cache
- Clear API key cache
- Clear service account token caches
- Create API keys
- Create or update application privileges
- Create or update role mappings
- Create or update roles
- Create or update users
- Create service account tokens
- Delegate PKI authentication
- Delete application privileges
- Delete role mappings
- Delete roles
- Delete service account token
- Delete users
- Disable users
- Enable users
- Enroll Kibana
- Enroll node
- Get API key information
- Get application privileges
- Get builtin privileges
- Get role mappings
- Get roles
- Get service accounts
- Get service account credentials
- Get token
- Get user privileges
- Get users
- Grant API keys
- Has privileges
- Invalidate API key
- Invalidate token
- OpenID Connect prepare authentication
- OpenID Connect authenticate
- OpenID Connect logout
- Query API key information
- Update API key
- Bulk update API keys
- SAML prepare authentication
- SAML authenticate
- SAML logout
- SAML invalidate
- SAML complete logout
- SAML service provider metadata
- SSL certificate
- Activate user profile
- Disable user profile
- Enable user profile
- Get user profiles
- Suggest user profile
- Update user profile data
- Has privileges user profile
- Snapshot and restore APIs
- Snapshot lifecycle management APIs
- SQL APIs
- Transform APIs
- Usage API
- Watcher APIs
- Definitions
- Migration guide
- Release notes
- Elasticsearch version 8.5.3
- Elasticsearch version 8.5.2
- Elasticsearch version 8.5.1
- Elasticsearch version 8.5.0
- Elasticsearch version 8.4.3
- Elasticsearch version 8.4.2
- Elasticsearch version 8.4.1
- Elasticsearch version 8.4.0
- Elasticsearch version 8.3.3
- Elasticsearch version 8.3.2
- Elasticsearch version 8.3.1
- Elasticsearch version 8.3.0
- Elasticsearch version 8.2.3
- Elasticsearch version 8.2.2
- Elasticsearch version 8.2.1
- Elasticsearch version 8.2.0
- Elasticsearch version 8.1.3
- Elasticsearch version 8.1.2
- Elasticsearch version 8.1.1
- Elasticsearch version 8.1.0
- Elasticsearch version 8.0.1
- Elasticsearch version 8.0.0
- Elasticsearch version 8.0.0-rc2
- Elasticsearch version 8.0.0-rc1
- Elasticsearch version 8.0.0-beta1
- Elasticsearch version 8.0.0-alpha2
- Elasticsearch version 8.0.0-alpha1
- Dependencies and versions
JWT authentication
editJWT authentication
editThis functionality is in beta and is subject to change. The design and code is less mature than official GA features and is being provided as-is with no warranties. Beta features are not subject to the support SLA of official GA features.
Elasticsearch can be configured to trust JSON Web Tokens (JWTs) issued from an external service as bearer tokens for authentication.
When a JWT realm is used to authenticate with Elasticsearch, a distinction is made between the client that is connecting to Elasticsearch, and the user on whose behalf the request should run. The JWT authenticates the user, and a separate credential authenticates the client.
A common scenario for JWTs is when an existing front-end application uses OpenID Connect (OIDC) to authenticate and identify a user, and then accesses Elasticsearch on behalf of the authenticated user.
If the front-end application does not exist, you can use the Token-based authentication services instead.
JWT uses OIDC workflows
editJWT authentication in Elasticsearch is derived from OIDC user workflows, where different tokens can be issued by an OIDC Provider (OP). One possible token is an ID token, which uses the JWT format. If the ID token is presented to a JWT realm, Elasticsearch can use it as a bearer token to authenticate, identify, and authorize an individual user.
Because JWTs are obtained external to Elasticsearch, you can define a custom workflow instead of using the OIDC workflow. However, the JWT format must still be JSON Web Signature (JWS). The JWS header and JWS signature are validated using OIDC ID token validation rules.
Elasticsearch supports a separate OpenID Connect realm, which provides stronger security guarantees than the JWT realm, and is preferred for any use case where Elasticsearch can act as an OIDC RP. The OIDC realm is the only supported way to enable OIDC authentication in Kibana.
If JWTs are issued for the front-end application, the application is the realm client and JWT user.
That is not supported by OIDC flows, but it may be supported by bespoke JWT issuers.
In that case, use the client secret and JWT for the client application, and the
es-security-runas-user
HTTP request header for the different user. See Applying the run_as
privilege to JWT realm users.
Configure Elasticsearch to use a JWT realm
editTo use JWT authentication, create the realm in the elasticsearch.yml
file
to configure it within the Elasticsearch authentication chain.
The JWT realm has a few mandatory settings, plus optional settings that are described in JWT realm settings.
Client authentication is enabled by default for the JWT realms. Disabling client authentication is possible, but strongly discouraged.
-
Add your JWT realm to the
elasticsearch.yml
file. The following example includes the most common settings, which are not intended for every use case:xpack.security.authc.realms.jwt.jwt1: order: 3 client_authentication.type: shared_secret allowed_issuer: "https://issuer.example.com/jwt/" allowed_audiences: [ "8fb85eba-979c-496c-8ae2-a57fde3f12d0" ] allowed_signature_algorithms: [RS256,HS256] pkc_jwkset_path: jwt/jwkset.json claims.principal: sub
-
order
-
Specifies a realm
order
of3
, which indicates the order in which the configured realm is checked when authenticating a user. Realms are consulted in ascending order, where the realm with the lowest order value is consulted first. -
client_authentication.type
-
Specifies the client authentication type as
shared_secret
, which means that the client is authenticated using an HTTP request header that must match a pre-configured secret value. The client must provide this shared secret with every request in theES-Client-Authentication
header. The value must be a case-insensitive match to the realm’sclient_authentication.shared_secret
. -
allowed_issuer
- Sets a verifiable identifier for your JWT issuer. This value is typically a URL, UUID, or some other case-sensitive string value.
-
allowed_audiences
- Specifies a list of JWT audiences that the realm will allow. These values are typically URLs, UUIDs, or other case-sensitive string values.
-
allowed_signature_algorithms
-
Indicates that Elasticsearch should use the
RS256
orHS256
signature algorithms to verify the signature of the JWT from the JWT issuer. -
pkc_jwkset_path
-
The file path to a JSON Web Key Set (JWKS) containing the public key material
that the JWT realm uses to verify JWT signatures. If a path is provided,
then it is resolved relative to the Elasticsearch configuration directory. In Elastic Cloud,
use an absolute path starting with
/app/config/
. -
claims.principal
- The name of the JWT claim that contains the user’s principal (username).
-
-
After defining settings, use the
elasticsearch-keystore
tool to store values for secure settings in the Elasticsearch keystore.-
Store the
shared_secret
value forclient_authentication.type
:bin/elasticsearch-keystore add xpack.security.authc.realms.jwt.jwt1.client_authentication.shared_secret
-
Store the HMAC keys for
allowed_signature_algorithms
, which use the HMAC SHA-256 algorithmHS256
in the example:Path to a JWKS, which is a resource for a set of JSON-encoded secret keys. The file can be removed after you load the contents into the Elasticsearch keystore.
Using the JWKS is preferred. However, you can add an HMAC key in string format using the following command. This format is compatible with HMAC UTF-8 keys, but only supports a single key with no attributes. You can only use one HMAC format (either
hmac_jwkset
orhmac_key
) simultaneously.bin/elasticsearch-keystore add xpack.security.authc.realms.jwt.jwt1.hmac_key
-
JWT encoding and validation
editJWTs can be parsed into three pieces:
- Header
- Provides information about how to validate the token.
- Claims
- Contains data about the calling user or application.
- Signature
- The data that’s used to validate the token.
Header: {"typ":"JWT","alg":"HS256"} Claims: {"aud":"aud8","sub":"security_test_user","iss":"iss8","exp":4070908800,"iat":946684800} Signature: UnnFmsoFKfNmKMsVoDQmKI_3-j95PCaKdgqqau3jPMY
This example illustrates a partial decoding of a JWT. The validity period is
from 2000 to 2099 (inclusive), as defined by the issue time (iat
) and
expiration time (exp
). JWTs typically have a validity period shorter than
100 years, such as 1-2 hours or 1-7 days, not an entire human life.
The signature in this example is deterministic because the header, claims, and
HMAC key are fixed. JWTs typically have a nonce
claim to make the signature
non-deterministic. The supported JWT encoding is JSON Web Signature (JWS), and
the JWS Header
and Signature
are validated using OpenID Connect ID Token
validation rules. Some validation is customizable through
JWT realm settings.
Header claims
editThe header claims indicate the token type and the algorithm used to sign the token.
-
alg
-
(Required, String) Indicates the algorithm that was used to sign the token, such
as
HS256
. The algorithm must be in the realm’s allow list. -
typ
-
(Optional, String) Indicates the token type, which must be
JWT
.
Payload claims
editOIDC ID tokens contain several claims, which provide information about the user who is issuing the token, and the token itself.
OIDC payload claims
editThe following claims are validated by a subset of OIDC ID token rules.
Elasticsearch doesn’t validate nonce
claims, but a custom JWT issuer can add a
random nonce
claim to introduce entropy into the signature.
You can relax validation of any of the time-based claims by setting
allowed_clock_skew
. This value sets the maximum allowed clock skew before
validating JWTs with respect to their authentication time (auth_time
),
creation (iat
), not before (nbf
), and expiration times (exp
).
-
iss
-
(Required, String) Denotes the issuer that created the ID token. The value must
be an exact, case-sensitive match to the value in the
allowed_issuer
setting. -
aud
-
(Required, String) Indicates the audiences that the ID token is for, expressed as a
comma-separated value (CSV). One of the values must be an exact, case-sensitive
match to any of the CSV values in the
allowed_audiences
setting. -
exp
- (Required, integer) Expiration time for the ID token, expressed in UTC seconds since epoch.
-
iat
- (Required, integer) Time that the ID token was issued, expressed in UTC seconds since epoch.
-
nbf
- (Optional, integer) Indicates the time before which the JWT must not be accepted, expressed as UTC seconds since epoch.
-
auth_time
- (Optional, integer) Time when the user authenticated to the JWT issuer, expressed as UTC seconds since epoch.
Elasticsearch settings for consuming OIDC claims
editElasticsearch uses OIDC ID token claims for the following settings.
-
principal
-
(Required, String) Contains the user’s principal (username). The value is
configurable using the realm setting
claims.principal
. If not set, the value defaults tosub
. You can configure an optional regular expression using theclaims.principal_pattern
to extract a substring. -
groups
-
(Optional, JSON array) Contains the user’s group membership.
The value is configurable using the realm setting
claims.groups
. You can configure an optional regular expression using the realm settingclaims.groups_pattern
to extract a substring value. -
name
-
(Optional, String) Contains a human-readable identifier that identifies the
subject of the token. The value is configurable using the realm setting
claims.name
. You can configure an optional regular expression using the realm settingclaims.name_pattern
to extract a substring value. -
mail
-
(Optional, String) Contains the e-mail address to associate with the user. The
value is configurable using the realm setting
claims.mail
. You can configure an optional regular expression using the realm settingclaims.mail_pattern
to extract a substring value. -
dn
-
(Optional, String) Contains the user’s Distinguished Name (DN), which uniquely
identifies a user or group. The value is configurable using the realm setting
claims.dn
. You can configure an optional regular expression using the realm settingclaims.dn_pattern
to extract a substring value.
JWT realm authorization
editThe JWT realm supports authorization with the create or update role mappings API, or delegating authorization to another realm. You cannot use these methods simultaneously, so choose whichever works best for your environment.
You cannot map roles in the JWT realm using the role_mapping.yml
file.
Authorizing with the role mapping API
editYou can use the create or update role mappings API to define role mappings that determine which roles should be assigned to each user based on their username, groups, or other metadata.
PUT /_security/role_mapping/jwt1_users?refresh=true { "roles" : [ "user" ], "rules" : { "all" : [ { "field": { "realm.name": "jwt1" } }, { "field": { "username": "principalname1" } }, { "field": { "dn": "CN=Principal Name 1,DC=example.com" } }, { "field": { "groups": "group1" } }, { "field": { "metadata.jwt_claim_other": "other1" } } ] }, "enabled": true }
If you use this API in the JWT realm, the following claims are available for role mapping:
-
principal
- (Required, String) Principal claim that is used as the Elasticsearch user’s username.
-
dn
- (Optional, String) Distinguished Name (DN) that is used as the Elasticsearch user’s DN.
-
groups
- (Optional, String) Comma-separated value (CSV) list that is used as the Elasticsearch user’s list of groups.
-
metadata
-
(Optional, object) Additional metadata about the user, such as strings, integers,
boolean values, and collections that are used as the Elasticsearch user’s metadata.
These values are key value pairs formatted as
metadata.jwt_claim_<key>
=<value>
.
Delegating JWT authorization to another realm
editIf you delegate authorization to other realms from the
JWT realm, only the principal
claim is available for role lookup. When
delegating the assignment and lookup of roles to another realm from the JWT
realm, claims for dn
, groups
, mail
, metadata
, and name
are not used
for the Elasticsearch user’s values. Only the JWT principal
claim is passed to the
delegated authorization realms. The realms that are delegated for authorization
- not the JWT realm - become responsible for populating all of the Elasticsearch user’s
values.
The following example shows how you define delegation authorization in the
elasticsearch.yml
file to multiple other realms from the JWT realm. A JWT
realm named jwt2
is delegating authorization to multiple realms:
xpack.security.authc.realms.jwt.jwt2.authorization_realms: file1,native1,ldap1,ad1
You can then use the
create or update role mappings API to map
roles to the authorizing realm. The following example maps roles in the native1
realm for the principalname1
JWT principal.
PUT /_security/role_mapping/native1_users?refresh=true { "roles" : [ "user" ], "rules" : { "all" : [ { "field": { "realm.name": "native1" } }, { "field": { "username": "principalname1" } } ] }, "enabled": true }
If realm jwt2
successfully authenticates a client with a JWT for principal
principalname1
, and delegates authorization to one of the listed realms
(such as native1
), then that realm can look up the Elasticsearch user’s values. With
this defined role mapping, the realm can also look up this role mapping rule
linked to realm native1
.
Applying the run_as
privilege to JWT realm users
editElasticsearch can retrieve roles for a JWT user through either role mapping or
delegated authorization. Regardless of which option you choose, you can apply the
run_as
privilege to a role so that a user can
submit authenticated requests to "run as" a different user. To submit requests as
another user, include the es-security-runas-user
header in your requests.
Requests run as if they were issued from that user and Elasticsearch uses their roles.
For example, let’s assume that there’s a user with the username user123_runas
.
The following request creates a user role named jwt_role1
, which specifies a
run_as
user with the user123_runas
username. Any user with the jwt_role1
role can issue requests as the specified run_as
user.
POST /_security/role/jwt_role1?refresh=true { "cluster": ["manage"], "indices": [ { "names": [ "*" ], "privileges": ["read"] } ], "run_as": [ "user123_runas" ], "metadata" : { "version" : 1 } }
You can then map that role to a user in a specific realm. The following request
maps the jwt_role1
role to a user with the username user2
in the jwt2
JWT
realm. This means that Elasticsearch will use the jwt2
realm to authenticate the user
named user2
. Because user2
has a role (the jwt_role1
role) that includes
the run_as
privilege, Elasticsearch retrieves the role mappings for the user123_runas
user and uses the roles for that user to submit requests.
POST /_security/role_mapping/jwt_user1?refresh=true { "roles": [ "jwt_role1"], "rules" : { "all" : [ { "field": { "realm.name": "jwt2" } }, { "field": { "username": "user2" } } ] }, "enabled": true, "metadata" : { "version" : 1 } }
After mapping the roles, you can make an
authenticated call to Elasticsearch using a JWT and include
the ES-Client-Authentication
header:
curl -s -X GET -H "Authorization: Bearer eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJhdWQiOlsiZXMwMSIsImVzMDIiLCJlczAzIl0sInN1YiI6InVzZXIyIiwiaXNzIjoibXktaXNzdWVyIiwiZXhwIjo0MDcwOTA4ODAwLCJpYXQiOjk0NjY4NDgwMCwiZW1haWwiOiJ1c2VyMkBzb21ldGhpbmcuZXhhbXBsZS5jb20ifQ.UgO_9w--EoRyUKcWM5xh9SimTfMzl1aVu6ZBsRWhxQA" -H "ES-Client-Authentication: sharedsecret test-secret" https://localhost:9200/_security/_authenticate
The response includes the user who submitted the request (user2
), including
the jwt_role1
role that you mapped to this user in the JWT realm:
{"username":"user2","roles":["jwt_role1"],"full_name":null,"email":"user2@something.example.com", "metadata":{"jwt_claim_email":"user2@something.example.com","jwt_claim_aud":["es01","es02","es03"], "jwt_claim_sub":"user2","jwt_claim_iss":"my-issuer"},"enabled":true,"authentication_realm": {"name":"jwt2","type":"jwt"},"lookup_realm":{"name":"jwt2","type":"jwt"},"authentication_type":"realm"} %
If you want to specify a request as the run_as
user, include the
the es-security-runas-user
header with the name of the user that you
want to submit requests as. The following request uses the user123_runas
user:
curl -s -X GET -H "Authorization: Bearer eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJhdWQiOlsiZXMwMSIsImVzMDIiLCJlczAzIl0sInN1YiI6InVzZXIyIiwiaXNzIjoibXktaXNzdWVyIiwiZXhwIjo0MDcwOTA4ODAwLCJpYXQiOjk0NjY4NDgwMCwiZW1haWwiOiJ1c2VyMkBzb21ldGhpbmcuZXhhbXBsZS5jb20ifQ.UgO_9w--EoRyUKcWM5xh9SimTfMzl1aVu6ZBsRWhxQA" -H "ES-Client-Authentication: sharedsecret test-secret" -H "es-security-runas-user: user123_runas" https://localhost:9200/_security/_authenticate
In the response, you’ll see that the user123_runas
user submitted the request,
and Elasticsearch used the jwt_role1
role:
{"username":"user123_runas","roles":["jwt_role1"],"full_name":null,"email":null,"metadata":{}, "enabled":true,"authentication_realm":{"name":"jwt2","type":"jwt"},"lookup_realm":{"name":"native", "type":"native"},"authentication_type":"realm"}%
PKC JWKS reloading
editJWT authentication supports signature verification using PKC (Public Key Cryptography) or HMAC algorithms.
PKC JSON Web Token Key Sets (JWKS) can contain public RSA and EC keys. HMAC JWKS or an HMAC UTF-8 JWK contain secret keys. JWT issuers typically rotate PKC JWKS more frequently (such as daily), because RSA and EC public keys are designed to be easier to distribute than secret keys like HMAC.
JWT realms load a PKC JWKS and an HMAC JWKS or HMAC UTF-8 JWK at startup. JWT realms can also reload PKC JWKS contents at runtime; a reload is triggered by signature validation failures.
HMAC JWKS or HMAC UTF-8 JWK reloading is not supported at this time.
Load failures, parse errors, and configuration errors prevent a node from starting (and restarting). However, runtime PKC reload errors and recoveries are handled gracefully.
All other JWT realm validations are checked before a signature failure can trigger a PKC JWKS reload. If multiple JWT authentication signature failures occur simultaneously with a single Elasticsearch node, reloads are combined to reduce the reloads that are sent externally.
Separate reload requests cannot be combined if JWT signature failures trigger:
- PKC JWKS reloads in different Elasticsearch nodes
- PKC JWKS reloads in the same Elasticsearch node at different times
Enabling client authentication (client_authentication.type
) is strongly
recommended. Only trusted client applications and realm-specific JWT users can
trigger PKC reload attempts. Additionally, configuring the following
JWT security settings is recommended:
-
allowed_audiences
-
allowed_clock_skew
-
allowed_issuer
-
allowed_signature_algorithms
Authorizing to the JWT realm with an HMAC UTF-8 key
editThe following settings are for a JWT issuer, Elasticsearch, and a client of Elasticsearch. The example HMAC key is in an OIDC format that’s compatible with HMAC. The key bytes are the UTF-8 encoding of the UNICODE characters.
HMAC UTF-8 keys need to be longer than HMAC random byte keys to achieve the same key strength.
JWT issuer
editThe following values are for the bespoke JWT issuer.
Issuer: iss8 Audiences: aud8 Algorithms: HS256 HMAC UTF-8: hmac-oidc-key-string-for-hs256-algorithm
JWT realm settings
editTo define a JWT realm, add the following realm settings to elasticsearch.yml
.
xpack.security.authc.realms.jwt.jwt8.order: 8 xpack.security.authc.realms.jwt.jwt8.allowed_issuer: iss8 xpack.security.authc.realms.jwt.jwt8.allowed_audiences: [aud8] xpack.security.authc.realms.jwt.jwt8.allowed_signature_algorithms: [HS256] xpack.security.authc.realms.jwt.jwt8.claims.principal: sub xpack.security.authc.realms.jwt.jwt8.client_authentication.type: shared_secret
JWT realm secure settings
editAfter defining the realm settings, use the
elasticsearch-keystore
tool to add the
following secure settings to the Elasticsearch keystore. In Elastic Cloud, you define settings
for the Elasticsearch keystore under Security in your deployment.
xpack.security.authc.realms.jwt.jwt8.hmac_key: hmac-oidc-key-string-for-hs256-algorithm xpack.security.authc.realms.jwt.jwt8.client_authentication.shared_secret: client-shared-secret-string
JWT realm role mapping rule
editThe following request creates role mappings for Elasticsearch in the jwt8
realm for
the user principalname1
:
PUT /_security/role_mapping/jwt8_users?refresh=true { "roles" : [ "user" ], "rules" : { "all" : [ { "field": { "realm.name": "jwt8" } }, { "field": { "username": "principalname1" } } ] }, "enabled": true }
Request headers
editThe following header settings are for an Elasticsearch client.
Authorization: Bearer eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJpc3MiOiJpc3M4IiwiYXVkIjoiYXVkOCIsInN1YiI6InNlY3VyaXR5X3Rlc3RfdXNlciIsImV4cCI6NDA3MDkwODgwMCwiaWF0Ijo5NDY2ODQ4MDB9.UnnFmsoFKfNmKMsVoDQmKI_3-j95PCaKdgqqau3jPMY ES-Client-Authentication: SharedSecret client-shared-secret-string
You can use this header in a curl
request to make an authenticated call to
Elasticsearch. Both the bearer token and the client authorization token must be
specified as separate headers with the -H
option:
curl -s -X GET -H "Authorization: Bearer eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJpc3MiOiJpc3M4IiwiYXVkIjoiYXVkOCIsInN1YiI6InNlY3VyaXR5X3Rlc3RfdXNlciIsImV4cCI6NDA3MDkwODgwMCwiaWF0Ijo5NDY2ODQ4MDB9.UnnFmsoFKfNmKMsVoDQmKI_3-j95PCaKdgqqau3jPMY" -H "ES-Client-Authentication: SharedSecret client-shared-secret-string" https://localhost:9200/_security/_authenticate
If you used role mapping in the JWT realm, the response includes the user’s
username
, their roles
, metadata about the user, and the details about the
JWT realm itself.
{"username":"user2","roles":["jwt_role1"],"full_name":null,"email":"user2@something.example.com", "metadata":{"jwt_claim_email":"user2@something.example.com","jwt_claim_aud":["es01","es02","es03"], "jwt_claim_sub":"user2","jwt_claim_iss":"my-issuer"},"enabled":true,"authentication_realm": {"name":"jwt2","type":"jwt"},"lookup_realm":{"name":"jwt2","type":"jwt"},"authentication_type":"realm"} %
On this page
- JWT uses OIDC workflows
- Configure Elasticsearch to use a JWT realm
- JWT encoding and validation
- Header claims
- Payload claims
- OIDC payload claims
- Elasticsearch settings for consuming OIDC claims
- JWT realm authorization
- Authorizing with the role mapping API
- Delegating JWT authorization to another realm
- Applying the
run_as
privilege to JWT realm users - PKC JWKS reloading
- Authorizing to the JWT realm with an HMAC UTF-8 key
- JWT issuer
- JWT realm settings
- JWT realm secure settings
- JWT realm role mapping rule
- Request headers