如何延长User.Identity的可用属性 [英] How to extend available properties of User.Identity

查看:1371
本文介绍了如何延长User.Identity的可用属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用MVC5标识2.0用户登录到我的网站,那里的验证信息存储在SQL数据库中。 Asp.net身份已经以标准的方式被实现为可以在很多在线教程中找到。

I'm using MVC5 Identity 2.0 for users to log into my website, where the authentication details are stored in an SQL database. Asp.net Identity has been implemented in a standard way as can be found in many online tutorials.

在IdentityModels的ApplicationUser类已扩展至包括一些自定义属性,如整数OrganizationId。这个想法是,许多用户可以创建并分配到一个公共组织数据库关系的目的。

The ApplicationUser class in IdentityModels has been extended to include some custom properties, such as an integer OrganizationId. The idea is that many users can be created and assigned to a common Organization for database relationship purposes.

public class ApplicationUser : IdentityUser
    {
        public async Task<ClaimsIdentity> GenerateUserIdentityAsync(UserManager<ApplicationUser> manager)
        {
            // Note the authenticationType must match the one defined in CookieAuthenticationOptions.AuthenticationType
            var userIdentity = await manager.CreateIdentityAsync(this, DefaultAuthenticationTypes.ApplicationCookie);
            // Add custom user claims here
            return userIdentity;
        }

        //Extended Properties
        public DateTime? BirthDate { get; set; }
        public long? OrganizationId { get; set; }

        //Key Mappings
        [ForeignKey("OrganizationId")]
        public virtual Organization Organization { get; set; }
    }

我怎样才能找回在当前登录用户的OrganizationId财产控制器内?
这是通过一个可用的方法一旦用户登录或我总是从数据库中检索OrganizationId的基础上,用户ID,每次控制器方法执行?

How can I retrieve the OrganizationId property of the currently logged in user from within a controller? Is this available via a method once a user is logged in or do I always have the retrieve the OrganizationId from the database, based on the UserId, every time a controller method executes?

我已经看到我需要使用以下方法来获取登录的用户ID等在网络上阅读各地。

Reading around on the web I have seen I need to use the following to get the logged in UserId etc.

using Microsoft.AspNet.Identity;
...
User.Identity.GetUserId();

然而,OrganizationId不在User.Identity可用的属性。我是否需要延长User.Identity以包括OrganizationId财产?如果是这样,我怎么去这个问题。

However, OrganizationId is not a property available in User.Identity. Do I need to extend User.Identity to include the OrganizationId property? If so, how do I go about this.

我需要OrganizationId所以经常的原因是,许多表的查询都依赖于OrganizationId检索有关该公司关联到登录的用户组织数据。

The reason I need the OrganizationId so often is that many table queries are reliant on the OrganizationId to retrieve data relevant to the Organization that's associated to the logged in user.

推荐答案

每当你想User.Identity的特性与上述类似问题的任何附加属性扩展,这些属性首先添加到ApplicationUser类,像这样:

Whenever you want to extend the properties of User.Identity with any additional properties like the question above, add these properties to the ApplicationUser class first like so:

public class ApplicationUser : IdentityUser
{
    public async Task<ClaimsIdentity> GenerateUserIdentityAsync(UserManager<ApplicationUser> manager)
    {
        // Note the authenticationType must match the one defined in CookieAuthenticationOptions.AuthenticationType
        var userIdentity = await manager.CreateIdentityAsync(this, DefaultAuthenticationTypes.ApplicationCookie);
        // Add custom user claims here
        return userIdentity;
    }

    // Your Extended Properties
    public long? OrganizationId { get; set; }
}

然后,你需要的是像这样(我在新的扩展文件夹中创建矿)来创建一个扩展方法:

Then what you need is to create an extension method like so (I create mine in an new Extensions folder):

namespace App.Extensions
{
    public static class IdentityExtensions
    {
        public static string GetOrganizationId(this IIdentity identity)
        {
            var claim = ((ClaimsIdentity)identity).FindFirst("OrganizationId");
            // Test for null to avoid issues during local testing
            return (claim != null) ? claim.Value : string.Empty;
        }
    }
}

当你创建了ApplicationUser类的身份,只需添加索赔 - > OrganizationId像这样:

When you create the Identity in the ApplicationUser class, just add the Claim -> OrganizationId like so:

    public async Task<ClaimsIdentity> GenerateUserIdentityAsync(UserManager<ApplicationUser> manager)
    {
        // Note the authenticationType must match the one defined in CookieAuthenticationOptions.AuthenticationType
        var userIdentity = await manager.CreateIdentityAsync(this, DefaultAuthenticationTypes.ApplicationCookie);
        // Add custom user claims here => this.OrganizationId is a value stored in database against the user
        userIdentity.AddClaim(new Claim("OrganizationId", this.OrganizationId));

        return userIdentity;
    }

一旦你添加的索赔,让你的扩展方法到位,使其可作为你的User.Identity属性,在网页/文件中添加using语句要访问它

在我的情况:使用App.Extensions; 控制器和 @using内。 App.Extensions withing一个.cshtml视图文件。

in my case: using App.Extensions; within a Controller and @using. App.Extensions withing a .cshtml View file.

和访问扩展方法:

var orgId = User.Identity.GetOrganizationId();

希望帮助的人:)

Hope that helps anyone :)

这篇关于如何延长User.Identity的可用属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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