如何在ASP.NET MVC中基于Session数据实现授权检查?

发布于 2024-07-29 00:05:02 字数 566 浏览 2 评论 0原文

这将是我的第一个带有表单身份验证的 ASP.NET MVC 应用程序,因此我试图确保我不会错过任何内容。 场景是这样的:公共/安全区域。

在私人区域内,它甚至进一步限于特定区域/用户。 这些“区域”是通过对每个用户组自定义的基本区域进行自定义来定义的。

例如,用户可以访问 url /Area/Controller/Action。 他们需要获得安全区域的许可,否则将被重定向到登录视图。

我一直在阅读有关 AuthorizeAttribute 的内容,但我不确定应该如何/在哪里进行这些基本检查。 我最初的预感是在使用用户的 IP 成功登录后在会话中存储一个用户对象以及有关他们有权访问的内容等的详细信息。

每个安全控制器调用的授权检查将验证是否存在有效的用户对象会话期间,IP 仍然匹配,并且用户可以访问特定区域。 这个设置有什么明显的漏洞吗?

编辑:在哪里/如何实现这些检查,以便当控制器被标记为 [Authorize] 时,它将执行这些会话对象检查?

任何指示或建议将不胜感激。 谢谢。

This will be my first ASP.NET MVC application with forms authentication so I am trying to make sure I don't miss anything. The scenario is this: Public / Secured Areas.

Within the private area it is even further limited to specific areas / user. These 'Areas' are defined by customizations to the base area that is customized per user group.

So for example a user could get to url /Area/Controller/Action. They would need to have permission to the secured area or they would be redirected to the sign-in view.

I have been reading about the AuthorizeAttribute but I am not sure how/where I should be doing these basic checks. My initial hunch would be to store a user object in the session after a successful sign-in with the user's IP and details about what they have access to etc.

The authorization check for each secured controller call would verify that a valid user object exists in the session, the IPs still match up, and the user has access to the specific area. Is there any obvious holes to this setup?

Edit: Where/how do I implement these checks so that when a controller is tagged with [Authorize] it will perform those session object checks?

Any pointers or suggestions would be much appreciated. Thanks.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

ぇ气 2024-08-05 00:05:02

看来我使用了自定义的 AuthorizeAttribute。 其实很简单。 这是代码:

namespace MyApp.Custom.Security
{
    public class Secure : AuthorizeAttribute
    {
        /// <summary>
        /// Checks to see if the user is authenticated and has a valid session object
        /// </summary>        
        /// <param name="httpContext"></param>
        /// <returns></returns>
        protected override bool AuthorizeCore(HttpContextBase httpContext)
        {
            if (httpContext == null) throw new ArgumentNullException("httpContext");

            // Make sure the user is authenticated.
            if (httpContext.User.Identity.IsAuthenticated == false) return false;

            // This will check my session variable and a few other things.
            return Helpers.SecurityHelper.IsSignedIn();
        }
    }
}

然后在我的控制器上,我只需放置一个 [Secure] 属性,只要访问控制器,它就会使用上面的函数。 很简单。 我还创建了一个 [SecureByRole] 属性,它执行所有相同的操作,但也会检查我的自定义角色信息。 无需使用罐装会员资格中的所有内置巫术:)

Well it looks like I went with a custom AuthorizeAttribute. It was actually very simple. Here is the code:

namespace MyApp.Custom.Security
{
    public class Secure : AuthorizeAttribute
    {
        /// <summary>
        /// Checks to see if the user is authenticated and has a valid session object
        /// </summary>        
        /// <param name="httpContext"></param>
        /// <returns></returns>
        protected override bool AuthorizeCore(HttpContextBase httpContext)
        {
            if (httpContext == null) throw new ArgumentNullException("httpContext");

            // Make sure the user is authenticated.
            if (httpContext.User.Identity.IsAuthenticated == false) return false;

            // This will check my session variable and a few other things.
            return Helpers.SecurityHelper.IsSignedIn();
        }
    }
}

Then on my controllers I just have to put a [Secure] attribute and it uses my function above anytime that controller is accessed. Pretty simple. I also made a [SecureByRole] attribute as well that does all the same stuff but checks for my custom role information as well. No need to for all that built in voodoo from the canned Membership :)

南风起 2024-08-05 00:05:02

尝试查看 RoleProvider 类。 这是ASP.net如何使用基于角色的用户授权的基本框架。 我认为你应该使用 [Authorize(Roles='...' )] 属性来利用它。

Try to look at the RoleProvider class. This is the basic framework of how ASP.net use rolebased authorization to users. And I think you should use [Authorize(Roles='...')] attribute to make use of that.

烂柯人 2024-08-05 00:05:02

在我之前的应用程序中,我使用了一个简单的 HttpModule 来通过附加角色等来增强经过身份验证的用户(我这样做是因为我的要求非常有限)。

public class AuthorisationModule : IHttpModule
{
    public void Init( HttpApplication context )
    {
        context.AuthorizeRequest += AuthorizeRequest;
    }

    private void AuthorizeRequest(object sender, EventArgs e)
    {
        var currentUser = HttpContext.Current.User;
        if( !currentUser.IsAuthenticated() )
        {
            return;
        }

        var roles = new List<string>();
        // Add roles here using whatever logic is required

        var principal = new GenericPrincipal( currentUser.Identity, roles.ToArray() );
        HttpContext.Current.User = principal;
    }

    public void Dispose()
    {
        if(HttpContext.Current == null )
        {
            return;
        }

        if(HttpContext.Current.ApplicationInstance == null)
        {
            return;
        }

        HttpContext.Current.ApplicationInstance.AuthorizeRequest -= AuthorizeRequest;
    }
}

In my previous application I used a simple HttpModule to augment the authenticated user with additional roles etc ( I did this because my requirements were very constrained ).

public class AuthorisationModule : IHttpModule
{
    public void Init( HttpApplication context )
    {
        context.AuthorizeRequest += AuthorizeRequest;
    }

    private void AuthorizeRequest(object sender, EventArgs e)
    {
        var currentUser = HttpContext.Current.User;
        if( !currentUser.IsAuthenticated() )
        {
            return;
        }

        var roles = new List<string>();
        // Add roles here using whatever logic is required

        var principal = new GenericPrincipal( currentUser.Identity, roles.ToArray() );
        HttpContext.Current.User = principal;
    }

    public void Dispose()
    {
        if(HttpContext.Current == null )
        {
            return;
        }

        if(HttpContext.Current.ApplicationInstance == null)
        {
            return;
        }

        HttpContext.Current.ApplicationInstance.AuthorizeRequest -= AuthorizeRequest;
    }
}
对风讲故事 2024-08-05 00:05:02
[Authorize]
public class BaseController : Controller
{
    protected override void OnAuthorization(AuthorizationContext authContext)
    {
        if
            (
            !User.Identity.IsAuthenticated &&
            Request.LogonUserIdentity != null &&
            Request.LogonUserIdentity.IsAuthenticated
            )
        {
            var logonUserIdentity = Request.LogonUserIdentity.Name;
            if (!string.IsNullOrEmpty(logonUserIdentity))
            {
                if (logonUserIdentity.Contains("\\"))
                    logonUserIdentity = logonUserIdentity.Substring(logonUserIdentity.IndexOf("\\") + 1);

                var db = new UsersContext();
                var loginUser =
                    db.UserProfiles.FirstOrDefault(x => x.UserName == logonUserIdentity);

                //Auto-Login Windows Identity
                if (loginUser == null)
                    loginUser = CreateUser(db, logonUserIdentity);

                if (loginUser != null)
                {
                    FormsAuthentication.SetAuthCookie(loginUser.UserName, true);

                    string returnUrl = Request.RawUrl;
                    if (!string.IsNullOrEmpty(returnUrl))
                        Response.Redirect(returnUrl);
                    Response.Redirect("~/");

                }
            }
        }
    }

    private static UserProfile CreateUser(UsersContext db, string logonUserIdentity)
    {
        var user = new UserProfile {UserName = logonUserIdentity};
        db.UserProfiles.Add(user);
        db.SaveChanges();
        return user;
    }
}
[Authorize]
public class BaseController : Controller
{
    protected override void OnAuthorization(AuthorizationContext authContext)
    {
        if
            (
            !User.Identity.IsAuthenticated &&
            Request.LogonUserIdentity != null &&
            Request.LogonUserIdentity.IsAuthenticated
            )
        {
            var logonUserIdentity = Request.LogonUserIdentity.Name;
            if (!string.IsNullOrEmpty(logonUserIdentity))
            {
                if (logonUserIdentity.Contains("\\"))
                    logonUserIdentity = logonUserIdentity.Substring(logonUserIdentity.IndexOf("\\") + 1);

                var db = new UsersContext();
                var loginUser =
                    db.UserProfiles.FirstOrDefault(x => x.UserName == logonUserIdentity);

                //Auto-Login Windows Identity
                if (loginUser == null)
                    loginUser = CreateUser(db, logonUserIdentity);

                if (loginUser != null)
                {
                    FormsAuthentication.SetAuthCookie(loginUser.UserName, true);

                    string returnUrl = Request.RawUrl;
                    if (!string.IsNullOrEmpty(returnUrl))
                        Response.Redirect(returnUrl);
                    Response.Redirect("~/");

                }
            }
        }
    }

    private static UserProfile CreateUser(UsersContext db, string logonUserIdentity)
    {
        var user = new UserProfile {UserName = logonUserIdentity};
        db.UserProfiles.Add(user);
        db.SaveChanges();
        return user;
    }
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文