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
/*!
Huskarl provides tools for implementing secure `OAuth2` clients in rust.
This library provides a number of grant implementations, each of which is configured
with a set of parameters that define how the grant/workflow should progress.
The library also provides a caching layer for token responses; and a HTTP authorizer
that can be used to make authenticated requests to resource servers.
## Setup
1. Create a HTTP client instance (e.g. with `huskarl-reqwest`).
2. Get authorization server metadata (or OIDC discovery data) when appropriate (but not necessary).
3. Set up your client's authentication.
4. Create the grant, filling in its fields, and supplying the client authentication.
Once you have a grant, how exactly to use it depends on the grant. The simplest grants only
require the `exchange` call, which exchanges grant-specific parameters for a token at the token
endpoint.
Other grants act like workflows, with a set of steps required, which will also involve one
or more calls to the token endpoint.
## Grants provided in this crate:
- [`ClientCredentials`](grant::client_credentials::ClientCredentialsGrant)
Allows a client to exchange its own credentials in return for an access token.
- [`Refresh`](grant::refresh::RefreshGrant)
Allows a client which previously received a refresh token alongside an access token, to exchange
it in return for an access token.
- [`AuthorizationCode`](grant::authorization_code::AuthorizationCodeGrant)
Provides the ability for a client to send the interactive user a URL at which to authenticate;
a code from a successful authentication is returned to the client, which can exchange it in
return for an access token.
- [`DeviceAuthorization`](grant::device_authorization::DeviceAuthorizationGrant)
Enables a client to provide a code and/or URL to an interactive user, which they can use to
log in from another machine. They complete the requirements of login, and the authorization
server is notified that it can provide the corresponding access token to the client.
- [`TokenExchange`](grant::token_exchange::TokenExchangeGrant)
Allows the client to exchange an existing token for a new security token, supporting
impersonation and delegation use cases.
Further grants exist, could either be implemented for this library either in-crate, or can be
implemented by external crates. Examples include CIBA, JWT authorization, or provider-specific grants.
## Examples
### Client Credentials Grant
```rust
# use huskarl::prelude::*;
# use huskarl::core::http::HttpClient;
# use huskarl::core::secrets::{EnvVarSecret, encodings::StringEncoding};
# use huskarl::core::server_metadata::AuthorizationServerMetadata;
# use huskarl::grant::client_credentials::{ClientCredentialsGrant, ClientCredentialsGrantParameters};
# use huskarl::core::client_auth::ClientSecret;
#
# async fn example(http_client: impl HttpClient + 'static) {
# let issuer = "https://issuer";
# let client_id = "client_id";
# let client_secret = EnvVarSecret::new("CLIENT_SECRET", &StringEncoding).unwrap();
#
let metadata = AuthorizationServerMetadata::fetch()
.http_client(&http_client)
.issuer(issuer)
.call()
.await
.unwrap();
let grant = ClientCredentialsGrant::builder_from_metadata(&metadata)
.client_id(client_id)
.http_client(http_client)
.client_auth(ClientSecret::new(client_secret))
.build();
let token_response = grant
.exchange(
ClientCredentialsGrantParameters::builder()
.scopes(vec!["test"])
.build(),
)
.await
.unwrap();
println!(
"Access token: {}",
token_response.access_token().token().expose_secret()
);
# }
```
### Application state and error handling
Grants belong to the login path. For the request path, wrap a grant in a
token cache and an [`HttpAuthorizer`](authorizer::HttpAuthorizer) — workflow
types carry no type parameters, so they store directly in your application
state, and every operation returns the one concrete
[`Error`](core::Error) type, which embeds in your own error enum (hand-rolled
as below, or with `thiserror`'s `#[from]`).
Errors carry three stable signals, checked in this order:
[`is_retryable`](core::Error::is_retryable) means the failure is transient
and the same call may succeed later — back off and retry, do **not** re-run
the interactive flow; [`ReauthRequired`](core::ErrorKind::ReauthRequired)
means no token can be obtained automatically and the interactive flow must
run again; everything else is a genuine failure to log and surface.
```rust
# use huskarl::core::client_auth::NoAuth;
# use huskarl::core::http::HttpClient;
# use huskarl::grant::client_credentials::{ClientCredentialsGrant, ClientCredentialsGrantParameters};
use huskarl::{
authorizer::HttpAuthorizer,
cache::{InMemoryRefreshTokenStore, InMemoryTokenCache},
core::ErrorKind,
};
/// Plain types, no parameters: this struct names cleanly in app state.
struct App {
authorizer: HttpAuthorizer,
}
enum AppError {
/// Transient failure — retry the request later.
RetryLater(huskarl::core::Error),
/// The user must log in again.
LoginRequired,
/// Any other authorization failure.
Auth(huskarl::core::Error),
}
impl From<huskarl::core::Error> for AppError {
fn from(err: huskarl::core::Error) -> Self {
if err.is_retryable() {
AppError::RetryLater(err)
} else if err.kind() == ErrorKind::ReauthRequired {
AppError::LoginRequired
} else {
AppError::Auth(err)
}
}
}
# async fn example(http_client: impl HttpClient + 'static) -> Result<(), AppError> {
# let grant = ClientCredentialsGrant::builder()
# .client_id("client-id")
# .client_auth(NoAuth)
# .token_endpoint("https://as.example.com/token".parse()?)
# .http_client(http_client)
# .build();
// `grant` is any grant, built as in the example above.
let cache = InMemoryTokenCache::builder()
.grant(grant)
.grant_parameters(ClientCredentialsGrantParameters::builder().build())
.refresh_store(InMemoryRefreshTokenStore::default())
.build();
let app = App {
authorizer: HttpAuthorizer::builder().cache(cache).build(),
};
// Exchanges or refreshes as needed through the grant's own HTTP client;
// `?` lands in the app's error enum, with re-login distinguished.
let uri: http::Uri = "https://api.example.com/v1".parse().unwrap();
let headers = app
.authorizer
.get_headers(&http::Method::GET, &uri)
.await?;
// Send the request with your HTTP client, then feed the response headers
// back so DPoP nonce rotation and rejected tokens are tracked — see the
// authorizer module docs for the full request loop.
# let response_headers = http::HeaderMap::new();
app.authorizer.process_response(&uri, &response_headers);
# drop(headers);
# Ok(())
# }
```
To survive restarts, persist only the refresh token by handing the cache a
custom [`RefreshTokenStore`](cache::RefreshTokenStore) (keychain- or
disk-backed); on startup the cache refreshes into a fresh access token. For
handing a freshly-obtained token from the login path to a running cache, use
[`prime`](cache::TokenCache::prime).
*/
use Arc;
pub use huskarl_core as core;
/// A type-erased wrapper around a [`core::crypto::verifier::JwsVerifierPlatform`] for use as a feature-gated default.
;
/// The default JWS verifier platform for native platforms.
/// The default JWS verifier platform for WebAssembly/WebCrypto platforms.