以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");
