openid connect - identifying tenant during login

后端 未结 3 2058
后悔当初
后悔当初 2020-12-31 21:58

I have a multi-tenant (single database) application which allows for same username/email across different tenants.

At the time of login (Implicit flow) how can I iden

3条回答
  •  有刺的猬
    2020-12-31 22:35

    You're on the right track with the OAuth process. When you register the OpenID Connect scheme in your client web app's startup code, add a handler for the OnRedirectToIdentityProvider event and use that to add your "slug" value as the "tenant" ACR value (something OIDC calls the "Authentication Context Class Reference").

    Here's an example of how you'd pass it to the server:

    .AddOpenIdConnect("tenant", options =>
    {
        options.CallbackPath = "/signin-tenant";
        // other options omitted
        options.Events = new OpenIdConnectEvents
        {
            OnRedirectToIdentityProvider = async context =>
            {
                string slug = await GetCurrentTenantAsync();
                context.ProtocolMessage.AcrValues = $"tenant:{slug}";
            }
        };
    }
    

    You didn't specify what sort of server this is going to, but ACR (and the "tenant" value) are standard parts of OIDC. If you're using Identity Server 4, you could just inject the Interaction Service into the class processing the login and read the Tenant property, which is automatically parsed out of the ACR values for you. This example is non-working code for several reasons, but it demonstrates the important parts:

    public class LoginModel : PageModel
    {
        private readonly IIdentityServerInteractionService interaction;
        public LoginModel(IIdentityServerInteractionService interaction)
        {
            this.interaction = interaction;
        }
    
        public async Task PostEmailPasswordLoginAsync()
        {
            var context = await interaction.GetAuthorizationContextAsync(returnUrl);
            if(context != null)
            {
                var slug = context.Tenant;
                // etc.
            }
        }
    }
    

    In terms of identifying the individual user accounts, your life will be a lot easier if you stick to the OIDC standard of using "subject ID" as the unique user ID. (In other words, make that the key where you store your user data like the tenant "slug", the user email address, password salt and hash, etc.)

提交回复
热议问题