一、准备

创建一个名为QuickstartIdentityServer的ASP.NET Core Web 空项目(asp.net core 2.2),端口5000
创建一个名为Api的ASP.NET Core Web Api 项目(asp.net core 2.2),端口5001

二、定义服务端配置

1、NuGet命令行

NuGet命令行:Install-Package IdentityServer4

2、在QuickstartIdentityServer项目中添加一个Config.cs文件:

using IdentityServer4.Models;
using IdentityServer4.Test;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks; namespace QuickstartIdentityServer
{
public static class Config
{
public static IEnumerable<IdentityResource> GetIdentityResources()
{
return new IdentityResource[]
{
new IdentityResources.OpenId()
};
} public static IEnumerable<ApiResource> ApiResources()
{
return new[]
{
new ApiResource("socialnetwork", "社交网络")
};
}
public static IEnumerable<Client> Clients()
{
return new[]
{
new Client
{
ClientId = "socialnetwork",
ClientSecrets = new [] { new Secret("secret".Sha256()) },
AllowedGrantTypes = GrantTypes.ResourceOwnerPasswordAndClientCredentials,
AllowedScopes = new [] { "socialnetwork" }
}
};
}
public static IEnumerable<TestUser> Users()
{
return new[]
{
new TestUser
{
SubjectId = "",
Username = "mail@qq.com",
Password = "password"
}
};
}
}
}

3、注入ids4服务

    public class Startup
{
// This method gets called by the runtime. Use this method to add services to the container.
// For more information on how to configure your application, visit https://go.microsoft.com/fwlink/?LinkID=398940
public void ConfigureServices(IServiceCollection services)
{
var builder = services.AddIdentityServer()
.AddDeveloperSigningCredential()
.AddInMemoryIdentityResources(Config.GetIdentityResources())
.AddInMemoryApiResources(Config.ApiResources())//配置资源
.AddInMemoryClients(Config.Clients());//配置客户端
// rest omitted
}
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
} app.UseIdentityServer();//添加到管道中 app.Run(async (context) =>
{
await context.Response.WriteAsync("Hello World!");
});
}
}

三、定义Api端配置

1、通过nuget添加即可:

IdentityServer4.AccessTokenValidation

资源库配置identity server就需要对token进行验证, 这个库就是对access token进行验证的. 通过nuget安装.

2、配置

        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.AddMvcCore()
.AddAuthorization() //将认证服务添加到DI,配置"Bearer"作为默认方案
.AddJsonFormatters(); //注册IdentityServer
services.AddAuthentication(config => {
config.DefaultScheme = "Bearer"; //这个是access_token的类型,获取access_token的时候返回参数中的token_type一致
}).AddIdentityServerAuthentication(option => {//将IdentityServer访问令牌验证处理程序添加到DI中以供身份验证服务使用
option.ApiName = "socialnetwork"; //资源名称,认证服务注册的资源列表名称一致(该Api项目对应的IdentityServer的Api资源,与GetApiResources方法里面的Api名称对应),
option.Authority = "http://localhost:5000"; //认证服务的url
option.RequireHttpsMetadata = false; //是否启用https });
services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1);
}
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
app.UseAuthentication(); //将认证中间件添加到流水线中,以便在对主机的每次呼叫时自动执行认证
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
} app.UseMvc();
}
}

 3、添加WebApi资源服务器(就是拿到Token用来请求WebApi接口)

3.1、已有控制器添加[Authorize]特性,用来测试访问:这里注意要添加[Authorize]特性。用来做验证是否有权限的。没有的话,以上做的没有意义。需要引用命名空间:using Microsoft.AspNetCore.Authorization;

 3.2、在项目Api中新增接口文件IdentityController.cs,用于测试授权

如果你直接访问http://localhost:5001/identity ,你会得到一个401错误,因为调用这个接口需要凭证

这里设置一个Api接口,路由是"identity",跟传统的/controller/action访问路由不同,GET请求访问/identity即可

    [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 });
}
}

三、使用postman来测试接口

我们分别启动这两个项目,5000端口代表授权服务器,5001代表Api服务器
使用postman来测试调用

测试1(从授权服务器拿到token)

测试2(拿token去访问WebApi资源)

把access_token贴到Authorization Header的值里面, 前边要加上Bearer表示类型, 还有一个空格.

或者直接

注意: 测试出现这种情况是

是因为资源配置不一致:

图如下

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.AddAuthentication("Bearer")
.AddJwtBearer("Bearer", options =>
{
options.Authority = "http://localhost:5000";
options.RequireHttpsMetadata = false; options.Audience = "api1";
});
services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1);
}
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
app.UseAuthentication();
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
} app.UseMvc();
}
}

四、IDS4建立Authorization server和Client的更多相关文章

  1. 三、IDS4建立authorization server

    建立authorization server 一.环境搭建 1.创建项目 2.引用NuGet的identityserver4 3.配置asp.net core 管道 打开Startup.cs, 编辑C ...

  2. 使用Identity Server 4建立Authorization Server (1)

    预备知识: http://www.cnblogs.com/cgzl/p/7746496.html 本文内容基本完全来自于Identity Server 4官方文档: https://identitys ...

  3. 使用Identity Server 4建立Authorization Server (3)

    预备知识: http://www.cnblogs.com/cgzl/p/7746496.html 第一部分: http://www.cnblogs.com/cgzl/p/7780559.html 第二 ...

  4. 从头编写asp.net core 2.0 web api 基础框架 (5) + 使用Identity Server 4建立Authorization Server (7) 可运行前后台源码

    前台使用angular 5, 后台是asp.net core 2.0 web api + identity server 4. 从头编写asp.net core 2.0 web api 基础框架: 第 ...

  5. 使用Identity Server 4建立Authorization Server (4)

    预备知识: http://www.cnblogs.com/cgzl/p/7746496.html 第一部分: http://www.cnblogs.com/cgzl/p/7780559.html 第二 ...

  6. ASP.NET Core3.1使用Identity Server4建立Authorization Server

    前言 网上关于Identity Server4的资料有挺多的,之前是一直看杨旭老师的,最近项目中有使用到,在使用.NET Core3.1的时候有一些不同.所以在此记录一下. 预备知识: https:/ ...

  7. 使用Identity Server 4建立Authorization Server

    使用Identity Server 4建立Authorization Server (6) - js(angular5) 客户端 摘要: 预备知识: http://www.cnblogs.com/cg ...

  8. 使用Identity Server 4建立Authorization Server (5)

    预备知识: http://www.cnblogs.com/cgzl/p/7746496.html 第一部分: http://www.cnblogs.com/cgzl/p/7780559.html 第二 ...

  9. 使用Identity Server 4建立Authorization Server (6) - js(angular5) 客户端

    预备知识: http://www.cnblogs.com/cgzl/p/7746496.html 第一部分: http://www.cnblogs.com/cgzl/p/7780559.html 第二 ...

随机推荐

  1. CSS Reset(样式重置)

    CSS Reset,意为重置默认样式.HTML中绝大部分标签元素在网页显示中都有一个默认属性值,通常为了避免重复定义元素样式,需要进行重置默认样式(CSS Reset).举几个例子:1.淘宝(CSS ...

  2. linux清理缓存

    在free -h中查看自己的内存发现在运行一段时间后,有很多内存都被缓存占用, 所以要清理下缓存,增大可用内存 直接进入root账户,输入以下命令 echo 3 > /proc/sys/vm/d ...

  3. GO富集分析 信号通路

    基因富集分析是分析基因表达信息的一种方法,富集是指将基因按照先验知识,也就是基因组注释信息进行分类. 信号通路是指能将细胞外的分子信号经细胞膜传入细胞内发挥效应的一系列酶促反应通路.这些细胞外的分子信 ...

  4. [原创] Delphi 修改新建窗体时候的默认字体格式

    Delphi 修改新建窗体时候的默认字体格式 操作步骤: 1.运行输入“regedit” 2.找到目录(这里默认以Delphi 7为例) HKEY_CURRENT_USER\Software\Borl ...

  5. 替换OSD操作的优化与分析

    http://www.zphj1987.com/2016/09/19/%E6%9B%BF%E6%8D%A2OSD%E6%93%8D%E4%BD%9C%E7%9A%84%E4%BC%98%E5%8C%9 ...

  6. Android中实现Activity的启动拦截之----实现360卫士的安装应用界面

    第一.摘要 今天不是周末,但是我已经放假了,所以就开始我们的技术探索之旅,今天我们来讲一下Android中最期待的技术,就是拦截Activity的启动,其实我在去年的时候,就像实现这个技术了,但是因为 ...

  7. operator函数操作符

    函数操作数() 可以实现将对象当函数使用. class Square{ public: double operator()(double x)const{return x*x;} };

  8. 【CF1210B】Marcin and Training Camp(贪心)

    题意:有n个人,60种技能点,如果第i个人会第j种技能a[i]的二进制表示的第j位就是1,第i个人的价值是b[i] 如果有若干种技能i会j不会,i就会鄙视j 求一种至少两个人的选人方案使得价值和最大, ...

  9. 【转】C#反编译工具

    源地址:https://blog.csdn.net/kongwei521/article/details/54927689 源地址:https://www.cnblogs.com/JamesLi201 ...

  10. 删除STL容器中的元素

    有关stl容器删除元素的问题,错误的代码如下: std::vector<struct> mFriendList; ... std::vector<struct>::iterat ...