-
Notifications
You must be signed in to change notification settings - Fork 330
/
JwtFormat.cs
248 lines (220 loc) · 10.3 KB
/
JwtFormat.cs
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
// Copyright (c) .NET Foundation. All rights reserved.
// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System;
using System.Collections.Generic;
using System.Globalization;
using System.IdentityModel.Selectors;
using System.IdentityModel.Tokens;
using System.Linq;
using System.Security.Claims;
namespace Microsoft.Owin.Security.Jwt
{
/// <summary>
/// Signs and validates JSON Web Tokens.
/// </summary>
public class JwtFormat : ISecureDataFormat<AuthenticationTicket>
{
private readonly TokenValidationParameters _validationParameters;
private readonly IEnumerable<IIssuerSecurityTokenProvider> _issuerCredentialProviders;
private JwtSecurityTokenHandler _tokenHandler;
/// <summary>
/// Creates a new JwtFormat with TokenHandler and UseTokenLifetime enabled by default.
/// </summary>
protected JwtFormat()
{
TokenHandler = new JwtSecurityTokenHandler();
UseTokenLifetime = true;
}
/// <summary>
/// Initializes a new instance of the <see cref="JwtFormat"/> class.
/// </summary>
/// <param name="allowedAudience">The allowed audience for JWTs.</param>
/// <param name="issuerCredentialProvider">The issuer credential provider.</param>
/// <exception cref="System.ArgumentNullException">Thrown if the <paramref name="issuerCredentialProvider"/> is null.</exception>
public JwtFormat(string allowedAudience, IIssuerSecurityTokenProvider issuerCredentialProvider)
: this()
{
if (string.IsNullOrWhiteSpace(allowedAudience))
{
throw new ArgumentNullException("allowedAudience");
}
if (issuerCredentialProvider == null)
{
throw new ArgumentNullException("issuerCredentialProvider");
}
_validationParameters = new TokenValidationParameters()
{
ValidAudience = allowedAudience,
AuthenticationType = "JWT",
};
_issuerCredentialProviders = new[] { issuerCredentialProvider };
}
/// <summary>
/// Initializes a new instance of the <see cref="JwtFormat"/> class.
/// </summary>
/// <param name="allowedAudiences">The allowed audience for JWTs.</param>
/// <param name="issuerCredentialProviders">The issuer credential provider.</param>
/// <exception cref="System.ArgumentNullException">Thrown if the <paramref name="issuerCredentialProviders"/> is null.</exception>
public JwtFormat(IEnumerable<string> allowedAudiences, IEnumerable<IIssuerSecurityTokenProvider> issuerCredentialProviders)
: this()
{
if (allowedAudiences == null)
{
throw new ArgumentNullException("allowedAudiences");
}
var audiences = new List<string>(allowedAudiences);
if (!audiences.Any())
{
throw new ArgumentOutOfRangeException("allowedAudiences", Properties.Resources.Exception_AudiencesMustBeSpecified);
}
if (issuerCredentialProviders == null)
{
throw new ArgumentNullException("issuerCredentialProviders");
}
var credentialProviders = new List<IIssuerSecurityTokenProvider>(issuerCredentialProviders);
if (!credentialProviders.Any())
{
throw new ArgumentOutOfRangeException("issuerCredentialProviders", Properties.Resources.Exception_IssuerCredentialProvidersMustBeSpecified);
}
_validationParameters = new TokenValidationParameters()
{
ValidAudiences = audiences,
AuthenticationType = "JWT",
};
_issuerCredentialProviders = issuerCredentialProviders;
}
/// <summary>
/// Initializes a new instance of the <see cref="JwtFormat"/> class.
/// </summary>
/// <param name="validationParameters"> <see cref="TokenValidationParameters"/> used to determine if a token is valid.</param>
/// <exception cref="System.ArgumentNullException">Thrown if the <paramref name="validationParameters"/> is null.</exception>
public JwtFormat(TokenValidationParameters validationParameters)
: this()
{
if (validationParameters == null)
{
throw new ArgumentNullException("validationParameters");
}
_validationParameters = validationParameters;
if (string.IsNullOrWhiteSpace(_validationParameters.AuthenticationType))
{
_validationParameters.AuthenticationType = "JWT";
}
}
public JwtFormat(TokenValidationParameters validationParameters, IIssuerSecurityTokenProvider issuerCredentialProvider)
: this(validationParameters)
{
if (issuerCredentialProvider == null)
{
throw new ArgumentNullException("issuerCredentialProvider");
}
_issuerCredentialProviders = new[] { issuerCredentialProvider };
}
/// <summary>
/// Gets or sets a value indicating whether JWT issuers should be validated.
/// </summary>
/// <value>
/// true if the issuer should be validate; otherwise, false.
/// </value>
public bool ValidateIssuer
{
get { return _validationParameters.ValidateIssuer; }
set { _validationParameters.ValidateIssuer = value; }
}
/// <summary>
/// A System.IdentityModel.Tokens.SecurityTokenHandler designed for creating and validating Json Web Tokens.
/// </summary>
public JwtSecurityTokenHandler TokenHandler
{
get { return _tokenHandler; }
set
{
if (value == null)
{
throw new ArgumentNullException("value");
}
_tokenHandler = value;
}
}
/// <summary>
/// Indicates that the authentication session lifetime (e.g. cookies) should match that of the authentication token.
/// If the token does not provide lifetime information then normal session lifetimes will be used.
/// This is enabled by default.
/// </summary>
public bool UseTokenLifetime { get; set; }
/// <summary>
/// Transforms the specified authentication ticket into a JWT.
/// </summary>
/// <param name="data">The authentication ticket to transform into a JWT.</param>
/// <returns></returns>
public string Protect(AuthenticationTicket data)
{
throw new NotSupportedException();
}
/// <summary>
/// Validates the specified JWT and builds an AuthenticationTicket from it.
/// </summary>
/// <param name="protectedText">The JWT to validate.</param>
/// <returns>An AuthenticationTicket built from the <paramref name="protectedText"/></returns>
/// <exception cref="System.ArgumentNullException">Thrown if the <paramref name="protectedText"/> is null.</exception>
/// <exception cref="System.ArgumentOutOfRangeException">Thrown if the <paramref name="protectedText"/> is not a JWT.</exception>
public AuthenticationTicket Unprotect(string protectedText)
{
if (string.IsNullOrWhiteSpace(protectedText))
{
throw new ArgumentNullException("protectedText");
}
var token = TokenHandler.ReadToken(protectedText) as JwtSecurityToken;
if (token == null)
{
throw new ArgumentOutOfRangeException("protectedText", Properties.Resources.Exception_InvalidJwt);
}
TokenValidationParameters validationParameters = _validationParameters;
if (_issuerCredentialProviders != null)
{
// Lazy augment with issuers and tokens. Note these may be refreshed periodically.
validationParameters = validationParameters.Clone();
IEnumerable<string> issuers = _issuerCredentialProviders.Select(provider => provider.Issuer);
if (validationParameters.ValidIssuers == null)
{
validationParameters.ValidIssuers = issuers;
}
else
{
validationParameters.ValidIssuers = validationParameters.ValidIssuers.Concat(issuers);
}
IEnumerable<SecurityToken> tokens = _issuerCredentialProviders.Select(provider => provider.SecurityTokens)
.Aggregate((left, right) => left.Concat(right));
if (validationParameters.IssuerSigningTokens == null)
{
validationParameters.IssuerSigningTokens = tokens;
}
else
{
validationParameters.IssuerSigningTokens = validationParameters.IssuerSigningTokens.Concat(tokens);
}
}
SecurityToken validatedToken;
ClaimsPrincipal claimsPrincipal = TokenHandler.ValidateToken(protectedText, validationParameters, out validatedToken);
var claimsIdentity = (ClaimsIdentity)claimsPrincipal.Identity;
// Fill out the authenticationProperties issued and expires times if the equivalent claims are in the JWT
var authenticationProperties = new AuthenticationProperties();
if (UseTokenLifetime)
{
// Override any session persistence to match the token lifetime.
DateTime issued = validatedToken.ValidFrom;
if (issued != DateTime.MinValue)
{
authenticationProperties.IssuedUtc = issued.ToUniversalTime();
}
DateTime expires = validatedToken.ValidTo;
if (expires != DateTime.MinValue)
{
authenticationProperties.ExpiresUtc = expires.ToUniversalTime();
}
authenticationProperties.AllowRefresh = false;
}
return new AuthenticationTicket(claimsIdentity, authenticationProperties);
}
}
}