.net core Identity集成IdentityServer4 (1)基本操作
一. 新建asp.net core identity项目
新建项目->asp.net core web应用程序-> web应用程序(模型视图控制器)&更改身份验证为个人.
新建一个空数据库, 然后在appsettings中的连接字符串指向该空库.
"DefaultConnection": "Data Source=.;Initial Catalog=IdentityDBTest;Integrated Security=False;Persist Security Info=False;User ID=sa;Password=sa1234;MultipleActiveResultSets=True;Pooling=True;Min Pool Size=1;Max Pool Size=300;"
cmd进入项目根目录, 然后执行 dotnet ef database update -c ApplicationDbContext
会在指定的空库中创建Identity的相应数据表.
修改launchSettings的Project执行方式的url为 http://localhost:40010
在Startup.cs中添加如下代码, 配置asp.net core identity的用户相关信息
public void ConfigureServices(IServiceCollection services)
{
services.AddDbContext<ApplicationDbContext>(options =>
options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection"))); services.AddIdentity<ApplicationUser, IdentityRole>()
.AddEntityFrameworkStores<ApplicationDbContext>()
.AddDefaultTokenProviders(); services.Configure<IdentityOptions>(options =>
{
// Password settings
options.Password.RequireDigit = false;
options.Password.RequiredLength = ;
options.Password.RequireNonAlphanumeric = false;
options.Password.RequireUppercase = false;
options.Password.RequireLowercase = false;
//options.Password.RequiredUniqueChars = 6; // Lockout settings
//options.Lockout.DefaultLockoutTimeSpan = TimeSpan.FromMinutes(30);
//options.Lockout.MaxFailedAccessAttempts = 10;
//options.Lockout.AllowedForNewUsers = true; // User settings
options.User.RequireUniqueEmail = true;
}); services.ConfigureApplicationCookie(options =>
{
// Cookie settings
options.Cookie.Name = "identityCookieJJL";
options.Cookie.HttpOnly = true;
options.ExpireTimeSpan = TimeSpan.FromMinutes();
// If the LoginPath isn't set, ASP.NET Core defaults
// the path to /Account/Login.
options.LoginPath = "/Account/Login";
// If the AccessDeniedPath isn't set, ASP.NET Core defaults
// the path to /Account/AccessDenied.
options.AccessDeniedPath = "/Account/AccessDenied";
options.SlidingExpiration = true;
}); // Add application services.
services.AddTransient<IEmailSender, EmailSender>();
启动并运行, 注册一个用户, 并且确保登录成功
二. 集成IdentityServer
添加IdentityServer4.aspnetIdentity的Nuget包, 同时会自动添加IdentityServer4.
在根目录下新建一个AuthorizationConfig.cs类.
添加如下代码
/// <summary>
/// 哪些API可以使用这个authorization server.
/// </summary>
/// <returns></returns>
public static IEnumerable<ApiResource> ApiResources()
{
return new[]
{
new ApiResource("ProductApi", "微服务之产品Api")
};
}
public static IEnumerable<IdentityResource> GetIdentityResources()
{
return new List<IdentityResource> {
new IdentityResources.OpenId(),
new IdentityResources.Profile()
};
}
public static IEnumerable<Client> Clients()
{
return new[]
{
new Client
{
ClientId = "WebClientImplicit",
ClientSecrets = new [] { new Secret("SecretKey".Sha256()) },
AllowedGrantTypes = GrantTypes.Implicit,
AllowAccessTokensViaBrowser = true, RedirectUris = { http://localhost:40011/signin-oidc }, // where to redirect to after logout
PostLogoutRedirectUris = { http://localhost:40011/signout-callback-oidc }, AllowedScopes = new List<string>
{
IdentityServerConstants.StandardScopes.OpenId,
IdentityServerConstants.StandardScopes.Profile,
"ProductApi",
IdentityServerConstants.ClaimValueTypes.Json
}
,
RequireConsent=false,//不需要确认授权页面,方便直接跳转
AlwaysIncludeUserClaimsInIdToken=true
}
};
}
在StartUp.cs中的服务注册方法中添加代码
// configure identity server with in-memory stores, keys, clients and scopes
//我们在将Asp.Net Identity添加到DI容器中时,一定要把注册IdentityServer放在Asp.Net Identity之后,
//因为注册IdentityServer会覆盖Asp.Net Identity的一些配置,这个非常重要。
services.AddIdentityServer()
.AddDeveloperSigningCredential()
.AddInMemoryPersistedGrants()
.AddInMemoryIdentityResources(AuthorizationConfig.GetIdentityResources())
.AddInMemoryApiResources(AuthorizationConfig.ApiResources())
.AddInMemoryClients(AuthorizationConfig.Clients())
.AddAspNetIdentity<ApplicationUser>(); services.AddMvc();
在选暖宝的Configure使用注册项的方法中添加如下代码
// app.UseAuthentication(); // not needed, since UseIdentityServer adds the authentication middleware
app.UseIdentityServer();
接下来使用命令dotnet run启动项目
三. 新建地址为http://localhost:40011/的asp.net core mvc项目, 命名为MvcClientImplict
新建项目的方法和上面的.net core identity一样, 只是不需要个人验证. 修改launchSettings的端口是40010, 对应identityserver的配置url
nuget获取 identitymodel
public void ConfigureServices(IServiceCollection services)
{
services.AddAuthentication(options =>
{
options.DefaultScheme = "Cookies";
options.DefaultChallengeScheme = "oidc";
})
.AddCookie("Cookies")
.AddOpenIdConnect("oidc", options =>
{
options.SignInScheme = "Cookies"; options.Authority = "http://localhost:40010";
options.RequireHttpsMetadata = false;
//options.ResponseType = "id_token code";
options.ResponseType = "id_token token"; options.ClientId = "WebClientImplicit";
options.SaveTokens = true;
options.ClientSecret = "SecretKey"; options.Scope.Add("ProductApi");
//options.Scope.Add("offline_access"); options.GetClaimsFromUserInfoEndpoint = true;// }); services.AddMvc();
}
下面也别忘了 app.UseAuthentication()
运行并验证授权成功成功

四. 新建一个webApi(端口40012), 配置受到identityserver的保护
nuget :IdentityServer4.AccessTokenValidation
public void ConfigureServices(IServiceCollection services)
{
services.AddAuthentication("Bearer")
.AddIdentityServerAuthentication(option =>
{
option.Authority = "http://localhost:40010";//这里填写/.well-known/openid-configuration里看到的issuer
option.RequireHttpsMetadata = false; option.ApiName = "ProductApi";
option.ApiSecret = "SecretKey";
});
services.AddMvc();
}
app.UseAuthentication();
在默认的api上添加验证
[Authorize]
[Route("api/[controller]")]
public class ValuesController : Controller
{

在webapi里面新建一个 controller
[Route("api/[controller]")]
[Authorize]
public class IdentityController : ControllerBase
{
[HttpGet]
public IActionResult Get()
{
return new JsonResult(from c in User.Claims select new { c.Type, c.Value });
}
}

.net core Identity集成IdentityServer4 (1)基本操作的更多相关文章
- .net core Identity集成IdentityServer(3) 一键登出
在客户端程序, 我们补充一键登出操作. 使用了idsv之后, 退出的操作需要删除本地cookie, 然后去请求认证服务器, 也删除认证服务器的cookie. 官网给的退出的代码 public asyn ...
- .net core Identity集成IdentityServer(2) 实现IprofileService接口在accesstoken中增加自定义claims
导读 1. 如何添加自定义的claims. 前请提要 目前我们拥有了三个web应用. localhost:40010, 验证服务器 localhost:40011, mvc客户端, 充当webapp请 ...
- .net core identity集成微信授权登录
最快的方式是直接nuget安装AspNetCore.Authentication.WeChat包. 想要知道是如何实现的,可以看下面github上面的源码. 源码在这里:https://github. ...
- 从零搭建一个IdentityServer——集成Asp.net core Identity
前面的文章使用Asp.net core 5.0以及IdentityServer4搭建了一个基础的验证服务器,并实现了基于客户端证书的Oauth2.0授权流程,以及通过access token访问被保护 ...
- IdentityServer(12)- 使用 ASP.NET Core Identity
IdentityServer具有非常好的扩展性,其中用户及其数据(包括密码)部分你可以使用任何想要的数据库进行持久化. 如果需要一个新的用户数据库,那么ASP.NET Core Identity是你的 ...
- IdentityServer4 中文文档 -14- (快速入门)使用 ASP.NET Core Identity
IdentityServer4 中文文档 -14- (快速入门)使用 ASP.NET Core Identity 原文:http://docs.identityserver.io/en/release ...
- IdentityServer4【QuickStart】之使用asp.net core Identity
使用asp.net core Identity IdentityServer灵活的设计中有一部分是可以将你的用户和他们的数据保存到数据库中的.如果你以一个新的用户数据库开始,那么,asp.net co ...
- 第16章 使用ASP.NET Core Identity - Identity Server 4 中文文档(v1.0.0)
注意 对于任何先决条件(例如模板),首先要查看概述. IdentityServer旨在提供灵活性,其中一部分允许您为用户及其数据(包括账户密码)使用所需的任何数据库.如果您从新的用户数据库开始,那么A ...
- asp.net core系列 53 IdentityServer4 (IS4)介绍
一.概述 在物理层之间相互通信必须保护资源,需要实现身份验证和授权,通常针对同一个用户存储.对于资源安全设计包括二个部分,一个是认证,一个是API访问. 1 认证 认证是指:应用程序需要知道当前用户的 ...
随机推荐
- php判断语句
编写代码时,可以为不同的情况执行不同的动作.可以使用判断条件语句来实现. if...else...elseif 例子一: <?php $t=date("H"); if ($t ...
- STL中的容器作为返回值
分别以函数返回值方式和参数传引用方式测试了vector.map两种容器,代码如下: // testContainer.cpp : Defines the entry point for the con ...
- ASP.NET Core 注入和获取 AppSettings 配置
ASP.NET Core 项目中有个appsettings.json配置文件,用于存放一些配置信息,比如数据库连接字符串等,但访问的话,只能在 ASP.NET Core 项目中获取,如果我们在其他项目 ...
- SDWebImage之SDImageCache
SDImageCache和SDWebImageDownloader是SDWebImage库的最重要的两个部件,它们一起为SDWebImageManager提供服务,来完成图片的加载.SDImageCa ...
- 枚举类型enum详解——C语言
enum enum是C语言中的一个关键字,enum叫枚举数据类型,枚举数据类型描述的是一组整型值的集合(这句话其实不太妥当),枚举型是预处理指令#define的替代,枚举和宏其实非常类似,宏在预处理阶 ...
- phpMyAdmin 4.7.x CSRF 漏洞利用
作者:Ambulong phpMyAdmin是个知名MySQL/MariaDB在线管理工具,phpMyAdmin团队在4.7.7版本中修复了一个危害严重的CSRF漏洞(PMASA-2017-9),攻击 ...
- Struts2再爆远程命令执行漏洞![W3bSafe]Struts2-048 Poc Shell及防御修复方案抢先看!
漏洞概述 Apache Struts是美国阿帕奇(Apache)软件基金会负责维护的一个开源项目,是一套用于创建企业级Java Web应用的开源MVC框架.在Struts 2.3.x 系列的 Show ...
- 开源播放器 ijkplayer (一) :使用Ijkplayer播放直播视频
1.ijkplayer 编码 IjkPlayer支持硬解码和软解码. 软解码时不会旋转视频角度这时需要你通过onInfo的what == IMediaPlayer.MEDIA_INFO_VIDEO_R ...
- C#6.0语言规范(一) 介绍
C#(发音为“See Sharp”)是一种简单,现代,面向对象,类型安全的编程语言.C#源于C语言系列,对C,C ++和Java程序员来说很熟悉.EC#International将EC#标准化为ECM ...
- MySQL 组提交(group commit)
目录 前言 改进 原理 实现 参数 注意 前言 操作系统使用页面缓存来填补内存和磁盘访问的差距 对磁盘文件的写入会先写入道页面缓存中 由操作系统来决定何时将修改过的脏页刷新到磁盘 确保修改已经持久化到 ...