-
Notifications
You must be signed in to change notification settings - Fork 103
/
Copy pathAuthenticationHelper.cs
89 lines (78 loc) · 3.23 KB
/
AuthenticationHelper.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
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IdentityModel.Tokens.Jwt;
using System.Linq;
using System.Security.Claims;
using System.Text;
using Microsoft.Azure.SignalR.Common;
using Microsoft.IdentityModel.Tokens;
namespace Microsoft.Azure.SignalR
{
internal static class AuthenticationHelper
{
private const int MaxTokenLength = 4096;
private static readonly JwtSecurityTokenHandler JwtTokenHandler = new JwtSecurityTokenHandler();
public static string GenerateJwtBearer(
string issuer = null,
string audience = null,
IEnumerable<Claim> claims = null,
DateTime? expires = null,
string signingKey = null,
DateTime? issuedAt = null,
DateTime? notBefore = null)
{
var subject = claims == null ? null : new ClaimsIdentity(claims);
return GenerateJwtBearer(issuer, audience, subject, expires, signingKey, issuedAt, notBefore);
}
public static string GenerateAccessToken(string signingKey, string audience, IEnumerable<Claim> claims, TimeSpan lifetime)
{
var expire = DateTime.UtcNow.Add(lifetime);
var jwtToken = GenerateJwtBearer(
audience: audience,
claims: claims,
expires: expire,
signingKey: signingKey
);
if (jwtToken.Length > MaxTokenLength)
{
throw new AzureSignalRAccessTokenTooLongException();
}
return jwtToken;
}
public static string GenerateRequestId()
{
return Convert.ToBase64String(BitConverter.GetBytes(Stopwatch.GetTimestamp()));
}
private static string GenerateJwtBearer(
string issuer = null,
string audience = null,
ClaimsIdentity subject = null,
DateTime? expires = null,
string signingKey = null,
DateTime? issuedAt = null,
DateTime? notBefore = null)
{
SigningCredentials credentials = null;
if (!string.IsNullOrEmpty(signingKey))
{
// Refer: https://github.com/AzureAD/azure-activedirectory-identitymodel-extensions-for-dotnet/releases/tag/5.5.0
// From version 5.5.0, SignatureProvider caching is turned On by default, assign KeyId to enable correct cache for same SigningKey
var securityKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(signingKey));
securityKey.KeyId = signingKey;
credentials = new SigningCredentials(securityKey, SecurityAlgorithms.HmacSha256);
}
var token = JwtTokenHandler.CreateJwtSecurityToken(
issuer: issuer,
audience: audience,
subject: subject,
notBefore: notBefore,
expires: expires,
issuedAt: issuedAt,
signingCredentials: credentials);
return JwtTokenHandler.WriteToken(token);
}
}
}