【问题标题】:User.Identity.IsAuthenticated always return false in ResolverUser.Identity.IsAuthenticated 在解析器中总是返回 false
【发布时间】:2019-01-27 11:17:05
【问题描述】:

我正在尝试在我的 ASP.NET Core 项目中实现多租户。我可以从 url 捕获子域并从那里确定租户,但是当我想从登录用户那里获取租户时,User.Identity.IsAuthenticated 总是返回 false,即使用户已登录。这是代码:

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 应该包含用户信息。

【问题讨论】:

  • 能否提供基类?你从哪里得到http上下文?通常 http 上下文仅在端点中可用。当您想在该范围之外访问它时,您必须注册并注入 IHttpContextAccessor。
  • @alsami 我相信它来自 Saaskit.Multitenancy 包。我还没有冒险进入他们的代码,但我想知道如何在控制器/剃须刀之外捕获用户登录状态。当我在这里尝试context.User.Identity.IsAuthenticated 时,它总是返回false。
  • 我发现了问题。我应该在调用多租户注入之前添加app.UseAuthentication

标签: asp.net-core


【解决方案1】:

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

【讨论】:

  • ConfigureServices 方法中的注入?
猜你喜欢
  • 2020-10-04
  • 2013-10-30
  • 2014-11-10
  • 2023-03-15
  • 1970-01-01
  • 2019-07-10
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多