简介

大多数软件的相互沟通图:客户端与Web应用程序的访问、应用与Web api、api与api……相互沟通则需要授权、身份验证

IdentityServer3的功能:Web认证、SSO单点登录、Web Api访问权限(常用的这三个)

RP:依赖方

OP:OpenID Provider

IP:Id Provider

STS:安全令牌服务

Scope:范围标识(身份、资源)

用户(User)访问客户端、客户端(Client: 如Web或APP)向IdentityServer请求token,OP返回身份token\访问token,每一种资源都有一个标识范围(身份信息,授权资源信息都有一个对应的scope标识),OP会获取资源(RP)的Scope

开始使用IdentityServer3

1、新建一个控制台应用作为IdentityServer

安装:install-package identityserver3

新建Client.cs:在IdentityServer注册Client信息

using IdentityServer3.Core.Models;
using System.Collections.Generic; namespace IdSrv
{
static class Clients
{
public static List<Client> Get()
{
return new List<Client>
{
// no human involved
new Client
{
ClientName = "Silicon-only Client",
ClientId = "silicon",
Enabled = true,
AccessTokenType = AccessTokenType.Reference, Flow = Flows.ClientCredentials, ClientSecrets = new List<Secret>
{
new Secret("F621F470-9731-4A25-80EF-67A6F7C5F4B8".Sha256())
}, AllowedScopes = new List<string>
{
"api1"
}
}, // human is involved
new Client
{
ClientName = "Silicon on behalf of Carbon Client",
ClientId = "carbon",
Enabled = true,
AccessTokenType = AccessTokenType.Reference, Flow = Flows.ResourceOwner, ClientSecrets = new List<Secret>
{
new Secret("21B5F798-BE55-42BC-8AA8-0025B903DC3B".Sha256())
}, AllowedScopes = new List<string>
{
"api1"
}
}
};
}
}
}

Client.cs

Scopes.cs注册范围标识

using System.Collections.Generic;
using IdentityServer3.Core.Models; namespace IdSrv
{
static class Scopes
{
public static List<Scope> Get()
{
return new List<Scope>
{
new Scope
{
Name = "api1"
}
};
}
}
}

Scopes.cs

Users.cs注册用户

using IdentityServer3.Core.Services.InMemory;
using System.Collections.Generic; namespace IdSrv
{
static class Users
{
public static List<InMemoryUser> Get()
{
return new List<InMemoryUser>
{
new InMemoryUser
{
Username = "bob",
Password = "secret",
Subject = ""
},
new InMemoryUser
{
Username = "alice",
Password = "secret",
Subject = ""
}
};
}
}
}

Users.cs

配置Owin;这里把IdentityServer作为Owin的中间件配置一下

using Owin;
using IdentityServer3.Core.Configuration; namespace IdSrv
{
class Startup
{
public void Configuration(IAppBuilder app)
{
var options = new IdentityServerOptions
{
Factory = new IdentityServerServiceFactory()
.UseInMemoryClients(Clients.Get())
.UseInMemoryScopes(Scopes.Get())
.UseInMemoryUsers(Users.Get()), RequireSsl = false
}; app.UseIdentityServer(options);
}
}
}

Startup.cs

Program.cs

using Microsoft.Owin.Hosting;
using System; namespace IdSrv
{
class Program
{
static void Main(string[] args)
{ // hosting identityserver
using (WebApp.Start<Startup>("http://localhost:5000"))
{
Console.WriteLine("server running...");
Console.ReadLine();
}
}
}
}

Program.cs

2、新建控制台应用作为Client

namespace Client
{
class Program
{
static void Main(string[] args)
{
var response = GetClientToken();//获取令牌
CallApi(response);//实用令牌访问资源 response = GetUserToken();
CallApi(response);
} static void CallApi(TokenResponse response)
{
var client = new HttpClient();
client.SetBearerToken(response.AccessToken); Console.WriteLine(client.GetStringAsync("http://localhost:14869/test").Result);
} static TokenResponse GetClientToken()
{
var client = new TokenClient(
"http://localhost:5000/connect/token",
"silicon",
"F621F470-9731-4A25-80EF-67A6F7C5F4B8"); return client.RequestClientCredentialsAsync("api1").Result;
} static TokenResponse GetUserToken()
{
var client = new TokenClient(
"http://localhost:5000/connect/token",
"carbon",
"21B5F798-BE55-42BC-8AA8-0025B903DC3B"); return client.RequestResourceOwnerPasswordAsync("bob", "secret", "api1").Result;
}
}
}

Program.cs

3、新建Web API作为资源(RP)

Owin配置

using Microsoft.Owin;
using Owin;
using System.Web.Http;
using IdentityServer3.AccessTokenValidation; [assembly: OwinStartup(typeof(Apis.Startup))] namespace Apis
{
public class Startup
{
public void Configuration(IAppBuilder app)
{
// accept access tokens from identityserver and require a scope of 'api1'
app.UseIdentityServerBearerTokenAuthentication(new IdentityServerBearerTokenAuthenticationOptions
{
Authority = "http://localhost:5000",
ValidationMode = ValidationMode.ValidationEndpoint, RequiredScopes = new[] { "api1" }
}); // configure web api
var config = new HttpConfiguration();
config.MapHttpAttributeRoutes(); // require authentication for all controllers
config.Filters.Add(new AuthorizeAttribute()); app.UseWebApi(config);
}
}
}

Startup

Controller

using System.Security.Claims;
using System.Web.Http; namespace Apis
{
[Route("test")]
public class TestController : ApiController
{
public IHttpActionResult Get()
{
var caller = User as ClaimsPrincipal; var subjectClaim = caller.FindFirst("sub");
if (subjectClaim != null)
{
return Json(new
{
message = "OK user",
client = caller.FindFirst("client_id").Value,
subject = subjectClaim.Value
});
}
else
{
return Json(new
{
message = "OK computer",
client = caller.FindFirst("client_id").Value
});
}
}
}
}

Controller.cs

资源:

官网:https://identityserver.io/

IdentityServer3文档:https://identityserver.github.io/Documentation/docsv2/

示例与源码:https://identityserver.github.io/Documentation/

IdentityServer3:.NET开源OpenID和OAuth2架构的更多相关文章

  1. 首发福利!全球第一开源ERP Odoo系统架构部署指南 电子书分享

    引言 Odoo,以前叫OpenERP,是比利时Odoo S.A.公司开发的一个企业应用软件套件,开源套件包括一个企业应用快速开发平台,以及几千个Odoo及第三方开发的企业应用模块.Odoo适用于各种规 ...

  2. 《开源自主OdooERP部署架构指南》试读:第二章数据库服务构建

    文/开源智造联合创始人老杨 本文来自<开源自主OdooERP部署架构指南>的试读章节.书籍尚未出版,请勿转载.欢迎您反馈阅读意见. 使用apt.postgresql.org 您可以选择使用 ...

  3. 一个功能完备的.NET开源OpenID Connect/OAuth 2.0框架——IdentityServer3

    今天推荐的是我一直以来都在关注的一个开源的OpenID Connect/OAuth 2.0服务框架--IdentityServer3.其支持完整的OpenID Connect/OAuth 2.0标准, ...

  4. 入门教程:.NET开源OpenID Connect 和OAuth解决方案IdentityServer v3 创建简单的OAuth2.0服务器,客户端和API(三)

    本教程的目的在于创造尽可能简单的identityserver安装作为一个oauth2授权服务器.这应该能够让你了解一些基本功能和配置选项(完整的源代码可以发现在这里).在后面的文档中会介绍更多的高级功 ...

  5. .NET开源OpenID和OAuth解决方案Thinktecture IdentityServer

    现代的应用程序看起来像这样: 典型的交互操作包括: 浏览器与 web 应用程序进行通信 Web 应用程序与 web Api (有时是在他们自己的有时代表用户) 通信 基于浏览器的应用程序与 web A ...

  6. OpenID Connect + OAuth2.0

    一.问题的提出 现代应用程序或多或少都是如下这样的架构: 在这种情况下,前端.中间层和后端都需要进行验证和授权来保护资源,所以不能仅仅在业务逻辑层或者服务接口层来实现基础的安全功能.为了解决这样的问题 ...

  7. 入门教程:.NET开源OpenID Connect 和OAuth解决方案IdentityServer v3 术语(二)

    你应该知道的在文档和对象模型中使用一些特定的术语: OpenID Connect Provider (OP) 授权服务器 Thinktecture IdentityServer v3 是一个.NET ...

  8. 入门教程:.NET开源OpenID Connect 和OAuth解决方案IdentityServer v3 介绍 (一)

    现代的应用程序看起来像这样: 典型的交互操作包括: 浏览器与 web 应用程序进行通信 Web 应用程序与 web Api (有时是在他们自己的有时代表用户) 通信 基于浏览器的应用程序与 web A ...

  9. Android强大的开源库与系统架构工具

    后来加上的,因为太强大了,android上百个可立即使用的开源库介绍:https://github.com/Trinea/android-open-project 一款功能强大且实用的开发工具可以为开 ...

随机推荐

  1. Excel相关操作

    public static bool DataSetToExcel(DataSet dataSet, string filePath, bool isShowExcle = true) { DataT ...

  2. hdu3374 String Problem【最小表示法】【exKMP】

    String Problem Time Limit: 2000/1000 MS (Java/Others)    Memory Limit: 32768/32768 K (Java/Others)To ...

  3. TOP100summit:【分享实录-猫眼电影】业务纵横捭阖背后的技术拆分与融合

    王洋:猫眼电影商品业务线技术负责人.技术专家.主导了猫眼商品供应链和交易体系从0到1的建设,并在猫眼与美团拆分.与点评电影业务融合过程中,从技术层面保障了商品业务的平稳切换,同时也是美团点评<领 ...

  4. SmartStore.Net、NopCommerce 全局异常处理、依赖注入、代码研究

    以下是本人最近对NopCommerce和SmartStore.net部分代码的研究和总结,主要集中于:依赖注入.异常处理.对象映射.系统缓存.日志这些方面,供大家参考. NOP 3.8 /// < ...

  5. Ubuntu系统中各种文件颜色的含义

    蓝 色:文件夹 ,ls -l或ll时可以看到权限部分的第1个字母是d红色:压缩文件   绿色:可执行文件,包括jar白色:文本文件红色闪烁:错误的符号链接淡蓝色:符号链接黄色:设备文件灰色:其它文件 ...

  6. [No0000141]Outlook,设置全局已读回执

    Outlook,设置全局已读回执 文件->选项

  7. EM学习-思想和代码

    EM算法的简明实现 当然是教学用的简明实现了,这份实现是针对双硬币模型的. 双硬币模型 假设有两枚硬币A.B,以相同的概率随机选择一个硬币,进行如下的抛硬币实验:共做5次实验,每次实验独立的抛十次,结 ...

  8. 是时候给Xcode瘦身了

    我的Xcode 用的很久了,是从6.0之后一直慢慢升级来的. 最近CleanMyMac 一直提示磁盘空间不足... 扫描一下: 用户数据中竟然有接近17G的数据. 打开Finder使用快捷键comma ...

  9. Search,look for,find,seek(找)用法

    舉個例子 ----> 你可以幫我找我的眼鏡嗎? SEARCH Search是仔細.徹底尋找/搜尋的意思. 比較少人會說 Can you help me search for my glasses ...

  10. 内部排序->选择排序->堆排序

    文字描述 堆排序中,待排序数据同样可以用完全二叉树表示, 完全二叉树的所有非终端结点的值均不大于(或小于)其左.右孩子结点的值.由此,若序列{k1, k2, …, kn}是堆,则堆顶元素(或完全二叉树 ...