This repository has been archived by the owner on Sep 2, 2022. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 23
/
Copy pathSimpleRefreshTokenProvider.cs
57 lines (49 loc) · 2.01 KB
/
SimpleRefreshTokenProvider.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
using System;
using System.Threading.Tasks;
using Microsoft.Owin.Security.Infrastructure;
using YellowNotes.Api.Models;
using YellowNotes.Api.Services;
using YellowNotes.Api.Utils;
namespace YellowNotes.Api.Providers
{
internal class SimpleRefreshTokenProvider : AuthenticationTokenProvider
{
private readonly ITokenService _tokenService;
public SimpleRefreshTokenProvider(ITokenService tokenService)
{
_tokenService = tokenService;
}
public override Task CreateAsync(AuthenticationTokenCreateContext context)
{
string userName = context.Ticket.Identity.Name;
string clientId = context.Ticket.Properties.Dictionary["as:client_id"];
string token = Guid.NewGuid().ToString("n");
var refreshToken = new RefreshTokenModel
{
ClientId = clientId,
UserName = userName,
Token = HashProvider.Get(token),
ProtectedTicket = context.SerializeTicket(),
IssuedDate = DateTime.UtcNow,
ExpiresDate = DateTime.UtcNow.AddMinutes(AppConfiguration.RefreshTokenExpireTimeInMin)
};
_tokenService.SaveRefreshToken(refreshToken);
context.Ticket.Properties.IssuedUtc = refreshToken.IssuedDate;
context.Ticket.Properties.ExpiresUtc = refreshToken.ExpiresDate;
context.SetToken(token);
return Task.CompletedTask;
}
public override Task ReceiveAsync(AuthenticationTokenReceiveContext context)
{
var token = HashProvider.Get(context.Token);
var refreshToken = _tokenService.GetRefreshToken(token);
if (refreshToken != null)
{
context.DeserializeTicket(refreshToken.ProtectedTicket);
_tokenService.RemoveRefreshToken(token);
_tokenService.RemoveExpiredRefreshTokens(refreshToken.UserName);
}
return Task.CompletedTask;
}
}
}