forked from NancyFx/Nancy
-
Notifications
You must be signed in to change notification settings - Fork 9
/
Copy pathStatelessAuthentication.cs
83 lines (71 loc) · 2.88 KB
/
StatelessAuthentication.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
namespace Nancy.Authentication.Stateless
{
using System;
using Nancy.Bootstrapper;
/// <summary>
/// Nancy stateless authentication implementation
/// </summary>
public static class StatelessAuthentication
{
/// <summary>
/// Enables stateless authentication for the application
/// </summary>
/// <param name="pipelines">Pipelines to add handlers to (usually "this")</param>
/// <param name="configuration">Stateless authentication configuration</param>
public static void Enable(IPipelines pipelines, StatelessAuthenticationConfiguration configuration)
{
if (pipelines == null)
{
throw new ArgumentNullException("pipelines");
}
if (configuration == null)
{
throw new ArgumentNullException("configuration");
}
if (!configuration.IsValid)
{
throw new ArgumentException("Configuration is invalid", "configuration");
}
pipelines.BeforeRequest.AddItemToStartOfPipeline(GetLoadAuthenticationHook(configuration));
}
/// <summary>
/// Enables stateless authentication for a module
/// </summary>
/// <param name="module">Module to add handlers to (usually "this")</param>
/// <param name="configuration">Stateless authentication configuration</param>
public static void Enable(INancyModule module, StatelessAuthenticationConfiguration configuration)
{
if (module == null)
{
throw new ArgumentNullException("module");
}
if (configuration == null)
{
throw new ArgumentNullException("configuration");
}
if (!configuration.IsValid)
{
throw new ArgumentException("Configuration is invalid", "configuration");
}
module.Before.AddItemToStartOfPipeline(GetLoadAuthenticationHook(configuration));
}
/// <summary>
/// Gets the pre request hook for loading the authenticated user's details
/// from apikey given in request.
/// </summary>
/// <param name="configuration">Stateless authentication configuration to use</param>
/// <returns>Pre request hook delegate</returns>
private static Func<NancyContext, Response> GetLoadAuthenticationHook(StatelessAuthenticationConfiguration configuration)
{
if (configuration == null)
{
throw new ArgumentNullException("configuration");
}
return context =>
{
context.CurrentUser = configuration.GetUserIdentity(context);
return null;
};
}
}
}