|
| 1 | +// Copyright (c) Brock Allen & Dominick Baier. All rights reserved. |
| 2 | +// Licensed under the Apache License, Version 2.0. See LICENSE in the project root for license information. |
| 3 | + |
| 4 | +using Microsoft.AspNetCore.Authentication; |
| 5 | +using Microsoft.AspNetCore.Http; |
| 6 | +using Microsoft.Extensions.Logging; |
| 7 | +using System.Net; |
| 8 | +using System.Net.Http; |
| 9 | +using System.Threading; |
| 10 | +using System.Threading.Tasks; |
| 11 | + |
| 12 | +namespace Duende.AccessTokenManagement.OpenIdConnect; |
| 13 | + |
| 14 | +/// <summary> |
| 15 | +/// Delegating handler that adds behavior needed for DPoP to the backchannel |
| 16 | +/// http client of the OIDC authentication handler. |
| 17 | +/// |
| 18 | +/// This handler has two main jobs: |
| 19 | +/// |
| 20 | +/// 1. Store new nonces from successful responses from the authorization server. |
| 21 | +/// |
| 22 | +/// 2. Attach proof tokens to token requests in the code flow. |
| 23 | +/// |
| 24 | +/// On the authorize request, we will have sent a dpop_jkt parameter with a |
| 25 | +/// key thumbprint. The AS expects that we will use the corresponding key to |
| 26 | +/// create our proof, and we track that key in the http context. This handler |
| 27 | +/// retrieves that key and uses it to create proof tokens for use in the code |
| 28 | +/// flow. |
| 29 | +/// |
| 30 | +/// Additionally, the token endpoint might respond to a token exchange |
| 31 | +/// request with a request to retry with a nonce that it supplies via http |
| 32 | +/// header. When it does, this handler retries those code exchange requests. |
| 33 | +/// |
| 34 | +/// </summary> |
| 35 | +internal class AuthorizationServerDPoPHandler : DelegatingHandler |
| 36 | +{ |
| 37 | + private readonly IDPoPProofService _dPoPProofService; |
| 38 | + private readonly IDPoPNonceStore _dPoPNonceStore; |
| 39 | + private readonly IHttpContextAccessor _httpContextAccessor; |
| 40 | + private readonly ILogger<AuthorizationServerDPoPHandler> _logger; |
| 41 | + |
| 42 | + internal AuthorizationServerDPoPHandler( |
| 43 | + IDPoPProofService dPoPProofService, |
| 44 | + IDPoPNonceStore dPoPNonceStore, |
| 45 | + IHttpContextAccessor httpContextAccessor, |
| 46 | + ILoggerFactory loggerFactory) |
| 47 | + { |
| 48 | + _dPoPProofService = dPoPProofService; |
| 49 | + _dPoPNonceStore = dPoPNonceStore; |
| 50 | + _httpContextAccessor = httpContextAccessor; |
| 51 | + // We depend on the logger factory, rather than the logger itself, since |
| 52 | + // the type parameter of the logger (referencing this class) will not |
| 53 | + // always be accessible. |
| 54 | + _logger = loggerFactory.CreateLogger<AuthorizationServerDPoPHandler>(); |
| 55 | + } |
| 56 | + |
| 57 | + /// <inheritdoc/> |
| 58 | + protected override async Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken) |
| 59 | + { |
| 60 | + var codeExchangeJwk = _httpContextAccessor.HttpContext?.GetCodeExchangeDPoPKey(); |
| 61 | + if (codeExchangeJwk != null) |
| 62 | + { |
| 63 | + await SetDPoPProofTokenForCodeExchangeAsync(request, jwk: codeExchangeJwk).ConfigureAwait(false); |
| 64 | + } |
| 65 | + |
| 66 | + var response = await base.SendAsync(request, cancellationToken).ConfigureAwait(false); |
| 67 | + |
| 68 | + // The authorization server might send us a new nonce on either a success or failure |
| 69 | + var dPoPNonce = response.GetDPoPNonce(); |
| 70 | + |
| 71 | + if (dPoPNonce != null) |
| 72 | + { |
| 73 | + // This handler contains specialized logic to create the new proof |
| 74 | + // token using the proof key that was associated with a code flow |
| 75 | + // using a dpop_jkt parameter on the authorize call. Other flows |
| 76 | + // (such as refresh), are separately responsible for retrying with a |
| 77 | + // server-issued nonce. So, we ONLY do the retry logic when we have |
| 78 | + // the dpop_jkt's jwk |
| 79 | + if (codeExchangeJwk != null) |
| 80 | + { |
| 81 | + // If the http response code indicates a bad request, we can infer |
| 82 | + // that we should retry with the new nonce. |
| 83 | + // |
| 84 | + // The server should have also set the error: use_dpop_nonce, but |
| 85 | + // there's no need to incur the cost of parsing the json and |
| 86 | + // checking for that, as we would only receive the nonce http header |
| 87 | + // when that error was set. Authorization servers might preemptively |
| 88 | + // send a new nonce, but the spec specifically says to do that on a |
| 89 | + // success (and we handle that case in the else block). |
| 90 | + // |
| 91 | + // TL;DR - presence of nonce and 400 response code is enough to |
| 92 | + // trigger a retry during code exchange |
| 93 | + if (response.StatusCode == HttpStatusCode.BadRequest) |
| 94 | + { |
| 95 | + _logger.LogDebug("Token request failed with DPoP nonce error. Retrying with new nonce."); |
| 96 | + response.Dispose(); |
| 97 | + await SetDPoPProofTokenForCodeExchangeAsync(request, dPoPNonce, codeExchangeJwk).ConfigureAwait(false); |
| 98 | + return await base.SendAsync(request, cancellationToken).ConfigureAwait(false); |
| 99 | + } |
| 100 | + } |
| 101 | + |
| 102 | + if (response.StatusCode == HttpStatusCode.OK) |
| 103 | + { |
| 104 | + _logger.LogDebug("The authorization server has supplied a new nonce on a successful response, which will be stored and used in future requests to the authorization server"); |
| 105 | + |
| 106 | + await _dPoPNonceStore.StoreNonceAsync(new DPoPNonceContext |
| 107 | + { |
| 108 | + Url = request.GetDPoPUrl(), |
| 109 | + Method = request.Method.ToString(), |
| 110 | + }, dPoPNonce); |
| 111 | + } |
| 112 | + } |
| 113 | + |
| 114 | + return response; |
| 115 | + } |
| 116 | + |
| 117 | + /// <summary> |
| 118 | + /// Creates a DPoP proof token and attaches it to a request. |
| 119 | + /// </summary> |
| 120 | + internal async Task SetDPoPProofTokenForCodeExchangeAsync(HttpRequestMessage request, string? dpopNonce = null, string? jwk = null) |
| 121 | + { |
| 122 | + if (!string.IsNullOrEmpty(jwk)) |
| 123 | + { |
| 124 | + // remove any old headers |
| 125 | + request.ClearDPoPProofToken(); |
| 126 | + |
| 127 | + // create proof |
| 128 | + var proofToken = await _dPoPProofService.CreateProofTokenAsync(new DPoPProofRequest |
| 129 | + { |
| 130 | + Url = request.GetDPoPUrl(), |
| 131 | + Method = request.Method.ToString(), |
| 132 | + DPoPJsonWebKey = jwk, |
| 133 | + DPoPNonce = dpopNonce, |
| 134 | + }); |
| 135 | + |
| 136 | + if (proofToken != null) |
| 137 | + { |
| 138 | + _logger.LogDebug("Sending DPoP proof token in request to endpoint: {url}", |
| 139 | + request.RequestUri?.GetLeftPart(System.UriPartial.Path)); |
| 140 | + request.SetDPoPProofToken(proofToken.ProofToken); |
| 141 | + } |
| 142 | + else |
| 143 | + { |
| 144 | + _logger.LogDebug("No DPoP proof token in request to endpoint: {url}", |
| 145 | + request.RequestUri?.GetLeftPart(System.UriPartial.Path)); |
| 146 | + } |
| 147 | + } |
| 148 | + } |
| 149 | +} |
0 commit comments