/
handler_authz_authn.go
585 lines (450 loc) · 22.5 KB
/
handler_authz_authn.go
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
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
package handlers
import (
"bytes"
"context"
"encoding/base64"
"errors"
"fmt"
"net/url"
"strings"
"time"
oauthelia2 "authelia.com/provider/oauth2"
"github.com/sirupsen/logrus"
"github.com/valyala/fasthttp"
"github.com/authelia/authelia/v4/internal/authentication"
"github.com/authelia/authelia/v4/internal/authorization"
"github.com/authelia/authelia/v4/internal/configuration/schema"
"github.com/authelia/authelia/v4/internal/middlewares"
"github.com/authelia/authelia/v4/internal/model"
"github.com/authelia/authelia/v4/internal/oidc"
"github.com/authelia/authelia/v4/internal/session"
"github.com/authelia/authelia/v4/internal/utils"
)
// NewCookieSessionAuthnStrategy creates a new CookieSessionAuthnStrategy.
func NewCookieSessionAuthnStrategy(refresh schema.RefreshIntervalDuration) *CookieSessionAuthnStrategy {
return &CookieSessionAuthnStrategy{
refresh: refresh,
}
}
// NewHeaderAuthorizationAuthnStrategy creates a new HeaderAuthnStrategy using the Authorization and WWW-Authenticate
// headers, and the 407 Proxy Auth Required response.
func NewHeaderAuthorizationAuthnStrategy(schemes ...string) *HeaderAuthnStrategy {
return &HeaderAuthnStrategy{
authn: AuthnTypeAuthorization,
headerAuthorize: headerAuthorization,
headerAuthenticate: headerWWWAuthenticate,
handleAuthenticate: true,
statusAuthenticate: fasthttp.StatusUnauthorized,
schemes: model.NewAuthorizationSchemes(schemes...),
}
}
// NewHeaderProxyAuthorizationAuthnStrategy creates a new HeaderAuthnStrategy using the Proxy-Authorization and
// Proxy-Authenticate headers, and the 407 Proxy Auth Required response.
func NewHeaderProxyAuthorizationAuthnStrategy(schemes ...string) *HeaderAuthnStrategy {
return &HeaderAuthnStrategy{
authn: AuthnTypeProxyAuthorization,
headerAuthorize: headerProxyAuthorization,
headerAuthenticate: headerProxyAuthenticate,
handleAuthenticate: true,
statusAuthenticate: fasthttp.StatusProxyAuthRequired,
schemes: model.NewAuthorizationSchemes(schemes...),
}
}
// NewHeaderProxyAuthorizationAuthRequestAuthnStrategy creates a new HeaderAuthnStrategy using the Proxy-Authorization
// and WWW-Authenticate headers, and the 401 Proxy Auth Required response. This is a special AuthnStrategy for the
// AuthRequest implementation.
func NewHeaderProxyAuthorizationAuthRequestAuthnStrategy(schemes ...string) *HeaderAuthnStrategy {
return &HeaderAuthnStrategy{
authn: AuthnTypeProxyAuthorization,
headerAuthorize: headerProxyAuthorization,
headerAuthenticate: headerWWWAuthenticate,
handleAuthenticate: true,
statusAuthenticate: fasthttp.StatusUnauthorized,
schemes: model.NewAuthorizationSchemes(schemes...),
}
}
// NewHeaderLegacyAuthnStrategy creates a new HeaderLegacyAuthnStrategy.
func NewHeaderLegacyAuthnStrategy() *HeaderLegacyAuthnStrategy {
return &HeaderLegacyAuthnStrategy{}
}
// CookieSessionAuthnStrategy is a session cookie AuthnStrategy.
type CookieSessionAuthnStrategy struct {
refresh schema.RefreshIntervalDuration
}
// Get returns the Authn information for this AuthnStrategy.
func (s *CookieSessionAuthnStrategy) Get(ctx *middlewares.AutheliaCtx, provider *session.Session, _ *authorization.Object) (authn *Authn, err error) {
var userSession session.UserSession
authn = &Authn{
Type: AuthnTypeCookie,
Level: authentication.NotAuthenticated,
Username: anonymous,
}
if userSession, err = provider.GetSession(ctx.RequestCtx); err != nil {
return authn, fmt.Errorf("failed to retrieve user session: %w", err)
}
if userSession.CookieDomain != provider.Config.Domain {
ctx.Logger.Warnf("Destroying session cookie as the cookie domain '%s' does not match the requests detected cookie domain '%s' which may be a sign a user tried to move this cookie from one domain to another", userSession.CookieDomain, provider.Config.Domain)
if err = provider.DestroySession(ctx.RequestCtx); err != nil {
ctx.Logger.WithError(err).Error("Error occurred trying to destroy the session cookie")
}
userSession = provider.NewDefaultUserSession()
if err = provider.SaveSession(ctx.RequestCtx, userSession); err != nil {
ctx.Logger.WithError(err).Error("Error occurred trying to save the new session cookie")
}
}
if invalid := handleVerifyGETAuthnCookieValidate(ctx, provider, &userSession, s.refresh); invalid {
if err = ctx.DestroySession(); err != nil {
ctx.Logger.WithError(err).Errorf("Unable to destroy user session")
}
userSession = provider.NewDefaultUserSession()
userSession.LastActivity = ctx.Clock.Now().Unix()
if err = provider.SaveSession(ctx.RequestCtx, userSession); err != nil {
ctx.Logger.WithError(err).Error("Unable to save updated user session")
}
return authn, nil
}
if err = provider.SaveSession(ctx.RequestCtx, userSession); err != nil {
ctx.Logger.WithError(err).Error("Unable to save updated user session")
}
return &Authn{
Username: friendlyUsername(userSession.Username),
Details: authentication.UserDetails{
Username: userSession.Username,
DisplayName: userSession.DisplayName,
Emails: userSession.Emails,
Groups: userSession.Groups,
},
Level: userSession.AuthenticationLevel,
Type: AuthnTypeCookie,
}, nil
}
// CanHandleUnauthorized returns true if this AuthnStrategy should handle Unauthorized requests.
func (s *CookieSessionAuthnStrategy) CanHandleUnauthorized() (handle bool) {
return false
}
// HandleUnauthorized is the Unauthorized handler for the cookie AuthnStrategy.
func (s *CookieSessionAuthnStrategy) HandleUnauthorized(_ *middlewares.AutheliaCtx, _ *Authn, _ *url.URL) {
}
// HeaderAuthnStrategy is a header AuthnStrategy.
type HeaderAuthnStrategy struct {
authn AuthnType
headerAuthorize []byte
headerAuthenticate []byte
handleAuthenticate bool
statusAuthenticate int
schemes model.AuthorizationSchemes
}
// Get returns the Authn information for this AuthnStrategy.
func (s *HeaderAuthnStrategy) Get(ctx *middlewares.AutheliaCtx, _ *session.Session, object *authorization.Object) (authn *Authn, err error) {
var value []byte
authn = &Authn{
Type: s.authn,
Level: authentication.NotAuthenticated,
Username: anonymous,
}
if value = ctx.Request.Header.PeekBytes(s.headerAuthorize); len(value) == 0 {
return authn, nil
}
authz := model.NewAuthorization()
if err = authz.ParseBytes(value); err != nil {
return authn, fmt.Errorf("failed to parse content of %s header: %w", s.headerAuthorize, err)
}
authn.Header.Authorization = authz
var (
username, clientID string
ccs bool
level authentication.Level
)
scheme := authn.Header.Authorization.Scheme()
if !s.schemes.Has(scheme) {
return authn, fmt.Errorf("invalid scheme: scheme with name '%s' isn't available on this endpoint", scheme.String())
}
switch scheme {
case model.AuthorizationSchemeBasic:
username, level, err = s.handleGetBasic(ctx, authn, object)
case model.AuthorizationSchemeBearer:
username, clientID, ccs, level, err = handleVerifyGETAuthorizationBearer(ctx, authn, object)
default:
err = fmt.Errorf("failed to parse content of %s header: the scheme '%s' is not known", s.headerAuthorize, authn.Header.Authorization.SchemeRaw())
}
if err != nil {
return authn, fmt.Errorf("failed to validate %s header with %s scheme: %w", s.headerAuthorize, scheme, err)
}
switch {
case ccs:
if len(clientID) == 0 {
return authn, fmt.Errorf("failed to determine client id from the %s header", s.headerAuthorize)
}
authn.ClientID = clientID
case len(username) == 0:
return authn, fmt.Errorf("failed to determine username from the %s header", s.headerAuthorize)
default:
var details *authentication.UserDetails
if details, err = ctx.Providers.UserProvider.GetDetails(username); err != nil {
if errors.Is(err, authentication.ErrUserNotFound) {
ctx.Logger.WithField("username", username).Error("Error occurred while attempting to get user details for user: the user was not found indicating they were deleted, disabled, or otherwise no longer authorized to login")
return authn, err
}
return authn, fmt.Errorf("unable to retrieve details for user '%s': %w", username, err)
}
authn.Username = friendlyUsername(details.Username)
authn.Details = *details
}
authn.Level = level
return authn, nil
}
func (s *HeaderAuthnStrategy) handleGetBasic(ctx *middlewares.AutheliaCtx, authn *Authn, _ *authorization.Object) (username string, level authentication.Level, err error) {
var (
valid bool
)
if valid, err = ctx.Providers.UserProvider.CheckUserPassword(authn.Header.Authorization.Basic()); err != nil {
return "", authentication.NotAuthenticated, fmt.Errorf("failed to validate parsed credentials of %s header for user '%s': %w", s.headerAuthorize, authn.Header.Authorization.BasicUsername(), err)
}
if !valid {
return "", authentication.NotAuthenticated, fmt.Errorf("validated parsed credentials of %s header but they are not valid for user '%s': %w", s.headerAuthorize, authn.Header.Authorization.BasicUsername(), err)
}
return authn.Header.Authorization.BasicUsername(), authentication.OneFactor, nil
}
// CanHandleUnauthorized returns true if this AuthnStrategy should handle Unauthorized requests.
func (s *HeaderAuthnStrategy) CanHandleUnauthorized() (handle bool) {
return s.handleAuthenticate
}
// HandleUnauthorized is the Unauthorized handler for the header AuthnStrategy.
func (s *HeaderAuthnStrategy) HandleUnauthorized(ctx *middlewares.AutheliaCtx, authn *Authn, _ *url.URL) {
ctx.Logger.Debugf("Responding %d %s", s.statusAuthenticate, s.headerAuthenticate)
ctx.ReplyStatusCode(s.statusAuthenticate)
if authn.Header.Authorization != nil && authn.Header.Authorization.Scheme() == model.AuthorizationSchemeBearer && authn.Header.Error != nil {
ctx.Response.Header.SetBytesK(s.headerAuthenticate, fmt.Sprintf(`Bearer %s`, oidc.RFC6750Header(authn.Header.Realm, authn.Header.Scope, authn.Header.Error)))
} else if s.headerAuthenticate != nil {
ctx.Response.Header.SetBytesKV(s.headerAuthenticate, headerValueAuthenticateBasic)
}
}
// HeaderLegacyAuthnStrategy is a legacy header AuthnStrategy which can be switched based on the query parameters.
type HeaderLegacyAuthnStrategy struct{}
// Get returns the Authn information for this AuthnStrategy.
func (s *HeaderLegacyAuthnStrategy) Get(ctx *middlewares.AutheliaCtx, _ *session.Session, _ *authorization.Object) (authn *Authn, err error) {
var (
username, password string
value, header []byte
)
authn = &Authn{
Level: authentication.NotAuthenticated,
Username: anonymous,
}
if qryValueAuth := ctx.QueryArgs().PeekBytes(qryArgAuth); bytes.Equal(qryValueAuth, qryValueBasic) {
authn.Type = AuthnTypeAuthorization
header = headerAuthorization
} else {
authn.Type = AuthnTypeProxyAuthorization
header = headerProxyAuthorization
}
value = ctx.Request.Header.PeekBytes(header)
switch {
case value == nil && authn.Type == AuthnTypeAuthorization:
return authn, fmt.Errorf("header %s expected", headerAuthorization)
case value == nil:
return authn, nil
}
if username, password, err = headerAuthorizationParse(value); err != nil {
return authn, fmt.Errorf("failed to parse content of %s header: %w", header, err)
}
if username == "" || password == "" {
return authn, fmt.Errorf("failed to validate parsed credentials of %s header for user '%s': %w", header, username, err)
}
var (
valid bool
details *authentication.UserDetails
)
if valid, err = ctx.Providers.UserProvider.CheckUserPassword(username, password); err != nil {
return authn, fmt.Errorf("failed to validate parsed credentials of %s header for user '%s': %w", header, username, err)
}
if !valid {
return authn, fmt.Errorf("validated parsed credentials of %s header but they are not valid for user '%s': %w", header, username, err)
}
if details, err = ctx.Providers.UserProvider.GetDetails(username); err != nil {
if errors.Is(err, authentication.ErrUserNotFound) {
ctx.Logger.WithField("username", username).Error("Error occurred while attempting to get user details for user: the user was not found indicating they were deleted, disabled, or otherwise no longer authorized to login")
return authn, err
}
return authn, fmt.Errorf("unable to retrieve details for user '%s': %w", username, err)
}
authn.Username = friendlyUsername(details.Username)
authn.Details = *details
authn.Level = authentication.OneFactor
return authn, nil
}
// CanHandleUnauthorized returns true if this AuthnStrategy should handle Unauthorized requests.
func (s *HeaderLegacyAuthnStrategy) CanHandleUnauthorized() (handle bool) {
return true
}
// HandleUnauthorized is the Unauthorized handler for the Legacy header AuthnStrategy.
func (s *HeaderLegacyAuthnStrategy) HandleUnauthorized(ctx *middlewares.AutheliaCtx, authn *Authn, _ *url.URL) {
handleAuthzUnauthorizedAuthorizationBasic(ctx, authn)
}
func handleVerifyGETAuthnCookieValidate(ctx *middlewares.AutheliaCtx, provider *session.Session, userSession *session.UserSession, refresh schema.RefreshIntervalDuration) (invalid bool) {
isAnonymous := userSession.Username == ""
if isAnonymous && userSession.AuthenticationLevel != authentication.NotAuthenticated {
ctx.Logger.WithFields(map[string]any{"username": anonymous, "level": userSession.AuthenticationLevel.String()}).Errorf("Session for user has an invalid authentication level: this may be a sign of a compromise")
return true
}
if invalid = handleVerifyGETAuthnCookieValidateInactivity(ctx, provider, userSession, isAnonymous); invalid {
ctx.Logger.WithField("username", userSession.Username).Info("Session for user not marked as remembered has exceeded configured session inactivity")
return true
}
if invalid = handleVerifyGETAuthnCookieValidateRefresh(ctx, userSession, isAnonymous, refresh); invalid {
return true
}
if username := ctx.Request.Header.PeekBytes(headerSessionUsername); username != nil && !strings.EqualFold(string(username), userSession.Username) {
ctx.Logger.WithField("username", userSession.Username).Warnf("Session for user does not match the Session-Username header with value '%s' which could be a sign of a cookie hijack", username)
return true
}
if !userSession.KeepMeLoggedIn {
userSession.LastActivity = ctx.Clock.Now().Unix()
}
return false
}
func handleVerifyGETAuthnCookieValidateInactivity(ctx *middlewares.AutheliaCtx, provider *session.Session, userSession *session.UserSession, isAnonymous bool) (invalid bool) {
if isAnonymous || userSession.KeepMeLoggedIn || int64(provider.Config.Inactivity.Seconds()) == 0 {
return false
}
ctx.Logger.WithField("username", userSession.Username).Tracef("Inactivity report for user. Current Time: %d, Last Activity: %d, Maximum Inactivity: %d.", ctx.Clock.Now().Unix(), userSession.LastActivity, int(provider.Config.Inactivity.Seconds()))
return time.Unix(userSession.LastActivity, 0).Add(provider.Config.Inactivity).Before(ctx.Clock.Now())
}
func handleVerifyGETAuthnCookieValidateRefresh(ctx *middlewares.AutheliaCtx, userSession *session.UserSession, isAnonymous bool, refresh schema.RefreshIntervalDuration) (invalid bool) {
if refresh.Never() || isAnonymous {
return false
}
ctx.Logger.WithField("username", userSession.Username).Trace("Checking if we need check the authentication backend for an updated profile for user")
if !refresh.Always() && userSession.RefreshTTL.After(ctx.Clock.Now()) {
return false
}
ctx.Logger.WithField("username", userSession.Username).Debug("Checking the authentication backend for an updated profile for user")
var (
details *authentication.UserDetails
err error
)
if details, err = ctx.Providers.UserProvider.GetDetails(userSession.Username); err != nil {
if errors.Is(err, authentication.ErrUserNotFound) {
ctx.Logger.WithField("username", userSession.Username).Error("Error occurred while attempting to update user details for user: the user was not found indicating they were deleted, disabled, or otherwise no longer authorized to login")
return true
}
ctx.Logger.WithError(err).WithField("username", userSession.Username).Error("Error occurred while attempting to update user details for user")
return false
}
var (
diffEmails, diffGroups, diffDisplayName bool
)
diffEmails, diffGroups = utils.IsStringSlicesDifferent(userSession.Emails, details.Emails), utils.IsStringSlicesDifferent(userSession.Groups, details.Groups)
diffDisplayName = userSession.DisplayName != details.DisplayName
if !refresh.Always() {
userSession.RefreshTTL = ctx.Clock.Now().Add(refresh.Value())
}
if !diffEmails && !diffGroups && !diffDisplayName {
ctx.Logger.WithField("username", userSession.Username).Trace("Updated profile not detected for user")
return false
}
ctx.Logger.WithField("username", userSession.Username).Debug("Updated profile detected for user")
if ctx.Logger.Level >= logrus.TraceLevel {
generateVerifySessionHasUpToDateProfileTraceLogs(ctx, userSession, details)
}
userSession.Emails, userSession.Groups, userSession.DisplayName = details.Emails, details.Groups, details.DisplayName
return false
}
func handleVerifyGETAuthorizationBearer(ctx *middlewares.AutheliaCtx, authn *Authn, object *authorization.Object) (username, clientID string, ccs bool, level authentication.Level, err error) {
if ctx.Providers.OpenIDConnect == nil || ctx.Configuration.IdentityProviders.OIDC == nil || !ctx.Configuration.IdentityProviders.OIDC.Discovery.BearerAuthorization {
return "", "", false, authentication.NotAuthenticated, fmt.Errorf("authorization bearer scheme requires an OpenID Connect 1.0 configuration but it's absent")
}
if !ctx.Configuration.IdentityProviders.OIDC.Discovery.BearerAuthorization {
return "", "", false, authentication.NotAuthenticated, fmt.Errorf("authorization bearer scheme requires an OAuth 2.0 or OpenID Connect 1.0 client to be registered with the '%s' scope but there are none", oidc.ScopeAutheliaBearerAuthz)
}
return handleVerifyGETAuthorizationBearerIntrospection(ctx, ctx.Providers.OpenIDConnect, authn, object)
}
type AuthzBearerIntrospectionProvider interface {
GetFullClient(ctx context.Context, id string) (client oidc.Client, err error)
GetAudienceStrategy(ctx context.Context) (strategy oauthelia2.AudienceMatchingStrategy)
IntrospectToken(ctx context.Context, token string, tokenUse oauthelia2.TokenUse, session oauthelia2.Session, scope ...string) (oauthelia2.TokenUse, oauthelia2.AccessRequester, error)
}
func handleVerifyGETAuthorizationBearerIntrospection(ctx context.Context, provider AuthzBearerIntrospectionProvider, authn *Authn, object *authorization.Object) (username, clientID string, ccs bool, level authentication.Level, err error) {
var (
use oauthelia2.TokenUse
requester oauthelia2.AccessRequester
)
authn.Header.Error = &oauthelia2.RFC6749Error{
ErrorField: "invalid_token",
DescriptionField: "The access token is expired, revoked, malformed, or invalid for other reasons. The client can obtain a new access token and try again.",
}
if use, requester, err = provider.IntrospectToken(ctx, authn.Header.Authorization.Value(), oauthelia2.AccessToken, oidc.NewSession(), oidc.ScopeAutheliaBearerAuthz); err != nil {
return "", "", false, authentication.NotAuthenticated, fmt.Errorf("error performing token introspection: %w", oauthelia2.ErrorToDebugRFC6749Error(err))
}
if use != oauthelia2.AccessToken {
authn.Header.Error = oauthelia2.ErrInvalidRequest
return "", "", false, authentication.NotAuthenticated, fmt.Errorf("token is not an access token")
}
audience := []string{object.URL.String()}
strategy := provider.GetAudienceStrategy(ctx)
if err = strategy(requester.GetGrantedAudience(), audience); err != nil {
return "", "", false, authentication.NotAuthenticated, fmt.Errorf("token does not contain a valid audience for the url '%s' with the error: %w", audience[0], err)
}
fsession := requester.GetSession()
var (
client oidc.Client
osession *oidc.Session
ok bool
)
if osession, ok = fsession.(*oidc.Session); !ok {
return "", "", false, authentication.NotAuthenticated, fmt.Errorf("introspection returned an invalid session type")
}
if client, err = provider.GetFullClient(ctx, osession.ClientID); err != nil || client == nil {
return "", "", false, authentication.NotAuthenticated, fmt.Errorf("client id '%s' is not registered", osession.ClientID)
}
if !client.GetScopes().Has(oidc.ScopeAutheliaBearerAuthz) {
return "", "", false, authentication.NotAuthenticated, fmt.Errorf("client id '%s' is registered but does not permit the '%s' scope", osession.ClientID, oidc.ScopeAutheliaBearerAuthz)
}
if err = strategy(client.GetAudience(), audience); err != nil {
return "", "", false, authentication.NotAuthenticated, fmt.Errorf("client id '%s' is registered but does not permit an audience for the url '%s' with the error: %w", osession.ClientID, audience[0], err)
}
if osession.DefaultSession == nil || osession.DefaultSession.Claims == nil {
return "", "", false, authentication.NotAuthenticated, fmt.Errorf("introspection returned a session missing required values")
}
authn.Header.Error = nil
if osession.ClientCredentials {
return "", osession.ClientID, true, authentication.OneFactor, nil
}
if oidc.NewAuthenticationMethodsReferencesFromClaim(osession.DefaultSession.Claims.AuthenticationMethodsReferences).MultiFactorAuthentication() {
level = authentication.TwoFactor
} else {
level = authentication.OneFactor
}
return osession.Username, "", false, level, nil
}
func headerAuthorizationParse(value []byte) (username, password string, err error) {
if bytes.Equal(value, qryValueEmpty) {
return "", "", fmt.Errorf("header is malformed: empty value")
}
parts := strings.SplitN(string(value), " ", 2)
if len(parts) != 2 {
return "", "", fmt.Errorf("header is malformed: does not appear to have a scheme")
}
scheme := strings.ToLower(parts[0])
switch scheme {
case headerAuthorizationSchemeBasic:
if username, password, err = headerAuthorizationParseBasic(parts[1]); err != nil {
return username, password, fmt.Errorf("header is malformed: %w", err)
}
return username, password, nil
default:
return "", "", fmt.Errorf("header is malformed: unsupported scheme '%s': supported schemes '%s'", parts[0], strings.ToTitle(headerAuthorizationSchemeBasic))
}
}
func headerAuthorizationParseBasic(value string) (username, password string, err error) {
var content []byte
if content, err = base64.StdEncoding.DecodeString(value); err != nil {
return "", "", fmt.Errorf("could not decode credentials: %w", err)
}
strContent := string(content)
s := strings.IndexByte(strContent, ':')
if s < 1 {
return "", "", fmt.Errorf("format of header must be <user>:<password> but either doesn't have a colon or username")
}
return strContent[:s], strContent[s+1:], nil
}