加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > asp.Net > 正文

是否有任何ASP.NET身份的实现具有另一个级别以上的帐户?

发布时间:2020-12-16 09:55:25 所属栏目:asp.Net 来源:网络整理
导读:我正在使用ASP.NET身份.它运作良好,但我想在AspNetUsers表的父级中添加.在我的情况下,我希望每个用户都属于一个组织.在这一点上,我只是在寻找一些想法,看看其他人是否已经看到了允许这样做的实现. 有没有人见过这样做的任何实现.我想获得一些关于如何实现此
我正在使用ASP.NET身份.它运作良好,但我想在AspNetUsers表的父级中添加.在我的情况下,我希望每个用户都属于一个组织.在这一点上,我只是在寻找一些想法,看看其他人是否已经看到了允许这样做的实现.

有没有人见过这样做的任何实现.我想获得一些关于如何实现此功能的提示.

解决方法

我假设你正在使用身份存储的默认EF实现.

身份非常灵活,可以弯曲成多种形状以满足您的需求.

如果您正在寻找简单的父子关系,其中每个用户都有父记录(例如公司),那么实现该方法的方法之一是将公司引用添加到用户类:

using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
using Microsoft.AspNet.Identity.EntityFramework;


public class ApplicationUser : IdentityUser
{
    public ApplicationUser()
    {
    }

    [ForeignKey("CompanyId")]
    public Company Company { get; set; }
    public int CompanyId { get; set; }
}


public class Company
{
    [Key,DatabaseGenerated(DatabaseGeneratedOption.Identity)]
    public int CompanyId { get; set; }
    public String Name { get; set; }

    public virtual ICollection<ApplicationUser> Users { get; set; }
}

这将为用户提供外键给公司.但是从这里开始,下一步行动取决于您的应用程序需要什么.我想你会根据他们所属的公司对用户有某种限制.为了快速检索公司,您可以在登录用户时将CompanyId存储在索赔中.
ApplicationUser的默认实现具有GenerateUserIdentityAsync方法.您可以按如下方式修改:

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
        identity.AddClaim(new Claim("CompanyId",CompanyId.ToString()));
        return userIdentity;
    }

然后,在每个请求中,您都可以从Cookie访问此CompanyId声明:

public static int GetCompanyId(this IPrincipal principal)
    {
        var claimsPrincipal = principal as ClaimsPrincipal;
        //TODO check if claims principal is not null

        var companyIdString = claimsPrincipal.Claims.FirstOrDefault(c => c.Type == "CompanyId");
        //TODO check if the string is not null

        var companyId = int.Parse(companyIdString); //TODO this possibly can explode. Do some validation
        return companyId;
    }

然后,您将能够从Web应用程序的几乎任何位置调用此扩展方法:HttpContext.Current.User.GetCompanyId()

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读