This repository was archived by the owner on Dec 14, 2017. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathOAuthClaimsModule.cs
95 lines (87 loc) · 2.82 KB
/
OAuthClaimsModule.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
90
91
92
93
94
95
using System;
using System.Collections.Generic;
using System.Linq;
using System.Security.Claims;
using System.Text;
using System.Threading.Tasks;
using System.Web;
using System.Web.Security;
namespace BrockAllen.WebSecurityClaimsHelper
{
public class OAuthClaimsModule : IHttpModule
{
ClaimsCookieHelper cookieHelper = new ClaimsCookieHelper();
public void Init(HttpApplication context)
{
context.PostAuthenticateRequest += OnEnter;
context.EndRequest += OnLeave;
}
void OnEnter(object sender, EventArgs e)
{
CheckForClaimsCookie();
}
private void CheckForClaimsCookie()
{
var principal = ClaimsPrincipal.Current;
if (principal != null)
{
var ctx = HttpContext.Current;
if (ctx != null)
{
var claims = cookieHelper.Read(ctx);
if (claims != null)
{
var id = new ClaimsIdentity(claims);
principal.AddIdentity(id);
}
}
}
}
void OnLeave(object sender, EventArgs e)
{
var ctx = HttpContext.Current;
if (ctx != null)
{
CheckForFormsLogin(ctx);
CheckForFormsLogout(ctx);
}
}
private void CheckForFormsLogout(HttpContext ctx)
{
if (ctx.User != null &&
ctx.User.Identity != null &&
ctx.User.Identity.IsAuthenticated)
{
if (ctx.Response.Cookies.AllKeys.Contains(FormsAuthentication.FormsCookieName))
{
var logoutCookie = ctx.Response.Cookies[FormsAuthentication.FormsCookieName];
if (logoutCookie != null)
{
var now = DateTime.UtcNow;
if (DateTime.MinValue < logoutCookie.Expires && logoutCookie.Expires < now)
{
cookieHelper.RemoveCookie(ctx);
}
}
}
}
}
private void CheckForFormsLogin(HttpContext ctx)
{
if (ctx.User == null ||
ctx.User.Identity == null ||
!ctx.User.Identity.IsAuthenticated)
{
var formsUsername = ClaimsCookieHelper.ExtractUsernameFromFormsCookie();
if (!String.IsNullOrWhiteSpace(formsUsername))
{
var claims = cookieHelper.Read(ctx);
cookieHelper.Write(ctx, formsUsername, claims);
}
}
}
public void Dispose()
{
}
}
}