为Azure用户.net核心添加基于本地数据库的自定义授权声明

时间:2017-01-17 18:24:42

标签: asp.net-core-mvc azure-active-directory claims-based-identity asp.net-authorization

我正在尝试使用Azure AD电子邮件地址识别数据库用户,然后根据本地数据库用户的属性向azure AD身份验证用户添加自定义声明。在startup.cs中,我得到了:

public void ConfigureServices(IServiceCollection services)
{
    ...
    services.AddScoped<IClaimsTransformer, ClaimsTransformer>();
    ...
}

public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory, KayttajatContext context)
{
    ...
    app.UseClaimsTransformation(async (c) =>
    {
        IClaimsTransformer transformer = c.Context.RequestServices.GetRequiredService<IClaimsTransformer>();
        return await transformer.TransformAsync(c);
    });
    ...
}

然后ClaimsTransformer.cs看起来像这样:

namespace Authtest
{
    public class ClaimsTransformer : IClaimsTransformer
    {

        private readonly KayttajatContext _context;

        public ClaimsTransformer(KayttajatContext dbContext)
        {
            _context = dbContext;
        }

        public async Task<ClaimsPrincipal> TransformAsync(ClaimsTransformationContext ctrans)
        {

          string  sposti = ((ClaimsIdentity)ctrans.Principal.Identity).Name; 
           var user = await _context.Henkilöt.FirstOrDefaultAsync(t => t.Sposti == sposti); 

            if (user.Sposti == sposti)
            {
                ((ClaimsIdentity)ctrans.Principal.Identity).AddClaim(new Claim(ClaimTypes.Role, "Administrator"));
                ((ClaimsIdentity)ctrans.Principal.Identity).AddClaim(new Claim(ClaimTypes.Role, "User"));
            }
            else
            {
                ((ClaimsIdentity)ctrans.Principal.Identity).AddClaim(new Claim(ClaimTypes.Role, "User"));
            }
            return ctrans.Principal;
        }
    }
}

但是这给了我“NullReferenceException:对象引用未设置为对象的实例。”在if (user.Sposti == sposti)

如果我给其中一个变量赋予字符串值,if语句工作正常。我不知道我做错了什么?它与异步有关吗?请帮助这让我疯了。

1 个答案:

答案 0 :(得分:1)

我试图在设置之前调用字符串sposti = ((ClaimsIdentity)ctrans.Principal.Identity).Name;。现在工作,谢谢:))