1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
// actix-web-middleware-keycloak-auth
//
// Copyright: 2020, David Sferruzza
// License: MIT

//! # actix-web-middleware-keycloak-auth
//! A middleware for [Actix Web](https://actix.rs/) that handles authentication with a JWT emitted by [Keycloak](https://www.keycloak.org/).
//!
//! ## Setup middleware
//!
//! Setting up the middleware is done in 2 steps:
//! 1. creating a `KeycloakAuth` struct with the wanted configuration
//! 2. passing this struct to an Actix Web service `wrap()` method
//!
//! ```
//! use actix_web::{App, web, HttpResponse};
//! use actix_web_middleware_keycloak_auth::{KeycloakAuth, DecodingKey};
//!
//! # const KEYCLOAK_PK: &str = "-----BEGIN PUBLIC KEY-----\nMIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAnzyis1ZjfNB0bBgKFMSv\nvkTtwlvBsaJq7S5wA+kzeVOVpVWwkWdVha4s38XM/pa/yr47av7+z3VTmvDRyAHc\naT92whREFpLv9cj5lTeJSibyr/Mrm/YtjCZVWgaOYIhwrXwKLqPr/11inWsAkfIy\ntvHWTxZYEcXLgAXFuUuaS3uF9gEiNQwzGTU1v0FqkqTBr4B8nW3HCN47XUu0t8Y0\ne+lf4s4OxQawWD79J9/5d3Ry0vbV3Am1FtGJiJvOwRsIfVChDpYStTcHTCMqtvWb\nV6L11BWkpzGXSW4Hv43qa+GSYOD2QU68Mb59oSk2OB+BtOLpJofmbGEGgvmwyCI9\nMwIDAQAB\n-----END PUBLIC KEY-----";
//! // const KEYCLOAK_PK: &str = "..."; // You should get this from configuration
//!
//! // Initialize middleware configuration
//! let keycloak_auth = KeycloakAuth {
//!     detailed_responses: true,
//!     keycloak_oid_public_key: DecodingKey::from_rsa_pem(KEYCLOAK_PK.as_bytes()).unwrap(),
//!     required_roles: vec![],
//! };
//!
//! App::new()
//!     .service(
//!         web::scope("/private")
//!             .wrap(keycloak_auth) // Every route in the service will leverage the middleware
//!             .route("", web::get().to(|| HttpResponse::Ok().body("Private"))),
//!     )
//!     .service(web::resource("/").to(|| HttpResponse::Ok().body("Hello World")));
//! ```
//!
//! HTTP requests to `GET /private` will need to have a `Authorization` header containing `Bearer [JWT]` where `[JWT]` is a valid JWT that was signed by the private key associated with the public key provided when the middleware was initialized.
//!
//! ## Require roles
//!
//! You can require one or several specific roles to be included in JWT.
//! If they are not provided, the middleware will return a 403 error.
//!
//! ```
//! # use actix_web_middleware_keycloak_auth::{KeycloakAuth, DecodingKey, Role};
//! # const KEYCLOAK_PK: &str = "-----BEGIN PUBLIC KEY-----\nMIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAnzyis1ZjfNB0bBgKFMSv\nvkTtwlvBsaJq7S5wA+kzeVOVpVWwkWdVha4s38XM/pa/yr47av7+z3VTmvDRyAHc\naT92whREFpLv9cj5lTeJSibyr/Mrm/YtjCZVWgaOYIhwrXwKLqPr/11inWsAkfIy\ntvHWTxZYEcXLgAXFuUuaS3uF9gEiNQwzGTU1v0FqkqTBr4B8nW3HCN47XUu0t8Y0\ne+lf4s4OxQawWD79J9/5d3Ry0vbV3Am1FtGJiJvOwRsIfVChDpYStTcHTCMqtvWb\nV6L11BWkpzGXSW4Hv43qa+GSYOD2QU68Mb59oSk2OB+BtOLpJofmbGEGgvmwyCI9\nMwIDAQAB\n-----END PUBLIC KEY-----";
//! let keycloak_auth = KeycloakAuth {
//!     detailed_responses: true,
//!     keycloak_oid_public_key: DecodingKey::from_rsa_pem(KEYCLOAK_PK.as_bytes()).unwrap(),
//!     required_roles: vec![
//!         Role::Realm { role: "admin".to_owned() }, // The "admin" realm role must be provided in the JWT
//!         Role::Client {
//!             client: "backoffice".to_owned(),
//!             role: "readonly".to_owned()
//!         }, // The "readonly" role of the "backoffice" client must be provided in the JWT
//!     ],
//! };
//! ```
//!
//! ## Use several authentication profiles
//!
//! It is possible to setup multiple authentication profiles if, for example, multiple groups of routes require different roles.
//!
//! ```
//! use actix_web::{App, web, HttpResponse};
//! use actix_web_middleware_keycloak_auth::{KeycloakAuth, DecodingKey, Role};
//!
//! # const KEYCLOAK_PK: &str = "-----BEGIN PUBLIC KEY-----\nMIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAnzyis1ZjfNB0bBgKFMSv\nvkTtwlvBsaJq7S5wA+kzeVOVpVWwkWdVha4s38XM/pa/yr47av7+z3VTmvDRyAHc\naT92whREFpLv9cj5lTeJSibyr/Mrm/YtjCZVWgaOYIhwrXwKLqPr/11inWsAkfIy\ntvHWTxZYEcXLgAXFuUuaS3uF9gEiNQwzGTU1v0FqkqTBr4B8nW3HCN47XUu0t8Y0\ne+lf4s4OxQawWD79J9/5d3Ry0vbV3Am1FtGJiJvOwRsIfVChDpYStTcHTCMqtvWb\nV6L11BWkpzGXSW4Hv43qa+GSYOD2QU68Mb59oSk2OB+BtOLpJofmbGEGgvmwyCI9\nMwIDAQAB\n-----END PUBLIC KEY-----";
//! // const KEYCLOAK_PK: &str = "..."; // You should get this from configuration
//!
//! // No role required
//! let keycloak_auth = KeycloakAuth {
//!     detailed_responses: true,
//!     keycloak_oid_public_key: DecodingKey::from_rsa_pem(KEYCLOAK_PK.as_bytes()).unwrap(),
//!     required_roles: vec![],
//! };
//!
//! // Admin realm role is required
//! let keycloak_auth_admin = KeycloakAuth {
//!     detailed_responses: true,
//!     keycloak_oid_public_key: DecodingKey::from_rsa_pem(KEYCLOAK_PK.as_bytes()).unwrap(),
//!     required_roles: vec![Role::Realm { role: "admin".to_owned() }],
//! };
//!
//! App::new()
//!     .service(
//!         web::scope("/private")
//!             .wrap(keycloak_auth) // User must be authenticated
//!             .route("", web::get().to(|| HttpResponse::Ok().body("Private"))),
//!     )
//!     .service(
//!         web::scope("/admin")
//!             .wrap(keycloak_auth_admin) // User must have the "admin" role
//!             .route("", web::get().to(|| HttpResponse::Ok().body("Admin"))),
//!     )
//!     .service(web::resource("/").to(|| HttpResponse::Ok().body("Hello World")));
//! ```
//!
//! ## Access claims in handlers
//!
//! When authentication is successful, the middleware will store the decoded claims so that they can be accessed from handlers.
//!
//! ```
//! use actix_web::web::ReqData;
//! use actix_web::{HttpResponse, Responder};
//! use actix_web_middleware_keycloak_auth::Claims;
//!
//! async fn private(claims: ReqData<Claims>) -> impl Responder {
//!     HttpResponse::Ok().body(format!("{:?}", &claims))
//! }
//! ```

// Force exposed items to be documented
#![deny(missing_docs)]

mod errors;
mod roles;

/// _(Re-exported from the `jsonwebtoken` crate)_
pub use jsonwebtoken::DecodingKey;

use actix_web::dev::{Service, ServiceRequest, ServiceResponse, Transform};
use actix_web::{Error, HttpMessage};
use chrono::{serde::ts_seconds, DateTime, Utc};
use futures_util::future::{ok, ready, Ready};
use jsonwebtoken::{decode, decode_header, Validation};
use log::{debug, trace};
use serde::{Deserialize, Serialize};
use std::collections::HashMap;
use std::future::Future;
use std::pin::Pin;
use std::task::{Context, Poll};
use uuid::Uuid;

use errors::AuthError;
use roles::check_roles;

/// Middleware configuration
#[derive(Debug, Clone)]
pub struct KeycloakAuth {
    /// If true, error responses will be more detailed to explain what went wrong
    pub detailed_responses: bool,
    /// Public key to use to verify JWT
    pub keycloak_oid_public_key: DecodingKey<'static>,
    /// List of Keycloak roles that must be included in JWT
    pub required_roles: Vec<Role>,
}

impl<S, B> Transform<S> for KeycloakAuth
where
    S: Service<Request = ServiceRequest, Response = ServiceResponse<B>, Error = Error>,
    S::Future: 'static,
    B: 'static,
{
    type Request = ServiceRequest;
    type Response = ServiceResponse<B>;
    type Error = Error;
    type InitError = ();
    type Transform = KeycloakAuthMiddleware<S>;
    type Future = Ready<Result<Self::Transform, Self::InitError>>;

    fn new_transform(&self, service: S) -> Self::Future {
        trace!("Initialize KeycloakAuthMiddleware");
        ok(KeycloakAuthMiddleware {
            service,
            detailed_responses: self.detailed_responses,
            keycloak_oid_public_key: self.keycloak_oid_public_key.clone(),
            required_roles: self.required_roles.clone(),
        })
    }
}

/// Internal middleware configuration
pub struct KeycloakAuthMiddleware<S> {
    service: S,
    detailed_responses: bool,
    keycloak_oid_public_key: DecodingKey<'static>,
    required_roles: Vec<Role>,
}

/// Claims that are extracted from JWT and can be accessed in handlers using a `ReqData<Claims>` parameter
#[derive(Debug, Clone, Deserialize, Serialize)]
pub struct Claims {
    /// Subject (usually, the user ID)
    pub sub: Uuid,
    /// Expiration date
    #[serde(with = "ts_seconds")]
    pub exp: DateTime<Utc>,
    /// Optional realm roles from Keycloak
    pub realm_access: Option<Access>,
    /// Optional client roles from Keycloak
    pub resource_access: Option<HashMap<String, Access>>,
    /// Issuer
    pub iss: String,
    /// Audience
    pub aud: Option<String>,
    /// Issuance date
    #[serde(with = "ts_seconds")]
    pub iat: DateTime<Utc>,
    /// ID of the JWT
    pub jti: Uuid,
    /// Authorized party
    pub azp: String,
}

impl Default for Claims {
    fn default() -> Self {
        use chrono::Duration;
        use std::ops::Add;

        Self {
            sub: Uuid::from_u128_le(0),
            exp: Utc::now().add(Duration::minutes(1)),
            realm_access: None,
            resource_access: None,
            iss: env!("CARGO_PKG_NAME").to_owned(),
            aud: Some("account".to_owned()),
            iat: Utc::now(),
            jti: Uuid::from_u128_le(22685491128062564230891640495451214097),
            azp: "".to_owned(),
        }
    }
}

impl Claims {
    /// Extract Keycloak roles
    pub fn roles(&self) -> Vec<Role> {
        let mut roles = self
            .realm_access
            .clone()
            .map(|ra| {
                ra.roles
                    .iter()
                    .map(|role| Role::Realm {
                        role: role.to_owned(),
                    })
                    .collect()
            })
            .unwrap_or_else(Vec::new);

        let mut client_roles = self
            .resource_access
            .clone()
            .map(|ra| {
                ra.iter()
                    .flat_map(|(client_name, r)| {
                        r.roles
                            .iter()
                            .map(|role| Role::Client {
                                client: client_name.to_owned(),
                                role: role.to_owned(),
                            })
                            .collect::<Vec<Role>>()
                    })
                    .collect()
            })
            .unwrap_or_else(Vec::new);

        roles.append(&mut client_roles);
        roles
    }
}

/// Access details
#[derive(Debug, Clone, Deserialize, Serialize)]
pub struct Access {
    /// Roles
    pub roles: Vec<String>,
}

/// A realm or client role
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum Role {
    /// A realm role
    Realm {
        /// Name of the role
        role: String,
    },
    /// A client role
    Client {
        /// Client ID
        client: String,
        /// Name of the role
        role: String,
    },
}

impl std::fmt::Display for Role {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            Self::Realm { role } => write!(f, "{}", role),
            Self::Client { client, role } => write!(f, "{}.{}", client, role),
        }
    }
}

impl<S, B> Service for KeycloakAuthMiddleware<S>
where
    S: Service<Request = ServiceRequest, Response = ServiceResponse<B>, Error = Error>,
    S::Future: 'static,
    B: 'static,
{
    type Request = ServiceRequest;
    type Response = ServiceResponse<B>;
    type Error = Error;
    #[allow(clippy::type_complexity)]
    type Future = Pin<Box<dyn Future<Output = Result<Self::Response, Self::Error>>>>;

    fn poll_ready(&mut self, cx: &mut Context<'_>) -> Poll<Result<(), Self::Error>> {
        self.service.poll_ready(cx)
    }

    fn call(&mut self, req: ServiceRequest) -> Self::Future {
        let auth_header = req.headers().get("Authorization");

        match auth_header {
            Some(auth_header_value) => {
                let auth_header_str = auth_header_value.to_str();
                match auth_header_str {
                    Ok(raw_token) => {
                        let token = raw_token.trim_start_matches("Bearer ");
                        debug!("Bearer token was extracted from request headers");

                        match decode_header(token) {
                            Ok(jwt_header) => {
                                debug!("JWT header was decoded");
                                debug!("JWT is using {:?} algorithm", &jwt_header.alg);

                                match decode::<Claims>(
                                    &token,
                                    &self.keycloak_oid_public_key,
                                    &Validation::new(jwt_header.alg),
                                ) {
                                    Ok(token) => {
                                        debug!("JWT was decoded");

                                        match check_roles(token, &self.required_roles) {
                                            Ok(token_data) => {
                                                debug!("JWT is valid; putting claims in ReqData");

                                                {
                                                    let mut extensions = req.extensions_mut();
                                                    extensions.insert(token_data.claims);
                                                }

                                                Box::pin(self.service.call(req))
                                            }
                                            Err(e) => {
                                                debug!("{}", &e);
                                                Box::pin(ready(Ok(req.into_response(
                                                    e.to_response(self.detailed_responses)
                                                        .into_body(),
                                                ))))
                                            }
                                        }
                                    }
                                    Err(e) => {
                                        let e = AuthError::DecodeError(e.to_string());
                                        debug!("{}", &e);
                                        Box::pin(ready(Ok(req.into_response(
                                            e.to_response(self.detailed_responses).into_body(),
                                        ))))
                                    }
                                }
                            }
                            Err(e) => {
                                let e = AuthError::InvalidJwt(e.to_string());
                                debug!("{}", &e);
                                Box::pin(ready(Ok(req.into_response(
                                    e.to_response(self.detailed_responses).into_body(),
                                ))))
                            }
                        }
                    }
                    Err(_) => {
                        let e = AuthError::InvalidAuthorizationHeader;
                        debug!("{}", &e);
                        Box::pin(ready(Ok(req.into_response(
                            e.to_response(self.detailed_responses).into_body(),
                        ))))
                    }
                }
            }
            None => {
                let e = AuthError::NoBearerToken;
                debug!("{}", &e);
                Box::pin(ready(Ok(req.into_response(
                    e.to_response(self.detailed_responses).into_body(),
                ))))
            }
        }
    }
}