Crate azure_jwt

source ·
Expand description

Authenticates Azure JWT tokens.

This library will fetch public keys from Microsoft and use those keys to validate the authenticity of a token you provide. It defaults to validating and mapping Azure Id tokens for you out of the box, but should work with other tokens as well if you use a custom validator.

It uses request with the “blocking” feature to fetch metadata and public keys, but used correctly it will only update these once a day.

Dafault validation

There are mainly six conditions a well formed token will need to meet to be validated:

  1. That the token is issued by Azure and is not tampered with
  2. That this token is issued for use in your application
  3. That the token is not expired
  4. That the token is not used before it’s valid
  5. That the token is not issued in the future
  6. That the algorithm in the token header is the same as we use*

The validation will Error on a failed validation providing more granularity for library users to find out why the token was rejected.

If the token is invalid it will return an Error instead of a boolean. The main reason for this is easier logging of what type of test it failed.

You also have a validate_custom mathod which gives you full control over the mapping of the token fields and more control over the validation.

Security

You will need a private app_id created by Azure for your application to be able to veriify that the token is created for your application (and not anyone with a valid Azure token can log in) and you will need to authenticate that the user has the right access to your system.

For more information, see this artice: https://docs.microsoft.com/en-us/azure/active-directory/develop/id-tokens

Example

use azure_jwt::*;


    let mut az_auth = AzureAuth::new("6e74172b-be56-4843-9ff4-e66a39bb12e3").unwrap();

    let decoded_token = az_auth.validate_token(&token).expect("validated");
    assert_eq!(decoded_token.claims.preferred_username, Some("abeli@microsoft.com".to_string()));

Example in webserver

struct AppState {
    azure_auth: auth::AzureAuth,
}

pub fn start_web_server(port: &str) -> Result<(), Error> {

    // since this calls windows api, wrap in Arc<Mutex<_>> and share the validator
    let app_state = Arc::new(Mutex::new(AppState {
        azure_auth: auth::AzureAuth::new("32166c25-5e31-4cfc-a29b-04d0dfdb019a").unwrap(),
    }));
    println!("Starting web server on: http://localhost:8000");

    server::new(move || app(app_state.clone())).bind(port)?.run();

    Ok(())
}

Structs

Enums