User.Identity.IsAuthenticated始终在解析器中返回false

时间:2018-08-21 09:37:01

标签: asp.net-core

我正在尝试在ASP.NET Core项目中实现多租户。我可以从URL捕获子域并从那里确定租户,但是以某种方式,当我想从登录用户那里获取租户时,User.Identity.IsAuthenticated总是返回false,即使用户已经登录也是如此。这是代码:< / p>

public class CachingTenantResolver : MemoryCacheTenantResolver<Tenant>
{
    private readonly ApplicationDbContext _context;
    //private readonly ILoggerFactory _loggerFactory;
    public CachingTenantResolver(
        ApplicationDbContext context, IMemoryCache cache, ILoggerFactory loggerFactory)
         : base(cache, loggerFactory)
    {
        _context = context;
        //_loggerFactory = loggerFactory;
    }

    // Resolver runs on cache misses
    protected override async Task<TenantContext<Tenant>> ResolveAsync(HttpContext context)
    {

        Tenant tenant = new Tenant { Name = "DefaultTenant", Domain = "www" };

        if(context.User.Identity.IsAuthenticated)
        {
            string userId = context.User.FindFirst(ClaimTypes.NameIdentifier).Value;
            Account account = _context.Accounts.Include("Tenant").FirstOrDefault(i => i.IdentityUserID == userId);
            tenant = account.Tenant;
        }
        else
        {
            var subdomain = context.Request.Host.Host.ToLower().Split('.');

            var tempTenant = await _context.Tenants
                .FirstOrDefaultAsync(t => t.Domain == subdomain[0]);

            if (tempTenant!=null)
            {
                tenant = tempTenant;
            }
        }
        return new TenantContext<Tenant>(tenant);
    }
//...the rest of the resolver

我想念什么?据我了解,HttpContext应该包含用户信息。

1 个答案:

答案 0 :(得分:1)

确保在多租户注入之前调用app.UseAuthentication()。