您的位置:首页 > 其它

.Net Core 3.0 IdentityServer4 快速入门

2019-10-24 10:03 573 查看

.Net Core 3.0 IdentityServer4 快速入门

一、简介

  IdentityServer4是用于ASP.NET Core的OpenID Connect和OAuth 2.0框架。

  将IdentityServer4部署到您的应用中具备如下特点:

  1)、认证服务

  2)、单点登陆

  3)、API访问控制

  4)、联合网关

  5)、专注于定制

  6)、成熟的开源系统

  7)、免费和商业支持

二、整体部署

using IdentityServer4.Models;
using System.Collections.Generic;

namespace IdentityServer
{
public static class Config
{
public static IEnumerable<ApiResource> Apis
=> new List<ApiResource>
{
new ApiResource("api1","My API")
};

public static IEnumerable<Client> Clients =>
new List<Client>
{
new Client
{
ClientId="client",
AllowedGrantTypes =GrantTypes.ClientCredentials,
ClientSecrets={
new Secret("aju".Sha256())
},
AllowedScopes={ "api1"}
}
};
}
}
View Code     b)、配置IdentityServer

using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using System.Linq;

namespace Api.Controllers
{
[Route("identity")]
[Authorize]
public class IdentityController : ControllerBase
{
public IActionResult Get()
{
return new JsonResult(from c in User.Claims select new { c.Type, c.Value });
}
}
}
View Code

  b)、配置(将身份认证服务添加到DI,并将身份验证中间件添加到管道)    

using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;

namespace Api
{
public class Startup
{
public Startup(IConfiguration configuration)
{
Configuration = configuration;
}

public IConfiguration Configuration { get; }

// This method gets called by the runtime. Use this method to add services to the container.
public void ConfigureServices(IServiceCollection services)
{
services.AddControllers();
services.AddAuthentication("Bearer").AddJwtBearer("Bearer", options =>
{
options.Authority = "http://localhost:5000";
options.RequireHttpsMetadata = false;
options.Audience = "api1";
});
}

// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}

app.UseRouting();

app.UseAuthentication();//认证
app.UseAuthorization();//授权

app.UseEndpoints(endpoints =>
{
endpoints.MapControllers();
});
}
}
}
View Code

   AddAuthentication:将身份认证服务添加到DI比配置Bearer为默认

   AddAuthentication:将身份认证服务添加到管道中,以便对主机的每次调用都将自动执行身份验证

   AddAuthentication:添加授权中间件,以确保匿名客户端无法访问我们的API资源

   

http://localhost:5001/identity 
在浏览器上访问应返回401状态代码。这意味着您的API需要凭据,并且现在受IdentityServer保护。

  c)、所需的包

using IdentityModel.Client;
using Newtonsoft.Json.Linq;
using System;
using System.Net.Http;
using System.Threading.Tasks;

namespace Client
{
class Program
{
static async Task Main(string[] args)
{
// Console.WriteLine("Hello World!");
var client = new HttpClient();
var disco = await client.GetDiscoveryDocumentAsync("http://localhost:5000");
if (disco.IsError)
{
Console.WriteLine(disco.Error);
return;
}
var tokenResponse = await client.RequestClientCredentialsTokenAsync(new ClientCredentialsTokenRequest
{
Address = disco.TokenEndpoint,
ClientId = "client",
ClientSecret = "aju",
Scope = "api1"
});
if (tokenResponse.IsError)
{
Console.WriteLine(tokenResponse.Error);
return;
}
Console.WriteLine(tokenResponse.Json);
Console.WriteLine("\n\n");
//call api

var apiClient = new HttpClient();
apiClient.SetBearerToken(tokenResponse.AccessToken);
var response = await apiClient.GetAsync("http://localhost:5001/identity");
if (!response.IsSuccessStatusCode)
{
Console.WriteLine(response.StatusCode);
}
else
{
var content = await response.Content.ReadAsStringAsync();
Console.WriteLine(JArray.Parse(content));
}
Console.ReadLine();
}
}
}
View Code   a)、所需的包

  

 4)、使用客户端访问Api资源

  

 

六、参考文献

  http://docs.identityserver.io/en/latest/index.html

 如果对您有帮助,请点个推荐(让更多需要的人看到哦)

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: