【.NET Core】ASP.NET Core之IdentityServer4(1):快速入门

本文中的IdentityServer4基于上节的jenkins 进行docker自动化部署。
使用了MariaDB,EF Core,AspNetIdentity,Docker

Demo地址:https://sso.neverc.cn
Demo源码:https://github.com/NeverCL/Geek.IdentityServer4

简介

OpenID Connect :常用的认证协议有SAML2p, WS-Federation and OpenID Connect – SAML2p。OpenID Connect是其中最新的协议。

OAuth 2.0 :OAuth 2.0 是一种授权协议。通过Access Token可以访问受保护的API接口。

OpenID Connect和OAuth 2.0非常相似,实际上,OpenID Connect是OAuth 2.0之上的一个扩展。
身份认证和API访问这两个基本的安全问题被合并为一个协议 - 往往只需一次往返安全令牌服务。

IdentityServer4基于ASP.NET Core 2对这两种协议的实现。

支持规范:https://identityserver4.readthedocs.io/en/release/intro/specs.html

关键词

IdentityServer:提供OpenID Connect and OAuth 2.0 protocols.

User:IdentityServer中的用户

Client:第三方应用,包括web applications, native mobile or desktop applications, SPAs etc.

Resource:包含Identity data 和 APIs。这是认证授权中的标识。

Identity Token:标识认证信息,至少包含user的sub claim。

Access Token:标识授权信息,可以包含Client 和 user的claim信息。

授权方式

Client Credentials

Client Credentials是最简单的一种授权方式。

步骤:

  1. 创建IdentityServer

    1. 定义APIs
    2. 定义Client
  2. 创建API
    1. 定义Authentication
  3. 使用Client
    1. 请求Token
    2. 使用Token

IdentityServer:

dotnet new web -o Geek.IdentityServer4 && dotnet add Geek.IdentityServer4 package IdentityServer4

Startup:

services.AddIdentityServer()
    .AddDeveloperSigningCredential()
    .AddInMemoryApiResources(Config.GetApiResources())
    .AddInMemoryClients(Config.GetClients());
...
app.UseIdentityServer();

Config:

public static IEnumerable<ApiResource> GetApiResources()
{
    return new List<ApiResource>
    {
        new ApiResource("api1")
    };
}

public static IEnumerable<Client> GetClients()
{
    return new List<Client>
    {
        new Client
        {
            ClientId = "client",
            AllowedGrantTypes = GrantTypes.ClientCredentials,
            ClientSecrets = { new Secret("secret".Sha256()) },
            Claims = { new Claim("name","名称") },
            AllowedScopes = { "api1" }
        },
    }
}

API:

dotnet new web -o Geek.Api && dotnet add Geek.Api package IdentityServer4.AccessTokenValidation

Startup:

services.AddMvc();
services.AddAuthentication("Bearer")//AddIdentityServerAuthentication 默认SchemeName:Bearer
    .AddIdentityServerAuthentication(opt =>
    {
        opt.ApiName = "api1";
        opt.Authority = "https://sso.neverc.cn";
    });
...
app.UseAuthentication();
app.UseMvc();

Controller:

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

Client:

dotnet new web -o Geek.Client && dotnet add Geek.Client package IdentityServer4.IdentityModel

Program:

var disco = await DiscoveryClient.GetAsync("https://sso.neverc.cn");
var tokenClient = new TokenClient(disco.TokenEndpoint, "client", "secret");
var tokenResponse = await tokenClient.RequestClientCredentialsAsync("api1");

var client = new HttpClient();
client.SetBearerToken(tokenResponse.AccessToken);
var response = await client.GetAsync("http://localhost:5001/identity");
var content = await response.Content.ReadAsStringAsync();
Console.WriteLine(JArray.Parse(content));

ResourceOwnerPassword

这种认证方式需要User提供用户名和密码,所以Client为非常可信的应用才可能使用这种方式。

步骤:

  1. 定义RO Client 和 User
  2. 使用Client

Identity Server

Config:

public static IEnumerable<Client> GetClients()
{
    ...
    new Client
    {
        ClientId = "ro.client",
        AllowedGrantTypes = GrantTypes.ResourceOwnerPassword,

        ClientSecrets = { new Secret("secret".Sha256()) },
        AllowedScopes = { "api1" }
    }
}
public static List<TestUser> GetUsers()
{
    return new List<TestUser>
    {
        new TestUser
        {
            SubjectId = "1",
            Username = "alice",
            Password = "password",
        }
    }
}

Startup:

services.AddIdentityServer()
    .AddDeveloperSigningCredential()
    .AddInMemoryApiResources(Config.GetApiResources())
    .AddInMemoryClients(Config.GetClients())
    .AddTestUsers(Config.GetUsers());

Client

var disco = await DiscoveryClient.GetAsync("https://sso.neverc.cn");
var tokenClient = new TokenClient(disco.TokenEndpoint, "ro.client", "secret");
var tokenResponse = await tokenClient.RequestResourceOwnerPasswordAsync("alice", "password", "api1");
var client = new HttpClient();
client.SetBearerToken(tokenResponse.AccessToken);
var response = await client.GetAsync("http://localhost:5001/identity");
var content = await response.Content.ReadAsStringAsync();
Console.WriteLine(JArray.Parse(content));

区分Client Credentials 和 ResourceOwnerPassword 可通过 sub claim来区分

Implicit

Implicit为隐式模式,通过浏览器端直接传输id_token

步骤:

  1. 配置IdentityServer

    1. 定义IdentityResources
    2. 定义mvc client
    3. 添加Mvc UI
  2. 创建mvc client

IdentityServer

public static IEnumerable<IdentityResource> GetIdentityResources()
{
    return new List<IdentityResource>
    {
        new IdentityResources.OpenId(),
        new IdentityResources.Profile()
    };
}

...
new Client
{
    ClientId = "mvc",
    ClientName = "MVC Client",
    AllowedGrantTypes = GrantTypes.Implicit,
    ClientSecrets = { new Secret("secret".Sha256()) },
    RedirectUris = { "http://localhost:5002/signin-oidc" },
    PostLogoutRedirectUris = { "http://localhost:5002/signout-callback-oidc" },
    AllowedScopes = new List<string>
    {
        IdentityServerConstants.StandardScopes.OpenId,
        IdentityServerConstants.StandardScopes.Profile,
    }
}
services.AddIdentityServer()
    .AddDeveloperSigningCredential()
    .AddInMemoryApiResources(Config.GetApiResources())
    .AddInMemoryClients(Config.GetClients())
    .AddTestUsers(Config.GetUsers())
    .AddInMemoryIdentityResources(Config.GetIdentityResources());

添加MvcUI:

在IdentityServer项目中powershell执行:

iex ((New-Object System.Net.WebClient).DownloadString(‘https://raw.githubusercontent.com/IdentityServer/IdentityServer4.Quickstart.UI/release/get.ps1‘))

MvcClient

public void ConfigureServices(IServiceCollection services)
{
    JwtSecurityTokenHandler.DefaultInboundClaimTypeMap.Clear();
    services.AddMvc();
    services.AddAuthentication(options =>
    {
        options.DefaultScheme = "Cookies";
        options.DefaultChallengeScheme = "oidc";
    })
    .AddCookie("Cookies")
    .AddOpenIdConnect("oidc", options =>
    {
        options.SignInScheme = "Cookies";
        options.Authority = "https://sso.neverc.cn";
        options.ClientId = "mvc";
        options.SaveTokens = true;
    });
}

public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
    app.UseAuthentication();
    app.UseMvcWithDefaultRoute();
}
public class HomeController : ControllerBase
{
    [Authorize]
    public ActionResult Index()
    {
        return new JsonResult(from c in User.Claims select new { c.Type, c.Value });
    }
}

Hybrid

在Implicit方式中,id_token在浏览器中传输是适用的,但是access_token不应该暴露在浏览器中。
Hybrid模式则是在Implicit的基础上,再传输code,适用code模式来获取access_token。

步骤:

  1. 定义Client
  2. 使用Client

IdentityServer配置

Config:

new Client
{
    ClientId = "hybrid",
    AllowedGrantTypes = GrantTypes.Hybrid,
    ClientSecrets = { new Secret("secret".Sha256()) },
    RedirectUris           = { "http://localhost:5002/signin-oidc" },
    PostLogoutRedirectUris = { "http://localhost:5002/signout-callback-oidc" },
    AllowedScopes = {
        IdentityServerConstants.StandardScopes.OpenId,
        IdentityServerConstants.StandardScopes.Profile,
        "api1"
    },
};

MvcClient配置

Startup:

.AddOpenIdConnect("oidc", options =>
{
    options.SignInScheme = "Cookies";
    options.Authority = "https://sso.neverc.cn";
    options.ClientId = "mvc";
    options.ClientSecret = "secret";
    options.ResponseType = "code id_token";
    options.SaveTokens = true;
    options.Scope.Add("api1");
});

Controller:

public async Task<IActionResult> CallApiUsingUserAccessToken()
{
    var accessToken = await HttpContext.GetTokenAsync("access_token");

    var client = new HttpClient();
    client.SetBearerToken(accessToken);
    var content = await client.GetStringAsync("http://localhost:5001/identity");

    ViewBag.Json = JArray.Parse(content).ToString();
    return View("json");
}

在登录完成后,即可通过认证得到的access_token调用CallApiUsingUserAccessToken来调用API服务。

总结

本文为IdentityServer4做了基本的介绍。
实际上IdentityServer4还可以非常灵活的与ASP.NET Identity 以及 EF Core等组合使用。
另外基于ASP.NET Core,所以IdentityServer4也支持跨平台。

原文地址:https://www.cnblogs.com/neverc/p/9004590.html

时间: 2024-08-12 09:15:44

【.NET Core】ASP.NET Core之IdentityServer4(1):快速入门的相关文章

.NET Core &amp; ASP.NET Core 1.0

.NET Core & ASP.NET Core 1.0在Redhat峰会上正式发布 众所周知,Red Hat和微软正在努力使.NET Core成为Red Hat企业版Linux (RHEL)系统上的一流开发平台选项.这个团队已经一起工作好几个月了,RHEL对.NET有许多需求.今天在RedHat 峰会DevNation 上宣布了.NET Core & ASP.NET Core 1.0 RTM.Red Hat有一个新的关于在RHEL上更简单的使用.NET Core的选项.(DevNatio

.NET Core &amp; ASP.NET Core 1.0在Redhat峰会上正式发布

众所周知,Red Hat和微软正在努力使.NET Core成为Red Hat企业版Linux (RHEL)系统上的一流开发平台选项.这个团队已经一起工作好几个月了,RHEL对.NET有许多需求.今天在RedHat 峰会DevNation 上宣布了.NET Core & ASP.NET Core 1.0 RTM.Red Hat有一个新的关于在RHEL上更简单的使用.NET Core的选项.(DevNation是一场全栈开发大会,将共同探讨开源的最优秀特性.DevNation 2016由50多场小分

ASP.NET Core 配置 Entity Framework Core - ASP.NET Core 基础教程 - 简单教程,简单编程

原文:ASP.NET Core 配置 Entity Framework Core - ASP.NET Core 基础教程 - 简单教程,简单编程 ASP.NET Core 配置 Entity Framework Core 上一章节学习完了视图,其实我们应该立即着手讲解模型的,但 ASP.NET Core MVC 中的模型和 Entity Framework 有相当大的关系,所以,在此之前,我们先来讲讲 Entity Framework Core 和如何配置它 本章中,我们将设置和配置我们的应用程

ASP.NET Core - ASP.NET Core MVC 的功能划分

概述 大型 Web 应用比小型 Web 应用需要更好的组织.在大型应用中,ASP.NET MVC(和 Core MVC)所用的默认组织结构开始成为你的负累.你可以使用两种简单的技术来更新组织方法并及时跟进不断增长的应用程序. Model-View-Controller (MVC) 模式相当成熟,即使在 Microsoft ASP.NET 空间中亦是如此.第一版 ASP.NET MVC 在 2009 年推出,并且在今年夏初全面启动了 ASP.NET Core MVC 平台.至今,随着 ASP.NE

ASP.NET Core 认证与授权[4]:JwtBearer认证

在现代Web应用程序中,通常会使用Web, WebApp, NativeApp等多种呈现方式,而后端也由以前的Razor渲染HTML,转变为Stateless的RESTFulAPI,因此,我们需要一种标准的,通用的,无状态的,与语言无关的认证方式,也就是本文要介绍的JwtBearer认证. 目录 Bearer认证 JWT(JSON WEB TOKEN) 头部(Header) 载荷(Payload) 签名(Signature) 示例 模拟Token 注册JwtBearer认证 添加受保护资源 运行

ASP.NET Core 第一章:简介

英文原版:Introduction to ASP.NET Core 关于ASP.NET Core ASP.NET Core 是一个全新的开源.跨平台框架,可以用它来构建基于网络连接的现代云应用程序,比如:Web 应用,IoT(Internet Of Things,物联网)应用和移动后端等.ASP.NET Core可以运行在 .NET Core 或完整的 .NET Framework 之上,其架构为发布到云端或本地运行的应用提供了一个最佳的开发框架,由开销很小的模块化组件构成,这就保持了你构造解决

ASP.NET Core:使用Dapper和SwaggerUI来丰富你的系统框架

一.概述 1.用VS2017创建如下图的几个.NET Standard类库,默认版本为1.4,你可以通过项目属性进行修改,最高支持到1.6,大概五月份左右会更新至2.0,API会翻倍,很期待! 排名分先后,这里简要说下我对各个类库职责的一个理解. Light.Model:存放实际项目中你用到的所有实体集合,包括数据库表映射实体,请求实体,响应实体,视图显示实体以及一些公共实体类等,同时你还可以根据自己业务的模块功能进行更细致的划分. Light.IRepository:数据库仓储接口,定义你操作

ASP.NET Core 1.0 开发记录

参考页面: http://www.yuanjiaocheng.net/ASPNET-CORE/first.html http://www.yuanjiaocheng.net/ASPNET-CORE/asp-net-core-overview.html http://www.yuanjiaocheng.net/ASPNET-CORE/asp.net-core-environment.html http://www.yuanjiaocheng.net/ASPNET-CORE/newproject.h

创建ASP.NET Core MVC应用程序(3)-基于Entity Framework Core(Code First)创建MySQL数据库表

创建ASP.NET Core MVC应用程序(3)-基于Entity Framework Core(Code First)创建MySQL数据库表 创建数据模型类(POCO类) 在Models文件夹下添加一个User类: namespace MyFirstApp.Models { public class User { public int ID { get; set; } public string Name { get; set; } public string Email { get; se

ASP.NET Core 1.0

跨平台运行ASP.NET Core 1.0 前言 首先提一下微软更名后的叫法: ASP.NET 5 更名为 ASP.NET Core 1.0 .NET Core 更名为 .NET Core 1.0 Entity Framework 7 更名为 Entity Framework Core 1.0 或者简称 EF Core 1.0 现在伴随着ASP.NET Core 1.0 RC2版的更新速度,许多官方文档都跟不上,还停留在RC1版的使用方式上(RC1版是继Beta版之后第一个发布的稳定版本).RC