|
| 1 | +// Copyright (c) Duende Software. All rights reserved. |
| 2 | +// Licensed under the MIT License. See LICENSE in the project root for license information. |
| 3 | + |
| 4 | +using System.Text; |
| 5 | +using IdentityModel; |
| 6 | +using Microsoft.AspNetCore.Authentication.JwtBearer; |
| 7 | +using Microsoft.Extensions.Options; |
| 8 | +using Microsoft.Net.Http.Headers; |
| 9 | +using static IdentityModel.OidcConstants; |
| 10 | + |
| 11 | +namespace DPoP.Api; |
| 12 | + |
| 13 | +public class DPoPJwtBearerEvents : JwtBearerEvents |
| 14 | +{ |
| 15 | + private readonly IOptionsMonitor<DPoPOptions> _optionsMonitor; |
| 16 | + private readonly DPoPProofValidator _validator; |
| 17 | + |
| 18 | + public DPoPJwtBearerEvents(IOptionsMonitor<DPoPOptions> optionsMonitor, DPoPProofValidator validator) |
| 19 | + { |
| 20 | + _optionsMonitor = optionsMonitor; |
| 21 | + _validator = validator; |
| 22 | + } |
| 23 | + |
| 24 | + public override Task MessageReceived(MessageReceivedContext context) |
| 25 | + { |
| 26 | + var dpopOptions = _optionsMonitor.Get(context.Scheme.Name); |
| 27 | + |
| 28 | + if (context.HttpContext.Request.TryGetDPoPAccessToken(out var token)) |
| 29 | + { |
| 30 | + context.Token = token; |
| 31 | + } |
| 32 | + else if (dpopOptions.Mode == DPoPMode.DPoPOnly) |
| 33 | + { |
| 34 | + // this rejects the attempt for this handler, |
| 35 | + // since we don't want to attempt Bearer given the Mode |
| 36 | + context.NoResult(); |
| 37 | + } |
| 38 | + |
| 39 | + return Task.CompletedTask; |
| 40 | + } |
| 41 | + |
| 42 | + public override async Task TokenValidated(TokenValidatedContext context) |
| 43 | + { |
| 44 | + var dpopOptions = _optionsMonitor.Get(context.Scheme.Name); |
| 45 | + |
| 46 | + if (context.HttpContext.Request.TryGetDPoPAccessToken(out var at)) |
| 47 | + { |
| 48 | + var proofToken = context.HttpContext.Request.GetDPoPProofToken(); |
| 49 | + var result = await _validator.ValidateAsync(new DPoPProofValidatonContext |
| 50 | + { |
| 51 | + Scheme = context.Scheme.Name, |
| 52 | + ProofToken = proofToken, |
| 53 | + AccessToken = at, |
| 54 | + Method = context.HttpContext.Request.Method, |
| 55 | + Url = context.HttpContext.Request.Scheme + "://" + context.HttpContext.Request.Host + context.HttpContext.Request.PathBase + context.HttpContext.Request.Path |
| 56 | + }); |
| 57 | + |
| 58 | + if (result.IsError) |
| 59 | + { |
| 60 | + // fails the result |
| 61 | + context.Fail(result.ErrorDescription ?? result.Error); |
| 62 | + |
| 63 | + // we need to stash these values away so they are available later when the Challenge method is called later |
| 64 | + context.HttpContext.Items["DPoP-Error"] = result.Error; |
| 65 | + if (!string.IsNullOrWhiteSpace(result.ErrorDescription)) |
| 66 | + { |
| 67 | + context.HttpContext.Items["DPoP-ErrorDescription"] = result.ErrorDescription; |
| 68 | + } |
| 69 | + if (!string.IsNullOrWhiteSpace(result.ServerIssuedNonce)) |
| 70 | + { |
| 71 | + context.HttpContext.Items["DPoP-Nonce"] = result.ServerIssuedNonce; |
| 72 | + } |
| 73 | + } |
| 74 | + } |
| 75 | + else if (dpopOptions.Mode == DPoPMode.DPoPAndBearer) |
| 76 | + { |
| 77 | + // if the scheme used was not DPoP, then it was Bearer |
| 78 | + // and if a access token was presented with a cnf, then the |
| 79 | + // client should have sent it as DPoP, so we fail the request |
| 80 | + if (context.Principal.HasClaim(x => x.Type == JwtClaimTypes.Confirmation)) |
| 81 | + { |
| 82 | + context.HttpContext.Items["Bearer-ErrorDescription"] = "Must use DPoP when using an access token with a 'cnf' claim"; |
| 83 | + context.Fail("Must use DPoP when using an access token with a 'cnf' claim"); |
| 84 | + } |
| 85 | + } |
| 86 | + } |
| 87 | + |
| 88 | + public override Task Challenge(JwtBearerChallengeContext context) |
| 89 | + { |
| 90 | + var dpopOptions = _optionsMonitor.Get(context.Scheme.Name); |
| 91 | + |
| 92 | + if (dpopOptions.Mode == DPoPMode.DPoPOnly) |
| 93 | + { |
| 94 | + // if we are using DPoP only, then we don't need/want the default |
| 95 | + // JwtBearerHandler to add its WWW-Authenticate response header |
| 96 | + // so we have to set the status code ourselves |
| 97 | + context.Response.StatusCode = 401; |
| 98 | + context.HandleResponse(); |
| 99 | + } |
| 100 | + else if (context.HttpContext.Items.ContainsKey("Bearer-ErrorDescription")) |
| 101 | + { |
| 102 | + var description = context.HttpContext.Items["Bearer-ErrorDescription"] as string; |
| 103 | + context.ErrorDescription = description; |
| 104 | + } |
| 105 | + |
| 106 | + if (context.HttpContext.Request.IsDPoPAuthorizationScheme()) |
| 107 | + { |
| 108 | + // if we are challening due to dpop, then don't allow bearer www-auth to emit an error |
| 109 | + context.Error = null; |
| 110 | + } |
| 111 | + |
| 112 | + // now we always want to add our WWW-Authenticate for DPoP |
| 113 | + // For example: |
| 114 | + // WWW-Authenticate: DPoP error="invalid_dpop_proof", error_description="Invalid 'iat' value." |
| 115 | + var sb = new StringBuilder(); |
| 116 | + sb.Append(OidcConstants.AuthenticationSchemes.AuthorizationHeaderDPoP); |
| 117 | + |
| 118 | + if (context.HttpContext.Items.ContainsKey("DPoP-Error")) |
| 119 | + { |
| 120 | + var error = context.HttpContext.Items["DPoP-Error"] as string; |
| 121 | + sb.Append(" error=\""); |
| 122 | + sb.Append(error); |
| 123 | + sb.Append('\"'); |
| 124 | + |
| 125 | + if (context.HttpContext.Items.ContainsKey("DPoP-ErrorDescription")) |
| 126 | + { |
| 127 | + var description = context.HttpContext.Items["DPoP-ErrorDescription"] as string; |
| 128 | + |
| 129 | + sb.Append(", error_description=\""); |
| 130 | + sb.Append(description); |
| 131 | + sb.Append('\"'); |
| 132 | + } |
| 133 | + } |
| 134 | + |
| 135 | + context.Response.Headers.Append(HeaderNames.WWWAuthenticate, sb.ToString()); |
| 136 | + |
| 137 | + |
| 138 | + if (context.HttpContext.Items.ContainsKey("DPoP-Nonce")) |
| 139 | + { |
| 140 | + var nonce = context.HttpContext.Items["DPoP-Nonce"] as string; |
| 141 | + context.Response.Headers[HttpHeaders.DPoPNonce] = nonce; |
| 142 | + } |
| 143 | + else |
| 144 | + { |
| 145 | + var nonce = context.Properties.GetDPoPNonce(); |
| 146 | + if (nonce != null) |
| 147 | + { |
| 148 | + context.Response.Headers[HttpHeaders.DPoPNonce] = nonce; |
| 149 | + } |
| 150 | + } |
| 151 | + |
| 152 | + return Task.CompletedTask; |
| 153 | + } |
| 154 | +} |
0 commit comments