ASP.NET MVC 表单身份验证 + 授权属性 + 简单角色 [英] ASP.NET MVC Forms Authentication + Authorize Attribute + Simple Roles

查看:36
本文介绍了ASP.NET MVC 表单身份验证 + 授权属性 + 简单角色的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试向 ASP.NET MVC 应用程序添加简单身份验证和授权.

I'm trying to add simple Authentication and Authorization to an ASP.NET MVC application.

我只是想在基本的表单身份验证中添加一些附加功能(由于简单和自定义数据库结构)

I'm just trying to tack on some added functionality to the basic Forms Authentication (due to simplicity and custom database structure)

假设这是我的数据库结构:用户:用户名密码角色(最好是一些枚举.如果需要,可以使用字符串.目前,用户只有一个角色,但这可能会改变)

Assuming this is my database structure: User: username password role (ideally some enum. Strings if need be. Currently, user only has ONE role, but this might change)

高级问题:鉴于上述数据库结构,我希望能够做到以下几点:

High Level Problem: Given the above database structure, I would like to be able to do the following:

  • 使用表单身份验证的简单登录
  • 用以下方式装饰我的行动:[授权(角色={ MyRoles.Admin, MyRoles.Member})]
  • 在我的视图中使用角色(以确定要在某些部分中显示的链接)

目前,我真正确定的是如何进行身份验证.在那之后我迷路了.我不确定在哪一点获取用户角色(登录、每次授权?).由于我的角色可能不是字符串,我不确定它们将如何与 User.IsInRole() 配合.

Currently, all I'm really sure of is how to Authenticate. After that I'm lost. I'm not sure at which point do I grab the user role (login, every authorization?). Since my roles may not be strings, I'm not sure how they will fit in with the User.IsInRole().

现在,我在这里问是因为我还没有找到一个简单"的方法来完成我所需要的.我看过很多例子.

Now, I'm asking here because I haven't found a "simple" accomplish what I need. I have seen multiple examples.

用于身份验证:

  • 我们有简单的用户验证来检查数据库和SetAuthCookie"
  • 或者我们覆盖 Membership 提供者并在 ValidateUser 中执行此操作在其中任何一个中,我不确定如何添加我的简单用户角色,以便它们与:HttpContext.Current.User.IsInRole("管理员")此外,我不确定如何修改它以使用我的枚举值.

对于授权,我见过:

  • 派生 AuthorizeAttribute 并实施 AuthorizeCore 或 OnAuthorization 来处理角色?
  • 实施 IPrincipal?

任何帮助将不胜感激.但是,我担心我可能需要很多细节,因为我在 Google 上搜索的内容似乎都不适合我需要做的事情.

Any assistance would be greatly appreciated. However, I fear I may need a lot of detail, because none of what I've Googled seems to fit with what I need to do.

推荐答案

构建可以使用枚举而不是字符串的自定义 AuthorizeAttribute.当您需要授权时,通过附加枚举类型名称 + 枚举值将枚举转换为字符串,并从那里使用 IsInRole.

Build a custom AuthorizeAttribute that can use your enums rather than strings. When you need to authorise, convert the enums into strings by appending the enum type name + the enum value and use the IsInRole from there.

要将角色添加到授权用户中,您需要附加到 HttpApplication AuthenticateRequest 事件,类似于 http://www.eggheadcafe.com/articles/20020906.asp(但将大量嵌套的 if 语句反转为保护子句!).

To add roles into an authorised user you need to attach to the HttpApplication AuthenticateRequest event something like the first code in http://www.eggheadcafe.com/articles/20020906.asp ( but invert the massively nested if statements into guard clauses!).

您可以在表单 auth cookie 中来回传递用户角色,也可以每次从数据库中获取它们.

You can round-trip the users roles in the forms auth cookie or grab them from the database each time.

这篇关于ASP.NET MVC 表单身份验证 + 授权属性 + 简单角色的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆