| | 1 | | // Copyright (c) Microsoft Corporation. All rights reserved. |
| | 2 | | // Licensed under the MIT License. |
| | 3 | |
|
| | 4 | | using Azure.Core; |
| | 5 | | using Azure.Core.Pipeline; |
| | 6 | | using System; |
| | 7 | | using System.IO; |
| | 8 | | using System.Security.Cryptography; |
| | 9 | | using System.Security.Cryptography.X509Certificates; |
| | 10 | | using System.Text; |
| | 11 | | using System.Text.Json; |
| | 12 | | using System.Threading; |
| | 13 | | using System.Threading.Tasks; |
| | 14 | | using Azure.Core.Diagnostics; |
| | 15 | |
|
| | 16 | | namespace Azure.Identity |
| | 17 | | { |
| | 18 | | internal class AadIdentityClient |
| | 19 | | { |
| | 20 | | private const string ClientAssertionType = "urn:ietf:params:oauth:client-assertion-type:jwt-bearer"; |
| | 21 | |
|
| | 22 | | private readonly CredentialPipeline _pipeline; |
| | 23 | |
|
| 4 | 24 | | protected AadIdentityClient() |
| | 25 | | { |
| 4 | 26 | | } |
| | 27 | |
|
| 0 | 28 | | public AadIdentityClient(CredentialPipeline pipeline) |
| | 29 | | { |
| 0 | 30 | | _pipeline = pipeline; |
| 0 | 31 | | } |
| | 32 | |
|
| | 33 | | public virtual async Task<AccessToken> AuthenticateAsync(string tenantId, string clientId, string clientSecret, |
| | 34 | | { |
| 0 | 35 | | using Request request = CreateClientSecretAuthRequest(tenantId, clientId, clientSecret, scopes); |
| | 36 | |
|
| 0 | 37 | | return await SendAuthRequestAsync(request, cancellationToken).ConfigureAwait(false); |
| 0 | 38 | | } |
| | 39 | |
|
| | 40 | | public virtual AccessToken Authenticate(string tenantId, string clientId, string clientSecret, string[] scopes, |
| | 41 | | { |
| 0 | 42 | | using Request request = CreateClientSecretAuthRequest(tenantId, clientId, clientSecret, scopes); |
| | 43 | |
|
| 0 | 44 | | return SendAuthRequest(request, cancellationToken); |
| 0 | 45 | | } |
| | 46 | |
|
| | 47 | | public virtual async Task<AccessToken> AuthenticateAsync(string tenantId, string clientId, X509Certificate2 clie |
| | 48 | | { |
| 0 | 49 | | using Request request = CreateClientCertificateAuthRequest(tenantId, clientId, clientCertificate, scopes); |
| | 50 | |
|
| 0 | 51 | | return await SendAuthRequestAsync(request, cancellationToken).ConfigureAwait(false); |
| 0 | 52 | | } |
| | 53 | |
|
| | 54 | | public virtual AccessToken Authenticate(string tenantId, string clientId, X509Certificate2 clientCertificate, st |
| | 55 | | { |
| 0 | 56 | | using Request request = CreateClientCertificateAuthRequest(tenantId, clientId, clientCertificate, scopes); |
| | 57 | |
|
| 0 | 58 | | return SendAuthRequest(request, cancellationToken); |
| 0 | 59 | | } |
| | 60 | |
|
| | 61 | | private async Task<AccessToken> SendAuthRequestAsync(Request request, CancellationToken cancellationToken) |
| | 62 | | { |
| 0 | 63 | | Response response = await _pipeline.HttpPipeline.SendRequestAsync(request, cancellationToken).ConfigureAwait |
| | 64 | |
|
| 0 | 65 | | if (response.Status == 200 || response.Status == 201) |
| | 66 | | { |
| 0 | 67 | | AccessToken result = await DeserializeAsync(response.ContentStream, cancellationToken).ConfigureAwait(fa |
| | 68 | |
|
| 0 | 69 | | return Response.FromValue(result, response); |
| | 70 | | } |
| | 71 | |
|
| 0 | 72 | | throw await _pipeline.Diagnostics.CreateRequestFailedExceptionAsync(response).ConfigureAwait(false); |
| 0 | 73 | | } |
| | 74 | |
|
| | 75 | | private AccessToken SendAuthRequest(Request request, CancellationToken cancellationToken) |
| | 76 | | { |
| 0 | 77 | | Response response = _pipeline.HttpPipeline.SendRequest(request, cancellationToken); |
| | 78 | |
|
| 0 | 79 | | if (response.Status == 200 || response.Status == 201) |
| | 80 | | { |
| 0 | 81 | | AccessToken result = Deserialize(response.ContentStream); |
| | 82 | |
|
| 0 | 83 | | return Response.FromValue(result, response); |
| | 84 | | } |
| | 85 | |
|
| 0 | 86 | | throw _pipeline.Diagnostics.CreateRequestFailedException(response); |
| | 87 | | } |
| | 88 | |
|
| | 89 | | private Request CreateClientSecretAuthRequest(string tenantId, string clientId, string clientSecret, string[] sc |
| | 90 | | { |
| 0 | 91 | | Request request = _pipeline.HttpPipeline.CreateRequest(); |
| | 92 | |
|
| 0 | 93 | | request.Method = RequestMethod.Post; |
| | 94 | |
|
| 0 | 95 | | request.Headers.Add(HttpHeader.Common.FormUrlEncodedContentType); |
| | 96 | |
|
| 0 | 97 | | request.Uri.Reset(_pipeline.AuthorityHost); |
| | 98 | |
|
| 0 | 99 | | request.Uri.AppendPath(tenantId); |
| | 100 | |
|
| 0 | 101 | | request.Uri.AppendPath("/oauth2/v2.0/token", escape: false); |
| | 102 | |
|
| 0 | 103 | | var bodyStr = $"response_type=token&grant_type=client_credentials&client_id={Uri.EscapeDataString(clientId)} |
| | 104 | |
|
| 0 | 105 | | ReadOnlyMemory<byte> content = Encoding.UTF8.GetBytes(bodyStr).AsMemory(); |
| | 106 | |
|
| 0 | 107 | | request.Content = RequestContent.Create(content); |
| | 108 | |
|
| 0 | 109 | | return request; |
| | 110 | | } |
| | 111 | |
|
| | 112 | | private Request CreateClientCertificateAuthRequest(string tenantId, string clientId, X509Certificate2 clientCert |
| | 113 | | { |
| 0 | 114 | | Request request = _pipeline.HttpPipeline.CreateRequest(); |
| | 115 | |
|
| 0 | 116 | | request.Method = RequestMethod.Post; |
| | 117 | |
|
| 0 | 118 | | request.Headers.Add(HttpHeader.Common.FormUrlEncodedContentType); |
| | 119 | |
|
| 0 | 120 | | request.Uri.Reset(_pipeline.AuthorityHost); |
| | 121 | |
|
| 0 | 122 | | request.Uri.AppendPath(tenantId); |
| | 123 | |
|
| 0 | 124 | | request.Uri.AppendPath("/oauth2/v2.0/token", escape: false); |
| | 125 | |
|
| 0 | 126 | | string clientAssertion = CreateClientAssertionJWT(clientId, request.Uri.ToString(), clientCertficate); |
| | 127 | |
|
| 0 | 128 | | var bodyStr = $"response_type=token&grant_type=client_credentials&client_id={Uri.EscapeDataString(clientId)} |
| | 129 | |
|
| 0 | 130 | | ReadOnlyMemory<byte> content = Encoding.UTF8.GetBytes(bodyStr).AsMemory(); |
| | 131 | |
|
| 0 | 132 | | request.Content = RequestContent.Create(content); |
| | 133 | |
|
| 0 | 134 | | return request; |
| | 135 | | } |
| | 136 | |
|
| | 137 | | private static string CreateClientAssertionJWT(string clientId, string audience, X509Certificate2 clientCertific |
| | 138 | | { |
| 0 | 139 | | var headerBuff = new ArrayBufferWriter<byte>(); |
| | 140 | |
|
| 0 | 141 | | using (var headerJson = new Utf8JsonWriter(headerBuff)) |
| | 142 | | { |
| 0 | 143 | | headerJson.WriteStartObject(); |
| | 144 | |
|
| 0 | 145 | | headerJson.WriteString("typ", "JWT"); |
| 0 | 146 | | headerJson.WriteString("alg", "RS256"); |
| 0 | 147 | | headerJson.WriteString("x5t", Base64Url.HexToBase64Url(clientCertificate.Thumbprint)); |
| | 148 | |
|
| 0 | 149 | | headerJson.WriteEndObject(); |
| | 150 | |
|
| 0 | 151 | | headerJson.Flush(); |
| 0 | 152 | | } |
| | 153 | |
|
| 0 | 154 | | var payloadBuff = new ArrayBufferWriter<byte>(); |
| | 155 | |
|
| 0 | 156 | | using (var payloadJson = new Utf8JsonWriter(payloadBuff)) |
| | 157 | | { |
| 0 | 158 | | payloadJson.WriteStartObject(); |
| | 159 | |
|
| 0 | 160 | | payloadJson.WriteString("jti", Guid.NewGuid()); |
| 0 | 161 | | payloadJson.WriteString("aud", audience); |
| 0 | 162 | | payloadJson.WriteString("iss", clientId); |
| 0 | 163 | | payloadJson.WriteString("sub", clientId); |
| 0 | 164 | | payloadJson.WriteNumber("nbf", DateTimeOffset.UtcNow.ToUnixTimeSeconds()); |
| 0 | 165 | | payloadJson.WriteNumber("exp", (DateTimeOffset.UtcNow + TimeSpan.FromMinutes(30)).ToUnixTimeSeconds()); |
| | 166 | |
|
| 0 | 167 | | payloadJson.WriteEndObject(); |
| | 168 | |
|
| 0 | 169 | | payloadJson.Flush(); |
| 0 | 170 | | } |
| | 171 | |
|
| 0 | 172 | | string header = Base64Url.Encode(headerBuff.WrittenMemory.ToArray()); |
| | 173 | |
|
| 0 | 174 | | string payload = Base64Url.Encode(payloadBuff.WrittenMemory.ToArray()); |
| | 175 | |
|
| 0 | 176 | | string flattenedJws = header + "." + payload; |
| | 177 | |
|
| 0 | 178 | | byte[] signature = clientCertificate.GetRSAPrivateKey().SignData(Encoding.ASCII.GetBytes(flattenedJws), Hash |
| | 179 | |
|
| 0 | 180 | | return flattenedJws + "." + Base64Url.Encode(signature); |
| | 181 | | } |
| | 182 | |
|
| | 183 | | private static async Task<AccessToken> DeserializeAsync(Stream content, CancellationToken cancellationToken) |
| | 184 | | { |
| 0 | 185 | | using (JsonDocument json = await JsonDocument.ParseAsync(content, default, cancellationToken).ConfigureAwait |
| | 186 | | { |
| 0 | 187 | | return Deserialize(json.RootElement); |
| | 188 | | } |
| 0 | 189 | | } |
| | 190 | |
|
| | 191 | | private static AccessToken Deserialize(Stream content) |
| | 192 | | { |
| 0 | 193 | | using (JsonDocument json = JsonDocument.Parse(content)) |
| | 194 | | { |
| 0 | 195 | | return Deserialize(json.RootElement); |
| | 196 | | } |
| 0 | 197 | | } |
| | 198 | |
|
| | 199 | | private static AccessToken Deserialize(JsonElement json) |
| | 200 | | { |
| 0 | 201 | | string accessToken = null; |
| | 202 | |
|
| 0 | 203 | | DateTimeOffset expiresOn = DateTimeOffset.MaxValue; |
| | 204 | |
|
| 0 | 205 | | foreach (JsonProperty prop in json.EnumerateObject()) |
| | 206 | | { |
| 0 | 207 | | switch (prop.Name) |
| | 208 | | { |
| | 209 | | case "access_token": |
| 0 | 210 | | accessToken = prop.Value.GetString(); |
| 0 | 211 | | break; |
| | 212 | |
|
| | 213 | | case "expires_in": |
| 0 | 214 | | expiresOn = DateTimeOffset.UtcNow + TimeSpan.FromSeconds(prop.Value.GetInt64()); |
| | 215 | | break; |
| | 216 | | } |
| | 217 | | } |
| | 218 | |
|
| 0 | 219 | | return new AccessToken(accessToken, expiresOn); |
| | 220 | | } |
| | 221 | | } |
| | 222 | | } |