OIDC.pm

filter: Statementstmt 75.0% 6 / 8 Branchbran n/a Conditioncond n/a MC/DCmcdc n/a Subroutinesub 100% 3 / 3 Podpod n/a totaltotal 81.8% 9 / 11 CC 1 SCAR 0.9
CC
1
Cov
75%
BEGIN
1.3
BEGIN
1.0
BEGIN
1.0
CRAP 1.1
« OIDC/Controller/OpenIDConnect.pm ↑ Summary
1 package Mojolicious::Plugin::Authentication::OIDC 0.06;
2 1 ▶use v5.26;
Subroutine BEGIN: called CC=1 SCAR=0.0
3 1 ▶use warnings;
Subroutine BEGIN: called CC=1 SCAR=0.0
4  
5 # ABSTRACT: OpenID Connect implementation integrated into Mojolicious
6  
7 =encoding UTF-8
8  
9 =head1 NAME
10  
11 Mojolicious::Plugin::Authentication::OIDC - OpenID Connect implementation
12 integrated into Mojolicious
13  
14 =head1 SYNOPSIS
15  
16 $self->plugin('Authentication::OIDC' => {
17 client_secret => '...',
18 well_known_url => 'https://idp/realms/master/.well-known/openid-configuration',
19 public_key => "-----BEGIN PUBLIC KEY-----\n...\n-----END PUBLIC KEY-----",
20 });
21  
22 # in controller
23 say "Hi " . $c->authn->current_user->firstname;
24  
25 use Array::Utils qw(intersect);
26 if(intersect($c->authn->current_user_roles->@*, qw(admin))) { ... }
27  
28 =head1 DESCRIPTION
29  
30 Mojolicious plugin for L<OpenID Connect|https://openid.net/developers/how-connect-works/>
31 authentication. Designed to work with an OpenID Connect provider like Keycloak,
32 in confidential access mode. Its design goal is to be configured "all at once"
33 and then little-to-no effort should be needed to support it elsewhere -- this is
34 largely achieved via hooks (L</on_success>, L</on_error>, L</on_login>,
35 L</on_activity>) and handlers (L</get_token>, L</get_user>, L</get_roles>)
36  
37 Controller actions C<OpenIDConnect#redirect> and C<OpenIDConnect#login> are
38 registered, and can be mapped to routes implicitly (see L</make_routes>) or
39 manually routed to (e.g., via L<Mojolicious::Plugin::OpenAPI>).
40  
41 For the auth workflow, clients should be sent to C<OpenIDConnect#redirect> (via
42 L</redirect_path> if L</make_routes> is enabled). Once the client authenticates
43 to the identity server, they'll be sent to C<OpenIDConnect#login> (via
44 L</login_path>, again, if L</make_routes> is enabled). Upon successful login, the
45 L</on_login> hook will be called, followed by the L</on_success> hook, which
46 should send the client to a post-login page. Then, on every server access
47 on/after login, the L</on_activity> hook will be called.
48  
49 Controllers may get information about the logged in user via the
50 L</current_user> and L</current_user_roles> helper methods.
51  
52 =cut
53  
54 0 ▶use Mojo::Base 'Mojolicious::Plugin';
Subroutine BEGIN: called CC=1 SCAR=2.6
55  
56 use Crypt::JWT qw(decode_jwt);
57 use Mojo::UserAgent;
58 use Readonly;
59 use Syntax::Keyword::Try;
60  
61 use experimental qw(signatures);
62  
63 Readonly::Array my @REQUIRED_PARAMS => qw(
64 client_secret
65 well_known_url
66 public_key
67 );
68 Readonly::Array my @ALLOWED_PARAMS => qw(
69 client_id on_login on_activity base_url
70 );
71 Readonly::Hash my %DEFAULT_PARAMS => (
72 login_path => '/auth/login',
73 redirect_path => '/auth',
74 make_routes => 1,
75  
76 on_success => sub ($c, $token, $url) {$c->session(token => $token); $c->redirect_to($url)},
77 on_error => sub ($c, $error) {$c->render(json => $error)},
78  
79 get_token => sub ($c) {$c->session('token')},
80 get_user => sub ($token) {$token},
81 get_roles => sub ($user, $token) {$user ? [] : undef},
82  
83 role_map => undef,
84 );
85 Readonly::Hash my %DEFAULT_CONSTANTS => (
86 scope => 'openid',
87 response_type => 'code',
88 grant_type => 'authorization_code',
89 );
90 Readonly::Scalar my $DEFAULT_PREFIX => 'authn';
91  
92 =head1 METHODS
93  
94 L<Mojolicious::Plugin::Authentication::OIDC> inherits all methods from
95 L<Mojolicious::Plugin> and implements the following new ones
96  
97 =head2 register( \%params )
98  
99 Register plugin in L<Mojolicious> application, including registering
100 L<Mojolicious::Plugin::Authentication::OIDC::Controller::OpenIDConnect> as a
101 Mojolicious controller.
102  
103 Configuration is done via the C<\%params> HashRef, given the following keys
104  
105 =head4 make_routes
106  
107 B<Optional>
108  
109 A flag to indicate whether routes should be registered for L</redirect_path> and
110 L</login_path> pointing to
111 L<Mojolicious::Plugin::Authentication::OIDC::Controller::OpenIDConnect/redirect>
112 and L<Mojolicious::Plugin::Authentication::OIDC::Controller::OpenIDConnect/login>,
113 respectively. Set to false if you are handling these routes some other way, for
114 instance in a L<Mojolicious::PLugin::OpenAPI> spec.
115  
116 Default: true
117  
118 =head4 client_id
119  
120 B<Optional>
121  
122 The application's unique identifier, to the auhorization server
123  
124 Default: the application moniker (lowercase)
125  
126 =head4 client_secret
127  
128 B<Required>
129  
130 A secret value known to the authorization server, specific to this application
131  
132 =head4 well_known_url
133  
134 B<Required>
135  
136 A discovery endpoint that informs the application of the authorization server's
137 specific configuration and capabilities
138  
139 Example: C<https://idp.domain.com/realms/master/.well-known/openid-configuration>
140  
141 =head4 public_key
142  
143 B<Required>
144  
145 The RSA public key corresponding to the private key with which the authorization
146 tokens are signed by the authorization server. Format is a PEM/DER/JWT string
147 accepted by L<Crypt::JWT/decode_jwt>'s C<key> parameter.
148  
149 =head4 redirect_path
150  
151 B<Optional>
152  
153 The path for the route which redirects users to the authorization server. Only
154 used when L</make_routes> is enabled, for configuring the path of that route.
155  
156 Default: C</auth>
157  
158 =head4 login_path
159  
160 B<Optional>
161  
162 The path section of the URL to be used as the OIDC C<redirect_uri>. The full
163 URL will be constructed based on the scheme/host/port of the request. This
164 path is also used for route registration if L</make_routes> is enabled.
165  
166 Default: C</auth/login>
167  
168 =head4 get_user ( $token )
169  
170 B<Optional>
171  
172 A callback that's given the auth token data as its only argument. It should
173 return the application's C<user> instance corresponding to that data (e.g., a
174 database record object), creating any references as necessary.
175  
176 Default: Simply returns the auth token data as a HashRef
177  
178  
179 =head4 get_token ( $controller )
180  
181 B<Optional>
182  
183 A callback that's given a Mojolicious controller as its only argument. It should
184 return the encoded authorization token. This allows the application to choose
185 where and how the token is stored on the client side and sent to the server.
186  
187 Default: returns the C<token> value of the Mojo session
188  
189 =head4 get_roles ( $user, $token )
190  
191 B<Optional>
192  
193 Given a C<user> instance (produced by L</get_user>) and a decoded authorization
194 token as arguments, returns an ArrayRef of roles pertaining to that user.
195  
196 Default: returns an empty ArrayRef
197  
198 =head4 role_map (%map)
199  
200 B<Optional>
201  
202 A mapping of external roles (e.g., from Authorization Server) to internal roles
203 used by the application's authorization framework. If this option is specified,
204 roles not present in its keys are deleted, all others will be mapped.
205  
206 =head4 on_login ( $controller, $user )
207  
208 B<Optional>
209  
210 A hook to allow the application to respond to a successful user login, such as
211 updating the user's C<last_login> date.
212  
213 Default: C<undef>
214  
215 =head4 on_activity ( $controller, $user )
216  
217 B<Optional>
218  
219 A hook to allow the application to respond to any request by a logged-in user,
220 such as updating the user's C<last_activity> date.
221  
222 Default: C<undef>
223  
224 =head4 on_success ( $controller, $token )
225  
226 B<Optional>
227  
228 A hook invoked when the user's authorization request succeeds. This code should
229 address storage of the authentication token on the frontend.
230  
231 Default: Stores the (encrypted) token in the C<token> key of the Mojo session
232 and redirects to C</login/success>
233  
234 =head4 on_error
235  
236 B<Optional>
237  
238 A hook invoked when the user's authorization request fails.
239  
240 Default: renders the Authorization Server's response (JSON)
241  
242 =head2 current_user
243  
244 Returns the user record (from L</get_user>) for the currently logged in user.
245 If no user is logged in, or any failure occurs in reading their access token,
246 returns C<undef>
247  
248 =head2 current_user_roles
249  
250 If a user is logged in, returns their roles (as determined by L</get_roles>).
251 Otherwise, returns C<undef>
252  
253 =cut
254  
255 sub register($self, $app, $params) {
256 # Prefix handling
257 my $prefix = $params->{prefix} // $DEFAULT_PREFIX;
258 $prefix .= '.' if ($prefix);
259 my $params_helper = "__oidc_params";
260 my $token_helper = "__oidc_token";
261 my $current_user_helper = "${prefix}current_user";
262 my $current_user_roles_helper = "${prefix}current_user_roles";
263 # Parameter handling
264 my %conf = (%DEFAULT_CONSTANTS, %DEFAULT_PARAMS, client_id => lc($app->moniker));
265 $conf{$_} = $params->{$_} foreach (grep {exists($params->{$_})} (keys(%DEFAULT_PARAMS), @REQUIRED_PARAMS, @ALLOWED_PARAMS));
266 # die if required/conditionally required params aren't found
267 foreach (@REQUIRED_PARAMS) {die("Required param '$_' not found") unless (defined($conf{$_}))}
268 die("Required param 'redirect_path' not found") if ($conf{make_routes} && !defined($conf{redirect_path}));
269  
270 # wrap success handler so that we can call login handler before finishing the req
271 my $success_handler = $conf{on_success};
272 $conf{on_success} = sub($c, $token, $url) {
273 my $token_data = $c->app->renderer->get_helper($token_helper)->($c, $token);
274 my $user = $conf{get_user}->($token_data);
275 $conf{on_login}->($c, $user) if ($conf{on_login});
276 return $success_handler->($c, $token, $url);
277 };
278  
279 # Add our controller to the namespace for calling via routes or, e.g., OpenAPI
280 push($app->routes->namespaces->@*, 'Mojolicious::Plugin::Authentication::OIDC::Controller');
281  
282 # Fetch actual endpoints from well-known URL
283 my $resp = Mojo::UserAgent->new()->get($conf{well_known_url});
284 die("Unable to determine OIDC endpoints (" . $resp->res->error->{message} . ")\n") if ($resp->res->is_error);
285 @conf{qw(auth_endpoint token_endpoint logout_endpoint)} =
286 @{$resp->res->json}{qw(authorization_endpoint token_endpoint end_session_endpoint)};
287  
288 # internal helper for stored parameters (only to be used by OpenIDConnect controller)
289 $app->helper(
290 $params_helper => sub {
291 return {map {$_ => $conf{$_}}
292 qw(auth_endpoint scope response_type login_path token_endpoint client_id client_secret grant_type on_error on_success logout_endpoint base_url)
293 };
294 }
295 );
296  
297 # internal helper for decoded auth token. Pass the token in, or it'll be retrieved
298 # via `get_token` handler
299 $app->helper(
300 $token_helper => sub($c, $token = undef, $decode = 1) {
301 my $t = $token // $conf{get_token}->($c);
302 return $t unless ($decode);
303 return undef if (!defined($t) || $t eq 'null');
304 return decode_jwt(token => $t, key => \$conf{public_key});
305 }
306 );
307  
308 # public helper to access current user and OIDC roles
309 $app->helper(
310 $current_user_helper => sub($c) {
311 my $t = $c->app->renderer->get_helper($token_helper)->($c);
312 return undef if (!defined($t) || $t eq 'null');
313 return $conf{get_user}->($t);
314 }
315 );
316 $app->helper(
317 $current_user_roles_helper => sub($c) {
318 my ($user, $token);
319 try {
320 $token = $c->app->renderer->get_helper($token_helper)->($c);
321 return [] unless ($token);
322 $user = $c->app->renderer->get_helper($current_user_helper)->($c);
323 my @roles = $conf{get_roles}->($user, $token)->@*;
324 @roles = grep {defined} map {$conf{role_map}->{$_}} @roles if (defined($conf{role_map}));
325 return [@roles];
326 } catch ($e) {
327 return undef
328 }
329 return undef;
330 }
331 );
332  
333 # if `on_activity` handler exists, call it from a before_dispatch hook
334 $app->hook(
335 before_dispatch => sub($c) {
336 my $u;
337 try {$u = $c->app->renderer->get_helper($current_user_helper)->($c);} catch ($e) {
338 }
339 $conf{on_activity}->($c, $u) if ($u);
340 }
341 )
342 if ($conf{on_activity});
343 # if `make_routes` is true, register our controller actions at the appropriate paths
344 # otherwise, it's up to the downstream code to do this, e.g., via OpenAPI spec
345 if ($conf{make_routes}) {
346 $app->routes->get($conf{redirect_path})->to("OpenIDConnect#redirect");
347 $app->routes->get($conf{login_path})->to('OpenIDConnect#login');
348 }
349 }
350  
351 =head1 AUTHOR
352  
353 Mark Tyrrell C<< <mark@tyrrminal.dev> >>
354  
355 =head1 LICENSE
356  
357 Copyright (c) 2024 Mark Tyrrell
358  
359 Permission is hereby granted, free of charge, to any person obtaining a copy
360 of this software and associated documentation files (the "Software"), to deal
361 in the Software without restriction, including without limitation the rights
362 to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
363 copies of the Software, and to permit persons to whom the Software is
364 furnished to do so, subject to the following conditions:
365  
366 The above copyright notice and this permission notice shall be included in all
367 copies or substantial portions of the Software.
368  
369 THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
370 IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
371 FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
372 AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
373 LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
374 OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
375 SOFTWARE.
376  
377 =cut
378  
379 1;
380  
381 __END__
« OIDC/Controller/OpenIDConnect.pm ↑ Summary