Skip to content

Commit d9496fe

Browse files
authored
Init file from workplace-solution
Added files created while at work
0 parents  commit d9496fe

File tree

1 file changed

+57
-0
lines changed

1 file changed

+57
-0
lines changed

AuthorizationHttpModule.cs

Lines changed: 57 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,57 @@
1+
using System;
2+
using System.Reflection;
3+
using System.Web;
4+
using System.Web.Compilation;
5+
using System.Web.Security;
6+
using System.Web.UI;
7+
8+
[AttributeUsage(AttributeTargets.Method | AttributeTargets.Class)]
9+
public class RequiresAuthenticationAttribute : Attribute { }
10+
11+
public class AttributeBasedFormsAuthenticationModule : IHttpModule {
12+
public void Init(HttpApplication application) {
13+
application.PostMapRequestHandler += OnPostAuthorizeRequest;
14+
}
15+
16+
public void Dispose() {
17+
// Clean up resources, if any
18+
}
19+
20+
private void OnPostAuthorizeRequest(object sender, EventArgs e) {
21+
var app = (HttpApplication)sender;
22+
var context = app.Context;
23+
var request = context.Request;
24+
25+
if (context.Handler is Page page) {
26+
if (page?.GetType().GetCustomAttribute<RequiresAuthenticationAttribute>() != null) {
27+
if (!request.IsAuthenticated || request.Cookies[FormsAuthentication.FormsCookieName] == null) {
28+
DenyAccess(context);
29+
}
30+
}
31+
if (request.HttpMethod == "POST") {
32+
var methodName = GetWebMethodNameFromRequest(request);
33+
if (!string.IsNullOrEmpty(methodName)) {
34+
var pageType = page?.GetType();
35+
var methodInfo = pageType?.GetMethod(methodName, BindingFlags.Public | BindingFlags.Static | BindingFlags.FlattenHierarchy);
36+
if (methodInfo?.GetCustomAttribute<RequiresAuthenticationAttribute>() != null) {
37+
if (!request.IsAuthenticated || request.Cookies[FormsAuthentication.FormsCookieName] == null) {
38+
DenyAccess(context);
39+
}
40+
}
41+
}
42+
}
43+
}
44+
}
45+
46+
private static void DenyAccess(HttpContext context) {
47+
context.Response.StatusCode = 401;
48+
context.Response.SuppressContent = true;
49+
context.Response.End();
50+
}
51+
52+
private static string GetWebMethodNameFromRequest(HttpRequest request) {
53+
var pathInfo = request.PathInfo.TrimStart('/');
54+
var slashIndex = pathInfo.IndexOf('/');
55+
return slashIndex >= 0 ? pathInfo.Substring(0, slashIndex) : pathInfo;
56+
}
57+
}

0 commit comments

Comments
 (0)