0

我们有一个正在使用 ASP.NET 5 aka vNext 和 MVC 6 开发的 Intranet 站点。

我们希望能够获得用户登录时使用的 Windows 网络 ID,但是有一个现有的数据库来定义角色等。我们将利用并且已经这样做了。我真正想做的就是在使用 ASP.NET Identity 管理用户有权访问的角色时获取 Windows 用户 ID。任何建议如何做到这一点?

基本上在 Startup.cs 中,我在配置服务中有如下内容:

    services.AddIdentity<WorldUser, IdentityRole>(config =>
    {
       config.User.RequireUniqueEmail = true;
       config.Password.RequiredLength = 8;
    }).AddEntityFrameworkStores<WorldContext>();

接下来在配置我有: app.UseIdentity();

Windows 身份验证在项目属性级别启用,匿名也是如此。我看不到实际获取 Windows 用户 ID 的方法。

4

2 回答 2

0

警告:这是 ASP.NET 4.5 而不是 5 的代码。

把这是你的web.config:

<system.web>
    <compilation debug="true" targetFramework="4.5" />
    <httpRuntime targetFramework="4.5" maxRequestLength="20480" />
    <authentication mode="Windows" />
    <authorization>
        <deny users="?" />                  <!--Denies access to the anonymous user.-->
        <allow users="MydomainName\MyUsername" />      <!--Grants access to this user.-->
        <allow roles="MyWindowsGroup" />
        <deny users="*" />                  <!--Denies access to everyone. This shakes out as everyone except the defined users/usergroupt that are rganted access manualy.-->
    </authorization>
</system.web>

这样,您必须有一个 Windows 网络用户 ID。用户在 Intranet 应用程序中始终拥有的。然后只需使用:

HttpContext.Current.User.Identity.Name

和以前一样。像这样:

String name = User.Identity.Name;
// If needed filter out the domain name here
int accessLevel = _UserRepository.GetAccessLevel(name) 
// Assuming  you use a repository to connect to your database. And also have a method to get the accesslevel for a username
Session["AccessLevel"] = accessLevel;
// In case you want to check for accesslevel in the views as well you can put it in a session like so.

这又是 .NEET 4.5 而不是.NET 5 应用程序的代码。C# 代码应该相同,但 .NET 5 中没有 web.config,因此您必须通过 Startup.cs 放入您的配置。

根据您的要求,这似乎是您所需要的,如果需要任何进一步的解释,请告诉我。

于 2015-10-22T20:29:56.067 回答
0

所以我仍然希望有人提出更好的答案,因为我的目标仍然是在使用 Windows 用户 ID 对用户进行身份验证后使用和利用 .Net Identity 进行授权。但现在,我将启用 Windows 身份验证并使用 Rick 在此线程中提供的自定义授权选项的解决方案: 如何在 ASP.NET Core 中创建自定义 AuthorizeAttribute?

所以我将执行以下操作,为每个角色创建一个类,如下所示:

    public class ETimeAdmin : AuthorizationHandler<ETimeAdmin>, IAuthorizationRequirement
    {
       protected override void Handle(AuthorizationContext context, ETimeAdmin requirement)
       {



       }
    }

然后在配置服务的 Startup.cs 中添加:

    services.AddAuthorization(options => options.AddPolicy("ETimeAdmin", policy => policy.Requirements.Add(new ETimeAdmin())));

最后我应该能够使用:

    [Authorize(Roles="ETimeAdmin")]

我不想在 Startup.cs 中执行上述操作,而是添加以下行:

     services.AddIdentity<ETimeUser, IdentityRole>(config =>
     {
     }).AddEntityFrameworkStores<ETimeContext>();

然后我可以使用 .Net Identity 已经提供的内容,而无需为每个角色编写自己的代码。我必须使用自己的缓存,所以每次我想检查用户是否有权限时都不需要返回数据库。一定有更好的方法...

于 2015-10-23T18:20:33.440 回答