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:
- That the token is issued by Azure and is not tampered with
- That this token is issued for use in your application
- That the token is not expired
- That the token is not used before it’s valid
- That the token is not issued in the future
- That the algorithm in the token header is the same as we use*
- Note that we do NOT use the token header to set the algorithm for us, look at this article for more information on why that would be bad
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§
- Azure
Auth - AzureAuth is the what you’ll use to validate your token.
- Azure
JwtClaims - Azure
JwtHeader - Jwk