GithubHelp home page GithubHelp logo

jwks-rsa-java's Introduction

jwks-rsa

CircleCI Maven Central FOSSA Status

Install

Maven

<dependency>
    <groupId>com.auth0</groupId>
    <artifactId>jwks-rsa</artifactId>
    <version>0.21.1</version>
</dependency>

Gradle

implementation 'com.auth0:jwks-rsa:0.21.1'

Usage

The JSON Web Tokens you get from the Authorization Server include a key id header parameter ("kid"), used to uniquely identify the Key used to sign the token.

i.e.: Given the following JWT:

eyJ0eXAiOiJKV1QiLCJhbGciOiJSUzI1NiIsImtpZCI6IlJrSTVNakk1T1VZNU9EYzFOMFE0UXpNME9VWXpOa1ZHTVRKRE9VRXpRa0ZDT1RVM05qRTJSZyJ9.eyJpc3MiOiJodHRwczovL3NhbmRyaW5vLmF1dGgwLmNvbS8iLCJzdWIiOiJhdXRoMHw1NjMyNTAxZjQ2OGYwZjE3NTZmNGNhYjAiLCJhdWQiOiJQN2JhQnRTc3JmQlhPY3A5bHlsMUZEZVh0ZmFKUzRyViIsImV4cCI6MTQ2ODk2NDkyNiwiaWF0IjoxNDY4OTI4OTI2fQ.NaNeRSDCNu522u4hcVhV65plQOiGPStgSzVW4vR0liZYQBlZ_3OKqCmHXsu28NwVHW7_KfVgOz4m3BK6eMDZk50dAKf9LQzHhiG8acZLzm5bNMU3iobSAJdRhweRht544ZJkzJ-scS1fyI4gaPS5aD3SaLRYWR0Xsb6N1HU86trnbn-XSYSspNqzIUeJjduEpPwC53V8E2r1WZXbqEHwM9_BGEeNTQ8X9NqCUvbQtnylgYR3mfJRL14JsCWNFmmamgNNHAI0uAJo84mu_03I25eVuCK0VYStLPd0XFEyMVFpk48Bg9KNWLMZ7OUGTB_uv_1u19wKYtqeTbt9m1YcPMQ

Decode it using any JWT library or tool like jwt.io and extract the kid parameter from the Header claims.

{
  "typ": "JWT",
  "alg": "RS256",
  "kid": "RkI5MjI5OUY5ODc1N0Q4QzM0OUYzNkVGMTJDOUEzQkFCOTU3NjE2Rg"
}

Use this kid on any of the JwkProviders enumerated below to obtain the signing key provided by the JWKS endpoint you've configured.

UrlJwkProvider

UrlJwkProvider fetches the jwk from /.well-known/jwks.json of the supplied domain issuer and returns a Jwk if the kid matches one of the registered keys.

JwkProvider provider = new UrlJwkProvider("https://samples.auth0.com/");
Jwk jwk = provider.get("{kid of the signing key}"); //throws Exception when not found or can't get one

Also it can load jwks.json file from any given Url (even to a local file in your filesystem).

JwkProvider provider = new UrlJwkProvider(new URL("https://samples.auth0.com/"));
Jwk jwk = provider.get("{kid of the signing key}"); //throws Exception when not found or can't get one

GuavaCachedJwkProvider

GuavaCachedJwkProvider cache the jwk in a LRU in memory cache, if the jwk is not found in the cache it will ask another provider for it and store it's result in the cache.

By default it stores 5 keys for 10 minutes, but these values can be changed.

JwkProvider http = new UrlJwkProvider("https://samples.auth0.com/");
JwkProvider provider = new GuavaCachedJwkProvider(http);
Jwk jwk = provider.get("{kid of the signing key}"); //throws Exception when not found or can't get one

RateLimitJwkProvider

RateLimitJwkProvider will limit the amounts of different signing keys to get in a given time frame.

By default the rate is limited to 10 different keys per minute but these values can be changed.

JwkProvider url = new UrlJwkProvider("https://samples.auth0.com/");
Bucket bucket = new Bucket(10, 1, TimeUnit.MINUTES);
JwkProvider provider = new RateLimitJwkProvider(url, bucket);
Jwk jwk = provider.get("{kid of the signing key}"); //throws Exception when not found or can't get one

JwkProviderBuilder

To create a provider for domain https://samples.auth0.com with cache and rate limit:

JwkProvider provider = new JwkProviderBuilder("https://samples.auth0.com/")
    .build();
Jwk jwk = provider.get("{kid of the signing key}"); //throws Exception when not found or can't get one

and specifying cache and rate limit attributes:

JwkProvider provider = new JwkProviderBuilder("https://samples.auth0.com/")
    .cached(10, 24, TimeUnit.HOURS)
    .rateLimited(10, 1, TimeUnit.MINUTES)
    .build();
Jwk jwk = provider.get("{kid of the signing key}"); //throws Exception when not found or can't get one

Error handling

There are certain scenarios in which this library can fail. Read below to understand what to expect and how to handle the errors.

Missing JSON Web Key

This error may arise when the hosted JSON Web Key set (JWKS) file doesn't represent a valid set of keys, or is empty. They are raised as a SigningKeyNotFoundException. The cause would need to be inspected in order to understand the specific failure reason.

Network error

There's a special case for Network errors. These errors represent timeouts, invalid URLs, or a faulty internet connection. They may occur when fetching the keys from the given URL. They are raised as a NetworkException instance.

If you need to detect this scenario, make sure to check it before the catch of SigningKeyNotFoundException.

try {
    // ...
} catch (NetworkException e) {
    // Network error
} catch (SigningKeyNotFoundException e) {
    // Key is invalid or not found
}

Unsupported JSON Web Key

When the received key is not of a supported type, or the attribute values representing it are wrong, an InvalidPublicKeyException will be raised. The following key types are supported:

  • RSA
  • Elliptic Curve
    • P-256
    • P-384
    • P-521

Rate limits

When using a rate-limited provider, a RateLimitReachedException error might be raised when the limit is breached. The instance can help determine how long to wait until the next call would be available.

try {
    // ...
} catch (RateLimitReachedException e) {
    long waitTime = e.getAvailableIn()
    // wait until available
}

What is Auth0?

Auth0 helps you to:

  • Add authentication with multiple authentication sources, either social like Google, Facebook, Microsoft Account, LinkedIn, GitHub, Twitter, Box, Salesforce, amont others, or enterprise identity systems like Windows Azure AD, Google Apps, Active Directory, ADFS or any SAML Identity Provider.
  • Add authentication through more traditional username/password databases.
  • Add support for linking different user accounts with the same user.
  • Support for generating signed Json Web Tokens to call your APIs and flow the user identity securely.
  • Analytics of how, when and where users are logging in.
  • Pull data from other sources and add it to the user profile, through JavaScript rules.

Create a free Auth0 Account

  1. Go to Auth0 and click Sign Up.
  2. Use Google, GitHub or Microsoft Account to login.

Issue Reporting

If you have found a bug or if you have a feature request, please report them at this repository issues section. Please do not report security vulnerabilities on the public GitHub issue tracker. The Responsible Disclosure Program details the procedure for disclosing security issues.

Author

Auth0

License

This project is licensed under the MIT license. See the LICENSE file for more info.

FOSSA Status

jwks-rsa-java's People

Contributors

beckr avatar colin-b avatar dafortune avatar damieng avatar darthvalinor avatar evansims avatar foobert avatar fossabot avatar ghostd avatar golszewski86 avatar hzalaz avatar jaxsun avatar jesseestum avatar jimmyjames avatar josephwitthuhntr avatar joshcanhelp avatar jsalinaspolo avatar kampka avatar lbalmaceda avatar luisrudge avatar nvinuesa avatar pauldaviesc avatar pevers avatar poovamraj avatar ryber avatar saltukalakus avatar skjolber avatar snyk-bot avatar w10t avatar xakepsdk avatar

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.