-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathaad-leihs-authenticator
executable file
·315 lines (224 loc) · 8.95 KB
/
aad-leihs-authenticator
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
#!/usr/bin/env ruby
require 'active_support/all'
require 'cgi'
require 'digest'
require 'jwt'
require 'logger'
require 'optparse'
require 'ostruct'
require 'pathname'
require 'rest-client'
require 'securerandom'
require 'set'
require 'sinatra/base'
require 'yaml'
$logger = Logger.new(STDOUT)
$logger.level = Logger::WARN
# DEV stuff only
# require 'pry'
# require 'rerun'
# require 'pry-remote'
################################################################################
### options and config #########################################################
################################################################################
options = OpenStruct.new
# options.config_file = Pathname.new("dev/config.yml")
OptionParser.new do |opts|
opts.banner = "Usage: phzh-ms-open-id-auth-system.rb [options]"
opts.on("-c", "--config-file [PATH]", String, "Configuration file") do |cf|
options.config_file = Pathname.new cf
end
end.parse!
$config = {
port: 3434
}.with_indifferent_access.deep_merge(
YAML.load_file(options.config_file).with_indifferent_access)
################################################################################
### a custom error which message will appear in the reponse ####################
################################################################################
class AuthenticationError < StandardError
def initialize(msg="Unclassified Authentication Error. " \
+ "Please contact your leihs administrator.")
super
end
end
################################################################################
### the web app ################################################################
################################################################################
class AuthenticatorApp < Sinatra::Base
set :environment, :production
def initialize()
$email_attribute = $config[:email_attribute].presence \
|| (raise 'email_attribute must be present in config')
$tenant = $config[:tenant].presence \
|| (raise 'tenant must be present in config')
$external_base_url = $config[:external_base_url].presence \
|| (raise 'external_base_url must be present in config')
$client_id = $config[:client_id].presence \
|| (raise 'client_id must be present in config')
$private_key = OpenSSL::PKey.read(
$config[:private_key].presence \
|| (raise 'private_key must be present in config'))
$public_key = OpenSSL::PKey.read(
$config[:public_key].presence \
|| (raise 'public_key must be present in config'))
$leihs_public_key = OpenSSL::PKey.read(
$config[:leihs_public_key].presence \
|| (raise 'leihs_public_key must be present in config'))
$nonces = Set[]
# get per tenant config and signing keys
# NOTE: Microsoft recomments to reload this every 24 Hours
$open_id_config =
"https://login.microsoftonline.com/#{$config[:tenant]}/.well-known/openid-configuration" \
.yield_self { |config_url| RestClient.get config_url}
.yield_self { |resp| JSON.parse(resp).with_indifferent_access }
$ms_keys = $open_id_config
.yield_self { |config| config[:jwks_uri] }
.yield_self { |jwks_uri| RestClient.get jwks_uri}
.yield_self { |resp| JSON.parse(resp).with_indifferent_access }
.yield_self { |res| $ms_keys = res[:keys] }
end
get '/authenticators/ms-open-id/status' do
'OK'
end
### error handling and error messages ########################################
def expired_response e, sign_in_request_token
status 403
$logger.error "#{e} #{e.backtrace}"
sign_in_request = JWT.decode sign_in_request_token,
$leihs_public_key, false, { algorithm: 'ES256' }
<<-HTML.strip_heredoc
<html>
<head></head>
<body>
<h1>Error: Token Expired </h1>
<p> Please <a href="#{sign_in_request[0]['server_base_url']}"> try again. </a></p>
</body>
</html>
HTML
end
def authentication_error_response e
status 403
$logger.error "#{e} #{e.backtrace}"
<<-HTML.strip_heredoc
<html>
<head></head>
<body>
<h1>Authentication Error</h1>
<p> #{e.message} </p>
</body>
</html>
HTML
end
def generic_error_response e
status 403
$logger.error "#{e} #{e.backtrace}"
<<-HTML.strip_heredoc
<html>
<head></head>
<body>
<h1> Unspecified Error in PHZH Open-ID Authentication Service </h1>
<p> Please try again. </p>
<p> Contact your leihs administrator if this problem occurs again. </p>
</body>
</html>
HTML
end
### sign-in ##################################################################
get '/authenticators/ms-open-id/sign-in' do
begin
sign_in_request_token = params[:token].presence
sign_in_request = JWT.decode sign_in_request_token,
$leihs_public_key, true, { algorithm: 'ES256' }
email = sign_in_request.first["email"]
token = JWT.encode({
sign_in_request_token: sign_in_request_token
# and more if we ever need it
}, $private_key, 'ES256')
nonce = SecureRandom.uuid
$nonces.add nonce
url = "https://login.microsoftonline.com/" + CGI::escape($tenant) \
+ '/oauth2/authorize?scope=openid&response_type=id_token&response_mode=form_post' \
+ '&redirect_uri=' + CGI::escape($external_base_url + "/authenticators/ms-open-id/callback") \
+ '&client_id=' + CGI::escape($client_id) \
+ '&login_hint=' + CGI::escape(email) \
+ '&state=' + CGI::escape(token) \
+ '&nonce=' + nonce
redirect url
rescue JWT::ExpiredSignature => e
expired_response e, sign_in_request_token
rescue StandardError => e
generic_error_response e
end
end
### sign-out ##################################################################
get '/authenticators/ms-open-id/sign-out' do
begin
redirect $open_id_config[:end_session_endpoint] \
+ "?post_logout_redirect_uri=" \
+ CGI::escape(params[:back_to])
rescue StandardError => e
generic_error_response e
end
end
### callback ##################################################################
def ms_signing_key(unverified_message)
kid = unverified_message[1]["kid"]
cert =$ms_keys.select{|k| k["kid"] == kid}.first["x5c"].first
OpenSSL::X509::Certificate.new(
"-----BEGIN CERTIFICATE-----\n" + cert + "\n-----END CERTIFICATE-----\n"
).public_key
end
def decode_id_token id_token
unverified_message = JWT.decode(id_token, nil, false)
key = ms_signing_key(unverified_message)
algorithm = unverified_message[1]["alg"]
JWT.decode(id_token, ms_signing_key(unverified_message), true, {algorithm: algorithm})
end
post '/authenticators/ms-open-id/callback' do
begin
id_token_data = decode_id_token(params[:id_token]).first.with_indifferent_access
nonce = id_token_data[:nonce]
if $nonces.include? nonce
$nonces.delete nonce
else
raise AuthenticationError,
"The nonce ist not known. Please try again as this can be a temporary issue. " +
"Contact your leihs administrator if the problem persists."
end
token_data = JWT.decode(params[:state], $public_key,
true, { algorithm: 'ES256'}).first.with_indifferent_access
sign_in_request_token = token_data[:sign_in_request_token]
sign_in_request = JWT.decode sign_in_request_token,
$leihs_public_key, true, { algorithm: 'ES256' }
unless id_token_data[$config[:email_attribute]].presence
raise AuthenticationError,
"The required property `unique_name` is missing. Contact your leihs administrator."
end
unless sign_in_request[0]["email"].downcase == id_token_data["upn"].downcase
raise AuthenticationError,
"There is an account mismatch between leihs and the response from the Open-ID provider. " +
"Make sure you use consistent accounts! " +
"Contact your leihs administrator if the problem persists."
end
token = JWT.encode({
sign_in_request_token: sign_in_request_token,
email: id_token_data["upn"].downcase,
success: true}, $private_key, 'ES256')
url = sign_in_request.first["server_base_url"] \
+ sign_in_request.first['path'] + "?token=#{token}"
redirect url
rescue JWT::ExpiredSignature => e
expired_response e, sign_in_request_token
rescue AuthenticationError => e
authentication_error_response e
rescue StandardError => e
generic_error_response e
end
end
end
################################################################################
### start up ###################################################################
################################################################################
AuthenticatorApp.port = $config[:port]
AuthenticatorApp.run!