前言

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

预备知识: https://www.cnblogs.com/cgzl/p/9405796.html

本文内容参考

如杨旭老师所说,官方文档真的很详细,有时间建议大家看下官方文档。

建立Authorization Server

建立ASP.Net Core项目使用空模板。

项目建立之后,运行方式改为使用控制台运行而不是IIS Express,以便查看各种debug信息。

这个已成为习惯,也是学习杨老师的,确实比较方便,当然如果不喜欢可以不设置,只需要端口号配置的时候对应好就可以的。



修改后文件代码为:

{
"profiles": {
"IdentityServer4.AuthServer": {
"commandName": "Project",
"launchBrowser": true,
"applicationUrl": "http://localhost:5000",
"environmentVariables": {
"ASPNETCORE_ENVIRONMENT": "Development"
}
}
}
}

端口号为5000,此时运行程序,会显示出Hello World!,默认的,没有修改。

安装Identity Server4

点击安装就好啦。

配置Identity Server4

API和客户端

API的配置和之前有所不同,之前是ApiResources,现在分为ApiResourcesApiScopes,后续会说到。

using IdentityServer4.Models;
using IdentityServer4.Test;
using System.Collections.Generic; namespace IdentityServer4.AuthServer.Configuration
{
public class InMemoryConfiguration
{
/// <summary>
/// Api Scopes
/// </summary>
/// <returns></returns>
public static IEnumerable<ApiScope> ApiScopes()
{
return new List<ApiScope>
{
new ApiScope("scope1","scope1")
};
}
/// <summary>
/// ApiResources
/// </summary>
/// <returns></returns>
public static IEnumerable<ApiResource> ApiResources()
{
return new[]
{
new ApiResource
{
Name = "api1",
DisplayName = "My Api1",
Scopes = { "scope1" }
}
};
}
/// <summary>
/// Clients
/// </summary>
/// <returns></returns>
public static IEnumerable<Client> Clients()
{
return new[]
{
new Client
{
ClientId = "client",
AllowedGrantTypes = GrantTypes.ResourceOwnerPasswordAndClientCredentials,
ClientSecrets =
{
new Secret("secret".Sha256())
},
AllowedScopes = { "scope1" }
}
};
}
/// <summary>
/// Users
/// </summary>
/// <returns></returns>
public static IEnumerable<TestUser> Users()
{
return new[]
{
new TestUser
{
SubjectId = "1",
Username = "mail@qq.com",
Password = "password"
}
};
}
}
}

ApiScopes: 这个应该怎么翻译我也不清楚,API范围?如果没理解错的话,就是给之前的ApiResources进行了一个分组。授权的时候会验证Scope

ApiResources:比如官网的第一个demo,可能会有疑问,你怎么知道我是api1呢?其实,就没有验证,只要有授权码就可以访问的。如果说,我只要api1的话,那就用到ApiResources了,生产环境中,也必然是需要用到的。

加载资源和客户端

修改Startup.cs

public void ConfigureServices(IServiceCollection services)
{
services.AddIdentityServer()
.AddDeveloperSigningCredential()
.AddTestUsers(InMemoryConfiguration.Users().ToList())
.AddInMemoryClients(InMemoryConfiguration.Clients())
.AddInMemoryApiScopes(InMemoryConfiguration.ApiScopes())
.AddInMemoryApiResources(InMemoryConfiguration.ApiResources());
}

当然,也需要app.UseIdentityServer();

首次启动时,Identity Server4将创建一个开发人员签名密钥,该文件名为tempkey.rsa。不必将该文件签入源代码管理中,如果不存在该文件将被重新创建。也就是AddDeveloperSigningCredential()。 这个方法只适合用于Identity Server4在单个机器运行, 如果是生产环境你得使用AddSigningCredential()这个方法.

运行一下,发现并没有什么改变,不过打开:http://localhost:5000/.well-known/openid-configuration,则应该看到所谓的发现文档。发现文档是身份服务器中的标准端点。客户端和API将使用发现文档来下载必要的配置数据。

获取Token

打开Postman,按照配置的输入然后试一下

获取到Token,控制台输出如下:

这里是有用户的信息的,但是我们可以把用户信息去掉,然后GrantType改为client_credentials,我们设置的是 ResourceOwnerPasswordAndClientCredentials 这个GrantType,所以使用用户名密码以及使用ClientCredentials都可以。

不过此时控制台会有区别,没有用户信息了。

美化美化UI

Identity Server 4 提供了一套QuickStart UI

https://github.com/IdentityServer/IdentityServer4.Quickstart.UI

此存储库包含UI所需的控制器,模型,视图和CSS文件。只需下载/克隆并将其复制到Web项目中即可。

打开项目根目录,运行Powershell,然后输入命令:

iex ((New-Object System.Net.WebClient).DownloadString('https://raw.githubusercontent.com/IdentityServer/IdentityServer4.Quickstart.UI/main/getmain.ps1'))

不过可能你会遇到我前三次那种错误,嗯,访问不了,那就全局或者先下载下来人工粘贴过去吧~

好了以后我们的项目是酱紫的:

由于有wwwroot下很多静态文件, 所以asp.net core 需要启用服务静态文件的功能: 修改Startup的Configure方法

先看修改前的样子吧

        public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
} app.UseIdentityServer(); app.UseRouting(); app.UseEndpoints(endpoints =>
{
endpoints.MapGet("/", async context =>
{
await context.Response.WriteAsync("Hello World!");
});
});
}

修改后

        public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
} app.UseIdentityServer(); app.UseStaticFiles(); app.UseRouting(); app.UseAuthorization(); app.UseEndpoints(endpoints =>
{
endpoints.MapControllerRoute(
name: "default",
pattern: "{controller=Home}/{action=Index}/{id?}"
);
});
}

是不是抛异常了?

因为我们现在有UI了,所以不要忘记在ConfigureServices里面注册MVC。

        public void ConfigureServices(IServiceCollection services)
{ services.AddControllersWithViews(); services.AddIdentityServer()
.AddDeveloperSigningCredential()
.AddTestUsers(InMemoryConfiguration.Users().ToList())
.AddInMemoryClients(InMemoryConfiguration.Clients())
.AddInMemoryApiScopes(InMemoryConfiguration.ApiScopes())
.AddInMemoryApiResources(InMemoryConfiguration.ApiResources());
}

然后运行一下试试:

登录一下~

好了,现在我们已经可以登录成功了。

登录界面可以自定义的~,OK,今天就到这里

计划

接下来会说一下

  • 建立我们的API项目并使用Token测试接口
  • 建立一个MVC客户端项目访问我们的API
  • 建立一个JS(Vue)客户端访问我们的API项目

End

推广下自己的公众号一个逗逼的程序员,主要记录自己工作中解决问题的思路分享及学习过程中的笔记。绝对不会程序员贩卖程序员的焦虑来割韭菜

ASP.NET Core3.1使用Identity Server4建立Authorization Server的更多相关文章

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

    前言 建立Web Api项目 在同一个解决方案下建立一个Web Api项目IdentityServer4.WebApi,然后修改Web Api的launchSettings.json.参考第一节,当然 ...

  2. 从头编写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 基础框架: 第 ...

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

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

  4. 使用Identity Server 4建立Authorization Server

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

  5. 三、IDS4建立authorization server

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

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

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

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

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

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

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

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

    第一部分: http://www.cnblogs.com/cgzl/p/7780559.html 第一部分主要是建立了一个简单的Identity Server. 接下来继续: 建立Web Api项目 ...

随机推荐

  1. TensorFlow从0到1之TensorFlow实现多元线性回归(16)

    在 TensorFlow 实现简单线性回归的基础上,可通过在权重和占位符的声明中稍作修改来对相同的数据进行多元线性回归. 在多元线性回归的情况下,由于每个特征具有不同的值范围,归一化变得至关重要.这里 ...

  2. matplotlib添加子图(拼图功能)

    我们已经知道,matplotlib是python中的一个十分好用的作图库,它的简单的使用方法可以在之前的随笔中找到.传送门:https://www.cnblogs.com/chester-cs/p/1 ...

  3. 从字符串到常量池,一文看懂String类设计

    从一道面试题开始 看到这个标题,你肯定以为我又要讲这道面试题了 // 这行代码创建了几个对象? String s3 = new String("1"); 是的,没错,我确实要从这里 ...

  4. Spring中的AOP(一)

    1. Spring AOP实现机制 Spring采用动态代理机制和字节码生成技术实现AOP.与最初的AspectJ采用编译器将横切逻辑织入目标对象不同,动态代理机制和字节码生成都是在运行期间为目标对象 ...

  5. SSM框架出现500的错误解决办法

    1,先确认pom.xml中有没有导入项目依赖, 2,发现导入之后还是报500.点击File->Project  Structure->Artifacts 点击SSM右键,选择put int ...

  6. Java笔试面试总结—try、catch、finally语句中有return 的各类情况

    前言 之前在刷笔试题和面试的时候经常会遇到或者被问到 try-catch-finally 语法块的执行顺序等问题,今天就抽空整理了一下这个知识点,然后记录下来. 正文 本篇文章主要是通过举例的方式来阐 ...

  7. 在Ubuntu上实现人脸识别登录

    安装Howdy: howdy项目地址 sudo add-apt-repository ppa:boltgolt/howdy sudo apt update sudo apt install howdy ...

  8. 学习Java的Day02

    知识点 数组: 一维数组   声明: 类型[] 数组名;([] 在前后没有影响,一般写在名称前.) 创建数组  数组名 =  new 类型[数组长度]. 数组索引从0开始.获取数组长度:数组名.len ...

  9. NodeMCU手把手入门:配置NodeMCU ESP8266开发板环境及点亮LED灯

    之前一直在玩树莓派,最近实验室买了些NodeMCU就想着玩一玩,没想到挺有意思的.其实树莓派能实现的功能,它大部分也可以,价格比派也便宜不少,舍不得买派的同学可以先买这个开发板玩一玩. 本文主要介绍了 ...

  10. Js数据类型、Json格式、Json对象、Json字符串

    数据类型,从结构上看,所有的数据最终都可以分成三种类型: 第一种类型是scalar(标量),也就是一个单独的string(字符串)或数字(numbers),比如“北京”这个单独的词. 第二种类型是se ...