-
Notifications
You must be signed in to change notification settings - Fork 150
Expand file tree
/
Copy pathDataProtectorTokenProvider.cs
More file actions
192 lines (176 loc) · 6.81 KB
/
DataProtectorTokenProvider.cs
File metadata and controls
192 lines (176 loc) · 6.81 KB
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
// Copyright (c) Microsoft Corporation, Inc. All rights reserved.
// Licensed under the MIT License, Version 2.0. See License.txt in the project root for license information.
using System;
using System.Globalization;
using System.IO;
using System.Text;
using System.Threading.Tasks;
using Microsoft.Owin.Security.DataProtection;
namespace Microsoft.AspNet.Identity.Owin
{
/// <summary>
/// Token provider that uses an IDataProtector to generate encrypted tokens based off of the security stamp
/// </summary>
public class DataProtectorTokenProvider<TUser> : DataProtectorTokenProvider<TUser, string>
where TUser : class, IUser<string>
{
/// <summary>
/// Constructor
/// </summary>
/// <param name="protector"></param>
public DataProtectorTokenProvider(IDataProtector protector) : base(protector)
{
}
}
/// <summary>
/// Token provider that uses an IDataProtector to generate encrypted tokens based off of the security stamp
/// </summary>
public class DataProtectorTokenProvider<TUser, TKey> : IUserTokenProvider<TUser, TKey>
where TUser : class, IUser<TKey> where TKey : IEquatable<TKey>
{
/// <summary>
/// Constructor
/// </summary>
/// <param name="protector"></param>
public DataProtectorTokenProvider(IDataProtector protector)
{
if (protector == null)
{
throw new ArgumentNullException("protector");
}
Protector = protector;
TokenLifespan = TimeSpan.FromDays(1);
}
/// <summary>
/// IDataProtector for the token
/// </summary>
public IDataProtector Protector { get; private set; }
/// <summary>
/// Lifespan after which the token is considered expired
/// </summary>
public TimeSpan TokenLifespan { get; set; }
/// <summary>
/// Generate a protected string for a user
/// </summary>
/// <param name="purpose"></param>
/// <param name="manager"></param>
/// <param name="user"></param>
/// <returns></returns>
public async Task<string> GenerateAsync(string purpose, UserManager<TUser, TKey> manager, TUser user)
{
if (user == null)
{
throw new ArgumentNullException("user");
}
var ms = new MemoryStream();
using (var writer = ms.CreateWriter())
{
writer.Write(DateTimeOffset.UtcNow);
writer.Write(Convert.ToString(user.Id, CultureInfo.InvariantCulture));
writer.Write(purpose ?? "");
string stamp = null;
if (manager.SupportsUserSecurityStamp)
{
stamp = await manager.GetSecurityStampAsync(user.Id).WithCurrentCulture();
}
writer.Write(stamp ?? "");
}
var protectedBytes = Protector.Protect(ms.ToArray());
return Convert.ToBase64String(protectedBytes);
}
/// <summary>
/// Return false if the token is not valid
/// </summary>
/// <param name="purpose"></param>
/// <param name="token"></param>
/// <param name="manager"></param>
/// <param name="user"></param>
/// <returns></returns>
public async Task<bool> ValidateAsync(string purpose, string token, UserManager<TUser, TKey> manager, TUser user)
{
try
{
var unprotectedData = Protector.Unprotect(Convert.FromBase64String(token));
var ms = new MemoryStream(unprotectedData);
using (var reader = ms.CreateReader())
{
var creationTime = reader.ReadDateTimeOffset();
var expirationTime = creationTime + TokenLifespan;
if (expirationTime < DateTimeOffset.UtcNow)
{
return false;
}
var userId = reader.ReadString();
if (!String.Equals(userId, Convert.ToString(user.Id, CultureInfo.InvariantCulture)))
{
return false;
}
var purp = reader.ReadString();
if (!String.Equals(purp, purpose))
{
return false;
}
var stamp = reader.ReadString();
if (reader.PeekChar() != -1)
{
return false;
}
if (manager.SupportsUserSecurityStamp)
{
var expectedStamp = await manager.GetSecurityStampAsync(user.Id).WithCurrentCulture() ?? string.Empty;
return stamp == expectedStamp;
}
return stamp == "";
}
}
// ReSharper disable once EmptyGeneralCatchClause
catch
{
// Do not leak exception
}
return false;
}
/// <summary>
/// Returns true if the provider can be used to generate tokens for this user
/// </summary>
/// <param name="manager"></param>
/// <param name="user"></param>
/// <returns></returns>
public Task<bool> IsValidProviderForUserAsync(UserManager<TUser, TKey> manager, TUser user)
{
return Task.FromResult(true);
}
/// <summary>
/// This provider no-ops by default when asked to notify a user
/// </summary>
/// <param name="token"></param>
/// <param name="manager"></param>
/// <param name="user"></param>
/// <returns></returns>
public Task NotifyAsync(string token, UserManager<TUser, TKey> manager, TUser user)
{
return Task.FromResult(0);
}
}
// Based on Levi's authentication sample
internal static class StreamExtensions
{
internal static readonly Encoding DefaultEncoding = new UTF8Encoding(false, true);
public static BinaryReader CreateReader(this Stream stream)
{
return new BinaryReader(stream, DefaultEncoding, true);
}
public static BinaryWriter CreateWriter(this Stream stream)
{
return new BinaryWriter(stream, DefaultEncoding, true);
}
public static DateTimeOffset ReadDateTimeOffset(this BinaryReader reader)
{
return new DateTimeOffset(reader.ReadInt64(), TimeSpan.Zero);
}
public static void Write(this BinaryWriter writer, DateTimeOffset value)
{
writer.Write(value.UtcTicks);
}
}
}