dsferruzza / actix-web-middleware-keycloak-auth Goto Github PK
View Code? Open in Web Editor NEWA middleware for Actix Web that handles authentication with a JWT emitted by Keycloak
License: MIT License
A middleware for Actix Web that handles authentication with a JWT emitted by Keycloak
License: MIT License
This is perhaps more of a question than an issue with this crate, but forgive me I am not well versed in rust or backend OAuth.
When accessing a protected endpoint, I am getting the error:
Error while decoding JWT token (InvalidSignature)
Steps to reproduce:
Set up keycloak, with a custom realm. In the custom realm, there is an admin user, who has several custom roles associated with it.
In code, follow your example, but get the public key dynamically:
// within fn main():
// Get the
let keycloak_realm = reqwest::get("http://localhost:9220/realms/custom_realm")
.await?
.json::<KeycloakRealm>()
.await;
match keycloak_realm {
Ok(realm) => {
// realm.public_key is `MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEA1GFEiRT0DRkUmOg/HfjJRpEqgcAI3JY4krdSMF7+I1Qo0mKXBpRow3QkIEKqc4mPX3NEb2xVXVMkmHk+6+ykqg5cqyV4S2w+e9lQy2nQSqklp3u5Jlu7YsiTe26Xxmqn761H4O3VvdnufDt4Nhvl/yqc45EeyIC+WWDaKk68eG+/KqEumme3oAbddFtt9oAIdL2EGJJinO7GcckcVawuG0tN9Di5v6hoV8U0g9Mdjf3ZBXnS6vNG5nCacOTaNCdGHEkV97yzbB60Gh0YAv4cwGCZrMDzCAfMfBA5kWwTaChL5i4hO55YXPG4QveYq55xz2BMhdNUpyws7e0w2m0VCwIDAQAB`
// confirmed this as RSA-OAEP in the keycloak UI
let formatted = format!(
"-----BEGIN RSA PUBLIC KEY-----\n{}\n-----END RSA PUBLIC KEY-----",
&realm.public_key
);
let keycloak_auth = KeycloakAuth::default_with_pk(
DecodingKey::from_rsa_pem(formatted.as_bytes()).unwrap(),
);
HttpServer::new(move || {
let cors = Cors::default();
let mut app = App::new()
.app_data(app_state.clone())
.app_data(reload_handle.clone())
.app_data(websocket_server.clone())
.app_data(tracker.clone())
.wrap(cors)
app = app
.service(
web::scope("/v1/private")
// not sure why I have to clone this, if I don't, I get the error:
// cannot move out of `keycloak_auth`, a captured variable in an `Fn` closure
.wrap(keycloak_auth.clone())
.route(
"",
web::get().to(|| async { HttpResponse::Ok().body("Private") }),
),
)
app
})
.bind((BIND_ADDRESS, BIND_PORT))?
.run()
.await?;
}
Err(error) => {
// Handle error stuff
}
}
All of this works, and the server is running. If I call the /private
route with no token, I correctly get a 401 no auth error.
When I call the api to get the user, I get the token. Token looks something like:
eyJhbGciOiJSUzI1NiIsInR5cCIgOiAiSldUIiwia2lkIiA6ICJ1QUlqZTNBUzM0d25Bblk4YmVGM1Z0Ulo1TWlJdzQycFB6c1FfV3lEVUNFIn0.eyJleHAiOjE3MDI5MTczNzIsImlhdCI6MTcwMjkxNzA3MiwiYXV0aF90aW1lIjoxNzAyOTE2NTkwLCJqdGkiOiI2MGM1ZGQ5MC03MmVkLTQyNjYtYWRiZi03Yjc5NzFjMjM5NjQiLCJpc3MiOiJodHRwOi8vbG9jYWxob3N0OjkyMjAvcmVhbG1zL3N0YXRoZXJvcyIsImF1ZCI6ImFjY291bnQiLCJzdWIiOiI2NjBmM2IyMy1hMjBhLTRhNzctYjUxYy1hMGU4YzRjNjcyMTAiLCJ0eXAiOiJCZWFyZXIiLCJhenAiOiJyYXBjb24iLCJzZXNzaW9uX3N0YXRlIjoiZWM3MGY1MGYtNjZhMi00Njk4LTg2Y2YtYmJkMzA1NTAxODlmIiwiYWNyIjoiMSIsImFsbG93ZWQtb3JpZ2lucyI6WyIqIl0sInJlYWxtX2FjY2VzcyI6eyJyb2xlcyI6WyJkZWZhdWx0LXJvbGVzLXN0YXRoZXJvcyIsIlJPTEVfUkFQQ09OX0FETUlOIiwib2ZmbGluZV9hY2Nlc3MiLCJ1bWFfYXV0aG9yaXphdGlvbiJdfSwicmVzb3VyY2VfYWNjZXNzIjp7ImFjY291bnQiOnsicm9sZXMiOlsibWFuYWdlLWFjY291bnQiLCJtYW5hZ2UtYWNjb3VudC1saW5rcyIsInZpZXctcHJvZmlsZSJdfX0sInNjb3BlIjoib3BlbmlkIGVtYWlsIHByb2ZpbGUiLCJzaWQiOiJlYzcwZjUwZi02NmEyLTQ2OTgtODZjZi1iYmQzMDU1MDE4OWYiLCJlbWFpbF92ZXJpZmllZCI6ZmFsc2UsInByZWZlcnJlZF91c2VybmFtZSI6ImFkbWluIn0.m0BpSB-ZZtnHP9H07AquMQMDSxKwE5vKCECdcb9FM98sxvSB_XXt59mcYL-gq9OKVYiBFPZrxlUdqssEPS_gNCdbPj-Drd93xLH59i07olz5Sin1p9hyya6JwptdBdL1pRNhGX9atwbyEmxi6W0WNcM2oqsM9mDY5HkGJDec9mF7n22uI2vnlvWY1E845CHVM8TWIeOlsMpKtnoY6qV0hS12alm_X6GKs1Cug1cMRCURQ_LDjKkUVn1HObgHV2vLcDk4PhyiB7nY-JZZJBNwB5Kcp2mXXqxjfADMZ5GekAoqdhMmEcCd8QwbRIfHCLD5g3bYNMOTR4VrFzBZGSpIVg
If you pop that into https://jwt.io/, it shows as signature verified for RS256.
In postman, I make a request to /v1/private
with header Authorization: Bearer <token>
, I get the error Error while decoding JWT token (InvalidSignature)
. I took at look at the other issue: #2, but it seems the problem there was already solved. I dug around stack overflow a bit as well for this issue, but since my JWT seems valid, I'm not sure what the issue might be.
This is probably not a bug with this crate? But what am I doing wrong in my setup? Am I passing the public key incorrectly? Am I making some wrong assumptions somewhere here?
On latest master, with latest nightly rustc.
error[E0599]: no method named `wrap_api` found for struct `App` in the current scope
--> examples/paperclip.rs:73:14
|
73 | .wrap_api()
| ^^^^^^^^ method not found in `App<impl ServiceFactory<ServiceRequest, Response = ServiceResponse<middleware::logger::StreamLog<AnyBody>>, Error = actix_web::Error, Config = (), InitError = ()>, middleware::logger::StreamLog<AnyBody>>`
Thanks for this crate, this seems to be exactly what I'm looking for!
Now, I'll be even happier if I can find an example with the full flow:
http://example.com/private
;http://example.com/private
.I would just like to be updated when this happens :)
Hello,
The token is not correctly decoded when there is more than 2 resource_access in addition to the default one in the keycloak token.
Steps to reproduce
Api part:
Implement like in the library example.
Keycloak part:
Create a realm on keycloak.
Create a admin role and an user associate to it (admin-user). Create a 2nd role (member) and associate it to a new user (member-user).
Create a keycloak client.
Create 2 role in the client: client-admin and client-member
Go to the admin-user and go to role-mapping. In the client-role select, pick the client you juste created and assign the client-admin role.
Go to the member-user and go to role-mapping. In the client-role select, pick the client you juste created and assign the client-member role.
Postman part:
Get the token by calling the keycloak api (by user) and make a API call with this token.
Current behaviour (bug)
Error while decoding JWT token (JSON error: invalid type: sequence, expected a string at line 1 column 146)
Expected behaviour (correct)
The token should be correctly decoded.
Relevant logs and/or media (optional)
[2020-12-11T15:19:39Z DEBUG actix_web_middleware_keycloak_auth] Bearer token was extracted from request headers [2020-12-11T15:19:39Z DEBUG actix_web_middleware_keycloak_auth] JWT header was decoded [2020-12-11T15:19:39Z DEBUG actix_web_middleware_keycloak_auth] JWT is using RS256 algorithm [2020-12-11T15:19:39Z DEBUG actix_web_middleware_keycloak_auth] Error while decoding JWT token (JSON error: invalid type: sequence, expected a string at line 1 column 146) [2020-12-11T15:19:39Z INFO actix_web::middleware::logger] 127.0.0.1:57949 "GET /private/users/1 HTTP/1.1" 401 107 "-" "PostmanRuntime/7.26.8" 0.000597
Working with one ressource_acces
Not working if there is more than 2 ressource_acces
Reported by
Gaëtan Fauconnier
Thank you for taking the time to write this library!
What are your thoughts on making the OID Public Key optional for JWT signature verification-- pulling from the keycloak API at runtime instead?
For instance, the following response comes from the realm URL:
http://localhost:8080/auth/realms/master
{
"realm": "master",
"public_key": "MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEArKUw6I2pf8aHOTRgHpH2QXKACNUXN9J7eLQvXAVRy4h/BaTx7ooACsRtftyaOxJQ4PvNqDevpcaIgZY1EWOeNSQkS2WoJws/IyF7fZ+En+2IQwfq2mBqQX9j6alJVmSsoovRyDpbZo33HYV1vqAKo08unBxGXbPx4hMXTlJcmF1DYQJKRuLfL6OPg1nlhZG4QhRgZR0PvDCvqXfIRPcKaS/IC6K6NiOl/+uxbSYeV9CeCSRHIreP0REq2mbmdXMOljZGqjKHOXsLFmwG7V9HeSyWb7k1ZeS00eMZS2k5CI3Jci1UP2NfyCDLgEyq3anJZQD7/GIERvEK4SSJt/wHGQIDAQAB",
"token-service": "http://localhost:8080/auth/realms/master/protocol/openid-connect",
"account-service": "http://localhost:8080/auth/realms/master/account",
"tokens-not-before": 0
}
In this case, we could pull public_key
from the response automatically, rather than requiring its presence when constructing the KeycloakAuth
struct.
error[E0437]: type `Config` is not a member of trait `FromRequest`
--> /home/erlend/.cargo/registry/src/github.com-1ecc6299db9ec823/actix-web-middleware-keycloak-auth-0.4.0-beta.1/src/extractors.rs:53:5
|
53 | type Config = EmptyConfig;
| ^^^^^^^^^^^^^^^^^^^^^^^^^^ not a member of trait `FromRequest`
error[E0437]: type `Config` is not a member of trait `FromRequest`
--> /home/erlend/.cargo/registry/src/github.com-1ecc6299db9ec823/actix-web-middleware-keycloak-auth-0.4.0-beta.1/src/extractors.rs:111:5
|
111 | type Config = EmptyConfig;
| ^^^^^^^^^^^^^^^^^^^^^^^^^^ not a member of trait `FromRequest`
error: aborting due to 2 previous errors
Hey there,
thanks for providing this awesome crate. 👍
Are there any plans to support groups?
BR Simon
I was going to add something like this in a PR
impl<F> PassthroughPolicy for F
where F: Fn(&AuthError) -> PassthroughAction + Clone
{
fn policy(&self, error: &AuthError) -> PassthroughAction {
self(error)
}
}
but couldn't (immediately) figure out some compiler errors I got when trying to use my changes in an existing project. I previous used v0.4.0-beta.2
, worked from that commit, and now got error:
error[E0599]: no variant or associated item named `from_message` found for enum `AnyBody` in the current scope
--> /home/erlend/.cargo/git/checkouts/actix-web-prom-af77977b77662c26/fc05d50/src/lib.rs:519:22
|
519 | AnyBody::from_message(StreamLog {
| ^^^^^^^^^^^^ variant or associated item not found in `AnyBody<_>`
A declarative, efficient, and flexible JavaScript library for building user interfaces.
🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
An Open Source Machine Learning Framework for Everyone
The Web framework for perfectionists with deadlines.
A PHP framework for web artisans
Bring data to life with SVG, Canvas and HTML. 📊📈🎉
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
Some thing interesting about web. New door for the world.
A server is a program made to process requests and deliver data to clients.
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
Some thing interesting about visualization, use data art
Some thing interesting about game, make everyone happy.
We are working to build community through open source technology. NB: members must have two-factor auth.
Open source projects and samples from Microsoft.
Google ❤️ Open Source for everyone.
Alibaba Open Source for everyone
Data-Driven Documents codes.
China tencent open source team.