一. 新建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)基本操作的更多相关文章

  1. .net core Identity集成IdentityServer(3) 一键登出

    在客户端程序, 我们补充一键登出操作. 使用了idsv之后, 退出的操作需要删除本地cookie, 然后去请求认证服务器, 也删除认证服务器的cookie. 官网给的退出的代码 public asyn ...

  2. .net core Identity集成IdentityServer(2) 实现IprofileService接口在accesstoken中增加自定义claims

    导读 1. 如何添加自定义的claims. 前请提要 目前我们拥有了三个web应用. localhost:40010, 验证服务器 localhost:40011, mvc客户端, 充当webapp请 ...

  3. .net core identity集成微信授权登录

    最快的方式是直接nuget安装AspNetCore.Authentication.WeChat包. 想要知道是如何实现的,可以看下面github上面的源码. 源码在这里:https://github. ...

  4. 从零搭建一个IdentityServer——集成Asp.net core Identity

    前面的文章使用Asp.net core 5.0以及IdentityServer4搭建了一个基础的验证服务器,并实现了基于客户端证书的Oauth2.0授权流程,以及通过access token访问被保护 ...

  5. IdentityServer(12)- 使用 ASP.NET Core Identity

    IdentityServer具有非常好的扩展性,其中用户及其数据(包括密码)部分你可以使用任何想要的数据库进行持久化. 如果需要一个新的用户数据库,那么ASP.NET Core Identity是你的 ...

  6. IdentityServer4 中文文档 -14- (快速入门)使用 ASP.NET Core Identity

    IdentityServer4 中文文档 -14- (快速入门)使用 ASP.NET Core Identity 原文:http://docs.identityserver.io/en/release ...

  7. IdentityServer4【QuickStart】之使用asp.net core Identity

    使用asp.net core Identity IdentityServer灵活的设计中有一部分是可以将你的用户和他们的数据保存到数据库中的.如果你以一个新的用户数据库开始,那么,asp.net co ...

  8. 第16章 使用ASP.NET Core Identity - Identity Server 4 中文文档(v1.0.0)

    注意 对于任何先决条件(例如模板),首先要查看概述. IdentityServer旨在提供灵活性,其中一部分允许您为用户及其数据(包括账户密码)使用所需的任何数据库.如果您从新的用户数据库开始,那么A ...

  9. asp.net core系列 53 IdentityServer4 (IS4)介绍

    一.概述 在物理层之间相互通信必须保护资源,需要实现身份验证和授权,通常针对同一个用户存储.对于资源安全设计包括二个部分,一个是认证,一个是API访问. 1 认证 认证是指:应用程序需要知道当前用户的 ...

随机推荐

  1. 学习爬虫Scrapy遇到的错误

    1. 这个问题是由于路径中含有中文,导致编码格式出错的问题, 查看错误方法,进入到ntpath.py文件中去,找到85行,然后,print 一下result_path,因为后面报出的错误,就是因为这段 ...

  2. tensorflow学习之(五)构造简单神经网络 并展示拟合过程

    # def 添加层 如何构造神经网络 并展示拟合过程 import tensorflow as tf import numpy as np import matplotlib.pyplot as pl ...

  3. ActiveMQ_5死信队列

    activemq死信队列 DLQ-死信队列(Dead Letter Queue)用来保存处理失败或者过期的消息. 出现以下情况时,消息会被redelivered: A transacted sessi ...

  4. Linux 第四天

    1.文件搜索命令 1)locate 在文件资料库中查找文件(需要文件资料库中有,新建的文件查不到,需要手动更新,updatedb.查不到/tmp目录下的文件) 语法:locate 文件名 常用选项: ...

  5. VIP之Switch

    Switch II 最大能连接12路输入与12路输出 不能合并数据数 每个输入可以驱动多个输出 每个输出只能被一个输入驱动 当输入没有连接到输出时,可以禁止掉 每个被禁止的输入可以设置成停止或者消耗模 ...

  6. IIS 设置文件传输大小限制

    IIS默认传输文件大小为30M,最大允许传输为2G. 1.通过webconfig配置节点设置 在IIS 6.0 设置如下配置节点: 但是IIS 7.0-8.0还要做添加如下配置节点才能正确,否则还是默 ...

  7. QQ网页弹窗

    QQ网页弹窗 1.网址:http://shang.qq.com/v3/index.html 2.选推广工具,提示语随便写 3.建一个html 网页,并把代码拷进去. 4.双击网页,就可以打开了.(用E ...

  8. 4.ASP.NET MVC 5.0 视图之模型绑定

    大家好,这篇文章,我将向大家介绍ASP.NET MVC的模型视图绑定,ASP.MVC的模型绑定分为两种:一种是动态绑定[Dynamic Binding];还有一种就是强类型绑定[Strongly ty ...

  9. Codeforces Round #553 (Div. 2) C. Problem for Nazar 数学

    题意:从奇数列 1 3 5 7 9 ....  偶数列2 4 6 8 10...分别轮流取 1 2 4 ....2^n 个数构成新数列 求新数列的区间和 (就一次询问) 思路:首先单次区间和就是一个简 ...

  10. koa中返回404并且刷新后才正常的解决方案

    概述 这几天学习koa2,有一些心得,记录下来,供以后开发时参考,相信对其他人也有用. 起因 这几天学习koa2,写的代码执行时有一个奇怪的bug:明明能够返回数据,却有时正常返回数据,有时偏偏给你返 ...