0

I want to implement the Authorization for my project. It would be a custom authorization where admins can create roles and assign to users. The authorization is simple at the page level, either a user has access to page or not. Now can somebody suggest which is a best place to write the code for authorizing users - Global.asax or HttpModule? or somewhere else?

I have a Session variable which I need to access while authorizing users. I tried writing code in Application_AuthenticateRequest(Globaal.asax) but found that session is inaccessible in it. After googling, I found Application_PreRequestHandlerExecute is a safe place for Session to be accessible in Global.asax. So my question is that if Application_PreRequestHandlerExecute is called for each and every Request? and a safe place to write code for authorization? At times, I have noticed the Session is null in this event too.

4

2 回答 2

0

这是一个教程,向您展示如何从头开始构建类似 WSAT 的工具:

滚动您自己的网站管理工具 - 第 1 部分

这是做同样事情的另一个教程来源:

如何使用 ASP.NET 成员资格和角色处理 Web 窗体应用程序中的安全性和授权。

于 2013-10-15T18:54:33.620 回答
0

我将使用 ASP.NET 的 HttpModule 实现一个过滤器,然后在 Web.config 中对其进行配置。

过滤器可以检查页面的 URL 以及当前登录的用户(和角色...),然后决定是否允许请求通过。

示例代码:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Collections.Specialized;
using Axiomatics.Security.AccessControl.Protocols.Xacml;

namespace axiomatics
{
    public class AuthZHttpModule : IHttpModule
    {

        public void Dispose()
        {
        }

        public void Init(HttpApplication context)
        {
            // context.BeginRequest += new EventHandler(OnBeginRequest);
            context.AuthenticateRequest += new EventHandler(onAuthenticateRequest);

        }

        public void onAuthenticateRequest(Object s, EventArgs e)
        {
            HttpApplication app = s as HttpApplication;
            // HttpModule called - let's check the current situation
            Global g = (Global)s;
            String username = "";
            if (g.User!=null && g.User.Identity!=null){
                username = g.User.Identity.Name;
            }
            string requestUrl = g.Request.Url.LocalPath;
            // Only protect .aspx pages
            if (requestUrl.EndsWith("aspx")){
                AuthorizationDecision decision = PDPUtil.pageAuthorized(username, g.Request);

                bool grantPageAccess = decision.Decision == Decision.Permit;
                if (grantPageAccess == false)
                {       
                    g.Response.Redirect("/error.aspx");
                }
            }
        }
    }
}

在示例代码中,我使用 XACML 驱动的授权引擎 ( PDPUtil.pageAuthorized()) 来确定是否应该授予访问权限。

如果您愿意,可以用您自己的逻辑替换 XACML 部分。

于 2013-10-16T12:06:13.740 回答