.net core web API使用Identity Server4 身份验证
一、新建一个.net core web项目作为Identity server 4验证服务。
选择更改身份验证,然后再弹出的对话框里面选择个人用户账户。
nuget 安装Identity server相关的依赖包
添加Identity server相关的配置,首先新建config文件加,然后添加IdentityServer.cs,文件中代码如下:
对于相关配置想做详细了解的同学可以参考园友 晓晨Master的identity server 系列博客 https://www.cnblogs.com/stulzq/p/9019446.html
using IdentityModel;
using IdentityServer4;
using IdentityServer4.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks; namespace WebIdentityServer.Config
{
public static class IdentityServer
{
public static List<Client> GetClients()
{
return new List<Client>()
{
new Client
{
ClientId = "mvc",
ClientName = "MVC Client",
AllowedGrantTypes = GrantTypes.ResourceOwnerPassword, RequireConsent = false, ClientSecrets =
{
new Secret("secret".Sha256())
}, RedirectUris = { "http://localhost:5002/signin-oidc" },
PostLogoutRedirectUris = { "http://localhost:5002/signout-callback-oidc" }, AllowedScopes =
{
IdentityServerConstants.StandardScopes.OpenId,
IdentityServerConstants.StandardScopes.Profile,
"api1"
},
AllowOfflineAccess = false,
AccessTokenType = AccessTokenType.Jwt,
}
};
} public static IEnumerable<IdentityResource> GetIdentityResources()
{
var customProfile = new IdentityResource(
name: "custom.profile",
displayName: "Custom profile",
claimTypes: new[] { "name", "email", "status" }); return new List<IdentityResource>
{
new IdentityResources.OpenId(),
new IdentityResources.Profile(),
customProfile
};
} public static IEnumerable<ApiResource> GetApiResources()
{
return new[]
{
// simple API with a single scope (in this case the scope name is the same as the api name)
new ApiResource("api1", "Some API 1"), // expanded version if more control is needed
new ApiResource
{
Name = "api2", // secret for using introspection endpoint
ApiSecrets =
{
new Secret("secret".Sha256())
}, // include the following using claims in access token (in addition to subject id)
UserClaims = { JwtClaimTypes.Name, JwtClaimTypes.Email }, // this API defines two scopes
Scopes =
{
new Scope()
{
Name = "api2.full_access",
DisplayName = "Full access to API 2",
},
new Scope
{
Name = "api2.read_only",
DisplayName = "Read only access to API 2"
}
}
}
};
}
}
}
在Startup类中添加如下配置:
1. 在ConfigureServices方法中添加如下代码配置
public void ConfigureServices(IServiceCollection services)
{
services.AddDbContext<ApplicationDbContext>(options =>
options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection"))); services.AddIdentity<ApplicationUser, IdentityRole>()
.AddEntityFrameworkStores<ApplicationDbContext>()
.AddDefaultTokenProviders(); // Add application services.
services.AddTransient<IEmailSender, EmailSender>(); services.AddIdentityServer()
.AddDeveloperSigningCredential()
.AddInMemoryPersistedGrants()
.AddInMemoryIdentityResources(IdentityServer.GetIdentityResources())
.AddInMemoryApiResources(IdentityServer.GetApiResources())
.AddInMemoryClients(IdentityServer.GetClients())
.AddAspNetIdentity<ApplicationUser>(); services.AddMvc();
}
2. 在Configure方法中添加如下代码配置
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
if (env.IsDevelopment())
{
app.UseBrowserLink();
app.UseDeveloperExceptionPage();
app.UseDatabaseErrorPage();
}
else
{
app.UseExceptionHandler("/Home/Error");
} app.UseStaticFiles(); // app.UseAuthentication(); // not needed, since UseIdentityServer adds the authentication middleware
app.UseIdentityServer(); app.UseMvc(routes =>
{
routes.MapRoute(
name: "default",
template: "{controller=Home}/{action=Index}/{id?}");
});
}
在程序包管理控制台使用Update-Database命令生成DB,然后再VS中打开Sql server 对象管理器中可以看到创建的数据库及表
启动servers,然后看到以下界面,点击Register注册一个用户然后点击login用注册的用户登陆。
如果能够登陆成功则说明我们的Identity server搭建成功,然后我们用postman单独拿取token:
二、配置.net core web Api使用身份验证系统:
1. 在Startup类的ConfigureServices中添加下列配置,Authority 是我们Identity server启动使用的url。
services.AddAuthentication("Bearer")
.AddJwtBearer("Bearer", options =>
{
options.Authority = "http://localhost:5000";
options.RequireHttpsMetadata = false;
options.Audience = "api1";
});
2. 在Startup类的Configure中添加下列配置。
app.UseAuthentication();
3. Controller 添加属性(特性)[Authorize]
[Route("api/[controller]")]
[ApiController]
[Authorize]
public class ValuesController : ControllerBase
然后我们验证是否可以Identity server验证token.
1. 不添加token,发送请求得到401 bad request 错误
2. 使用token,发送请求,得到200成功的状态码,并返回response。
.net core web API使用Identity Server4 身份验证的更多相关文章
- 用Middleware给ASP.NET Core Web API添加自己的授权验证
Web API,是一个能让前后端分离.解放前后端生产力的好东西.不过大部分公司应该都没能做到完全的前后端分离.API的实现方式有很 多,可以用ASP.NET Core.也可以用ASP.NET Web ...
- [转]用Middleware给ASP.NET Core Web API添加自己的授权验证
本文转自:http://www.cnblogs.com/catcher1994/p/6021046.html Web API,是一个能让前后端分离.解放前后端生产力的好东西.不过大部分公司应该都没能做 ...
- 使用JWT创建安全的ASP.NET Core Web API
在本文中,你将学习如何在ASP.NET Core Web API中使用JWT身份验证.我将在编写代码时逐步简化.我们将构建两个终结点,一个用于客户登录,另一个用于获取客户订单.这些api将连接到在本地 ...
- ASP.NET Core Web API 索引 (更新Identity Server 4 视频教程)
GraphQL 使用ASP.NET Core开发GraphQL服务器 -- 预备知识(上) 使用ASP.NET Core开发GraphQL服务器 -- 预备知识(下) [视频] 使用ASP.NET C ...
- ASP.NET Core Web API中带有刷新令牌的JWT身份验证流程
ASP.NET Core Web API中带有刷新令牌的JWT身份验证流程 翻译自:地址 在今年年初,我整理了有关将JWT身份验证与ASP.NET Core Web API和Angular一起使用的详 ...
- ASP.NET Core Web API 集成测试中使用 Bearer Token
在 ASP.NET Core Web API 集成测试一文中, 我介绍了ASP.NET Core Web API的集成测试. 在那里我使用了测试专用的Startup类, 里面的配置和开发时有一些区别, ...
- C#实现多级子目录Zip压缩解压实例 NET4.6下的UTC时间转换 [译]ASP.NET Core Web API 中使用Oracle数据库和Dapper看这篇就够了 asp.Net Core免费开源分布式异常日志收集框架Exceptionless安装配置以及简单使用图文教程 asp.net core异步进行新增操作并且需要判断某些字段是否重复的三种解决方案 .NET Core开发日志
C#实现多级子目录Zip压缩解压实例 参考 https://blog.csdn.net/lki_suidongdong/article/details/20942977 重点: 实现多级子目录的压缩, ...
- 从ASP.Net Core Web Api模板中移除MVC Razor依赖项
前言 :本篇文章,我将会介绍如何在不包括MVC / Razor功能和包的情况下,添加最少的依赖项到ASP.NET Core Web API项目中. 一.MVC VS WebApi (1)在ASP. ...
- ASP.NET Core 实战:使用 ASP.NET Core Web API 和 Vue.js 搭建前后端分离项目
一.前言 这几年前端的发展速度就像坐上了火箭,各种的框架一个接一个的出现,需要学习的东西越来越多,分工也越来越细,作为一个 .NET Web 程序猿,多了解了解行业的发展,让自己扩展出新的技能树,对自 ...
随机推荐
- mysql 转大写
当前表: mysql> select * from table1; +----------+------------+-----+ | name_new | transactor | pid | ...
- UML的使用
软件工程项目这周要交一个设计文档,其中涉及UML图的画法,根据上课给的ppt做一个记录. 有关于UML的介绍在这里不再赘述,直接开整! UML的基本模型 当然必要的介绍必不可少,这里先介绍UML的基本 ...
- java如何实现批量删除pdf指定的页数
依赖: <dependency> <groupId>org.apache.pdfbox</groupId> <artifactId>pdfbox-app ...
- react ui 参考网站
react.semantic-ui.com react官方中文网址 https://zh-hans.reactjs.org/ es6标准入门 nodejs官网文档 nodejs.org https:/ ...
- VBA 如何检测一个中文字符串是否包含在另一个字符串中
Sub test() aaa = "江苏省南京市建邺区水西门大街34号" If InStr(aaa, Then MsgBox "在里面" Else MsgBox ...
- spark-submit --files 动态加载外部资源文件
在做spark时,有些时候需要加载资源文件,需要在driver或者worker端访问.在client模式下可以使用IO流直接读取,但是在cluster模式下却不能直接读取,需要如下代码: val is ...
- Python3基础 sys.path 查看与修改导包的路径
Python : 3.7.3 OS : Ubuntu 18.04.2 LTS IDE : pycharm-community-2019.1.3 ...
- Python界面常用GUI包
作为Pyhon开发者,你迟早都会碰到图形用户界面(GUI)应用开发任务,这时候我们就需要一些界面库来帮助我们快速搭建界面,python的界面库很多,我认识的并不多,这里只列出几种我认识的 1.tkin ...
- php_MVC实现步骤一
1.Match 基本实现 功能,比赛列表,球队信息 数据表初始化: 比赛列表: 球队一 比分 球队二 比赛时间 韩国 1:2 澳大利亚 15-01-31 17:00 从SQL思考,如何完成上面的查询: ...
- Dev c++编译报错
https://blog.csdn.net/qq_37521610/article/details/87640513