如何在IdentityServer4的API端点内获取租户

时间:2018-12-05 17:20:05

标签: identityserver4

我有一个IdentityServer4实现,并添加了一个API端点,如下所示。我也有另一个要从该API端点获取数据的mvc应用程序。我需要从API端点内部获取租户,因此我通过querystring发送它,但是我认为这不是一个好方法。我不知道将租户带入API端点的另一种方法,我需要它。我怎么能得到??????

    // This is part of my IdSrv4 implementation
    public void ConfigureServices(IServiceCollection services)
    {
        services.AddIdentityServer(…); // details omitted


        services.AddAuthentication()
        .AddIdentityServerAuthentication("schema", isAuth =>
        {
            isAuth.Authority = configuration["BaseUrl"];
            isAuth.ApiName = "api";
        });
    }

    // Api inside of my IdSrv4, it is for servers users info.
    [Route("api")]
    public class SomeController
    {
        [HttpGet("users")]
        [Authorize(AuthenticationSchemes = " schema ")]
        public async Task<IActionResult> method(string tenant)
        {


            // Var tenant = How do I get the tenant here without pass it through querystring ?????

            // this is just for sample, here I going to do another things
            return Ok(users);
        }
    }

    // Client configuration inside my IdSrv4
    public static IEnumerable<Client> GetClients()
    {
        return new List<Client>
        {
            new Client
            {
                ClientName = "My Client",
                ClientId = "myclient",
                AllowedGrantTypes = GrantTypes.Hybrid,

                RequireConsent = false,

                RedirectUris = new List<string>()
                {
                    "http://localhost:54017/signin-oidc"
                },
                PostLogoutRedirectUris = new List<string>()
                {
                    "http://localhost:54017/signout-callback-oidc"
                },
                AllowedScopes =
                {
                    IdentityServerConstants.StandardScopes.OpenId,
                    IdentityServerConstants.StandardScopes.Profile,
                    IdentityServerConstants.StandardScopes.Email,
                    "api"
                },
                ClientSecrets =
                {
                    new Secret("secret".Sha256())
                }
            }
        }
    }

    // This is my other application that want to get Info from the API inside of my IdSrv4
    public void ConfigureServices(IServiceCollection services)
    {
        // For authentication
        services.AddAuthentication(options =>
        {
            options.DefaultScheme = CookieAuthenticationDefaults.AuthenticationScheme;
            options.DefaultChallengeScheme = "oidc";
        }
        )
        .AddCookie(CookieAuthenticationDefaults.AuthenticationScheme)
        .AddOpenIdConnect("oidc", options =>
        {
            options.SignInScheme = CookieAuthenticationDefaults.AuthenticationScheme;
            options.Authority = Configuration["IdentityServerUrl"];
            options.ClientId = Configuration["ClientId"];
            options.ResponseType = "code id_token";
            options.Scope.Add("openid");
            options.Scope.Add("profile");
            options.Scope.Add("api");
            options.SaveTokens = true;
            options.ClientSecret = "secret";

            options.TokenValidationParameters = new TokenValidationParameters
            {
                NameClaimType = JwtClaimTypes.GivenName
            };

            //the middleware filters acr claim by default, here we are including it as part of the claim
            options.ClaimActions.Remove("acr");

            options.Events.OnRedirectToIdentityProvider = n =>
            {
                if (n.ProtocolMessage.RequestType == OpenIdConnectRequestType.Authentication)
                {
                    n.ProtocolMessage.AcrValues = “tenant: mytenant”;
                }
                return Task.FromResult(0);
            };
        });
    }

    // Controller where I try to get the users from my IdSrv4
    [Authorize]
    public class UserController : Controller
    {
        public async Task<IActionResult> GetUsers()
        {
            //get access token
            var accessToken = await HttpContext.GetTokenAsync(OpenIdConnectParameterNames.AccessToken);

            var httpClient = new HttpClient();
            httpClient.BaseAddress = new Uri(Configuration["IdSrv4Url"]);
            httpClient.SetBearerToken(accessToken);

            var response = await httpClient.GetAsync("api/users").ConfigureAwait(false);

            if (response.IsSuccessStatusCode)
            {
                var usersAsString = await response.Content.ReadAsStringAsync().ConfigureAwait(false);

                var usersDtos = JsonConvert.DeserializeObject<IList<UserDto>>(usersAsString).ToList();

                return View(usersDtos);
            }
        }
    }

0 个答案:

没有答案
相关问题