基于IdentityServer4的单点登录——Client

以MvcClient项目为例

1.新建项目并添加引用

新建一个asp .net core 2.0的项目
引用IdentityModel

2.配置

比之前的控制台客户端多这个步骤,需要配置这个客户端的ClientId,Secret,Scheme,作用范围等等,这些内容与IdentityServer的Client的内容对应

public void ConfigureServices(IServiceCollection services)
{
    JwtSecurityTokenHandler.DefaultInboundClaimTypeMap.Clear();

    services.AddAuthentication(options =>
        {
            options.DefaultScheme = "Cookies";
            options.DefaultChallengeScheme = "oidc";
        })
        .AddCookie("Cookies")
        .AddOpenIdConnect("oidc", options =>
        {
            options.SignInScheme = "Cookies";
            //IdentityServer服务器
            options.Authority = "http://localhost:5000";
            options.RequireHttpsMetadata = false;
            //这个客户端的Id,Secret
            options.ClientId = "mvc";
            options.ClientSecret = "secret";
            options.ResponseType = "code id_token";

            options.SaveTokens = true;
            options.GetClaimsFromUserInfoEndpoint = true;
            //这个客户端的范围集合
            options.Scope.Add("api1");
            options.Scope.Add("offline_access");
        });
}
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
    app.UseAuthentication();
}

3.登录:跳转到IdentityServer的统一登录页面

因为Authorize特性,访问Secure页面的时候,如果没有登录,会自动跳转到设置的Authority的网址

[Authorize]
public IActionResult Secure()
{
    ViewData["Message"] = "Secure page.";

    return View();
}

4.登陆成功后,调用Api接口

(1)使用用户令牌访问Api

var accessToken = await HttpContext.GetTokenAsync("access_token");

var client = new HttpClient();
client.SetBearerToken(accessToken);
//访问之前定义好的Api项目的方法
var content = await client.GetStringAsync("http://localhost:5001/identity");

(2)使用application identity访问Api

//先访问IdentityServer服务器,获得授权令牌
//传参访问地址、客户端Id,客户端Secret
var tokenClient = new TokenClient("http://localhost:5000/connect/token", "mvc", "secret");
//传参范围
var tokenResponse = await tokenClient.RequestClientCredentialsAsync("api1");

//根据授权令牌访问Api
var client = new HttpClient();
client.SetBearerToken(tokenResponse.AccessToken);
//访问之前定义好的Api项目的方法
var content = await client.GetStringAsync("http://localhost:5001/identity");
原文地址:https://www.cnblogs.com/Lulus/p/7986644.html