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
use actix_web::{get, web, HttpRequest, HttpResponse, Scope};
extern crate jsonwebtoken as jwt;
use jwt::{encode, EncodingKey, Header};
use jwtk::PublicKeyToJwk;
use serde_json::json;
use url::Url;
use url_params_serializer::to_url_params;
use crate::{auth::ClaimsPrincipal, oauth2::OAuthManager};
#[derive(Debug, Serialize, Deserialize)]
struct Claims {
sub: String,
company: String,
exp: usize,
}
struct Oauth2Config {
private_key: jwtk::SomePrivateKey,
}
pub fn config() -> Scope {
let _ = std::fs::read("localhost.key").unwrap();
let k = jwtk::SomePrivateKey::from_pem(
&std::fs::read("localhost.key").unwrap(),
match std::env::var("RSA_ALGO").as_deref() {
Ok(alg) => jwtk::rsa::RsaAlgorithm::from_name(alg).unwrap(),
_ => jwtk::rsa::RsaAlgorithm::RS256,
},
)
.unwrap();
let oauth_config = web::Data::new(Oauth2Config {
private_key: k,
});
web::scope("/v2")
.app_data(oauth_config.clone())
.service(authorize_endpoint)
.service(token_endpoint)
.service(keys_endpoint)
.service(test_endpoint)
.service(crate::server::openid_connect::metadata)
}
#[get("/auth")]
async fn authorize_endpoint(
_auth_form: web::Form<crate::oauth2::auth::AuthRequest>,
auth_request_query: web::Query<crate::oauth2::auth::AuthRequest>,
_req: HttpRequest,
_config: web::Data<Oauth2Config>,
) -> HttpResponse {
let auth_request = auth_request_query.0.to_owned();
let mut auth_manager = OAuthManager::new();
let auth_result = auth_manager.authorize(&auth_request);
let mode = _req.headers().get("mode");
if mode != Option::None && mode.unwrap() == "debug" {
return match auth_result {
Ok(v) => HttpResponse::Ok().json(v),
Err(e) => HttpResponse::BadRequest().json(e),
};
}
let redirect_result = match auth_result {
Ok(v) => {
let callback_uri = v.callback_uri.to_owned();
Url::parse_with_params(callback_uri.unwrap().as_str(), to_url_params(v)).unwrap()
}
Err(e) => {
let url_params = to_url_params(e.to_owned());
let mut callback_uri = e.callback_uri.to_owned();
if e.callback_uri == Option::None {
let mut error_callback = String::from("");
error_callback.push_str(_req.connection_info().scheme());
error_callback.push_str("://");
error_callback.push_str(_req.connection_info().host());
error_callback.push_str("/error");
callback_uri = Some(error_callback);
}
Url::parse_with_params(callback_uri.unwrap().as_str(), url_params).unwrap()
}
};
HttpResponse::TemporaryRedirect()
.append_header(("Location", redirect_result.to_string()))
.finish()
}
#[get("/token")]
async fn token_endpoint(_req: HttpRequest, _config: web::Data<Oauth2Config>) -> HttpResponse {
let error = crate::oauth2::token::TokenErrorResponse::new();
HttpResponse::Ok()
.content_type("application/json")
.json(error)
}
#[get("/test")]
async fn test_endpoint(_req: HttpRequest, _config: web::Data<Oauth2Config>) -> HttpResponse {
let mut claims_principal = ClaimsPrincipal::new();
claims_principal.add_claim("role", json!("a"));
claims_principal.add_claim("role", json!("b"));
claims_principal.add_claim("role", json!("c"));
claims_principal.add_claim("iat", json!(10));
claims_principal.add_claim("expired", json!(false));
let token = encode(
&Header::default(),
&claims_principal.as_claims_map(),
&EncodingKey::from_secret("secret".as_ref()),
)
.unwrap();
HttpResponse::Ok().content_type("text/plain").body(token)
}
#[get("/keys")]
async fn keys_endpoint(_req: HttpRequest, config: web::Data<Oauth2Config>) -> HttpResponse {
let k_public_jwk = config.private_key.public_key_to_jwk().unwrap();
let jwks = jwtk::jwk::JwkSet {
keys: vec![k_public_jwk],
};
HttpResponse::Ok()
.content_type("application/json")
.json(jwks)
}