-
Notifications
You must be signed in to change notification settings - Fork 2
/
TokenAuthenticator.cs
53 lines (49 loc) · 1.56 KB
/
TokenAuthenticator.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
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Http;
using System.Text;
using System.Threading.Tasks;
using System.Web.Http.Controllers;
namespace SethWebster.WebApi.TokenAuthentication
{
internal sealed class TokenAuthenticator
{
private readonly string _authorizationHeaderKey = "Authorization";
public bool Authenticate(HttpActionContext actionContext, ITokenAuthenticator authenticator)
{
string token = string.Empty;
try
{
token = actionContext.Request.Headers.GetValues(_authorizationHeaderKey).First();
}
catch (Exception)
{
actionContext.Response = new HttpResponseMessage(System.Net.HttpStatusCode.BadRequest)
{
Content = new StringContent("Missing Authorization Header (" + _authorizationHeaderKey + ")")
};
return false;
}
try
{
if (authenticator.Authenticate(token, actionContext))
{
return true;
}
else
{
throw new Exception();
}
}
catch (Exception e)
{
actionContext.Response = new HttpResponseMessage(System.Net.HttpStatusCode.Unauthorized)
{
Content = new StringContent("Unauthorized User")
};
return false;
}
}
}
}