-
Notifications
You must be signed in to change notification settings - Fork 0
/
TokenAuthUserResolver.cs
62 lines (51 loc) · 1.81 KB
/
TokenAuthUserResolver.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
using System;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
using System.Security.Claims;
using System.Text.RegularExpressions;
using Sitecore;
using Sitecore.Pipelines.HttpRequest;
using Sitecore.Security.Authentication;
using Sitecore.Services.Infrastructure.Web.Http.Security;
namespace MyWebsite
{
[ExcludeFromCodeCoverage]
public class TokenAuthUserResolver : HttpRequestProcessor
{
private readonly ITokenProvider _tokenProvider;
public TokenAuthUserResolver(ITokenProvider tokenProvider)
{
_tokenProvider = tokenProvider;
}
public override void Process(HttpRequestArgs args)
{
if (Context.IsLoggedIn)
return;
string authorize = args.HttpContext.Request.Headers["Authorization"];
if (string.IsNullOrEmpty(authorize))
return;
Match match = Regex.Match(authorize, @"^Bearer ([^\.]+\.[^\.]+\.[^\.]+)$");
if (!match.Success)
{
//Maybe log this? Someone might be trying to fuck around with auth
return;
}
try
{
Group smt = match.Groups[1];
string token = smt.Value;
ITokenValidationResult tokenResult = _tokenProvider.ValidateToken(token);
if (!tokenResult.IsValid)
return;
Claim usernameClaim = tokenResult.Claims.FirstOrDefault(x => x.Type == "MyWebsite.Username");
if (usernameClaim == null)
return;
AuthenticationManager.Login(usernameClaim.Value);
}
catch (Exception)
{
//If something threw it was not a valid token and we ignore it
}
}
}
}