一、新建一个.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 身份验证的更多相关文章

  1. 用Middleware给ASP.NET Core Web API添加自己的授权验证

    Web API,是一个能让前后端分离.解放前后端生产力的好东西.不过大部分公司应该都没能做到完全的前后端分离.API的实现方式有很 多,可以用ASP.NET Core.也可以用ASP.NET Web ...

  2. [转]用Middleware给ASP.NET Core Web API添加自己的授权验证

    本文转自:http://www.cnblogs.com/catcher1994/p/6021046.html Web API,是一个能让前后端分离.解放前后端生产力的好东西.不过大部分公司应该都没能做 ...

  3. 使用JWT创建安全的ASP.NET Core Web API

    在本文中,你将学习如何在ASP.NET Core Web API中使用JWT身份验证.我将在编写代码时逐步简化.我们将构建两个终结点,一个用于客户登录,另一个用于获取客户订单.这些api将连接到在本地 ...

  4. ASP.NET Core Web API 索引 (更新Identity Server 4 视频教程)

    GraphQL 使用ASP.NET Core开发GraphQL服务器 -- 预备知识(上) 使用ASP.NET Core开发GraphQL服务器 -- 预备知识(下) [视频] 使用ASP.NET C ...

  5. ASP.NET Core Web API中带有刷新令牌的JWT身份验证流程

    ASP.NET Core Web API中带有刷新令牌的JWT身份验证流程 翻译自:地址 在今年年初,我整理了有关将JWT身份验证与ASP.NET Core Web API和Angular一起使用的详 ...

  6. ASP.NET Core Web API 集成测试中使用 Bearer Token

    在 ASP.NET Core Web API 集成测试一文中, 我介绍了ASP.NET Core Web API的集成测试. 在那里我使用了测试专用的Startup类, 里面的配置和开发时有一些区别, ...

  7. 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 重点: 实现多级子目录的压缩, ...

  8. 从ASP.Net Core Web Api模板中移除MVC Razor依赖项

    前言 :本篇文章,我将会介绍如何在不包括MVC / Razor功能和包的情况下,添加最少的依赖项到ASP.NET Core Web API项目中. 一.MVC   VS WebApi (1)在ASP. ...

  9. ASP.NET Core 实战:使用 ASP.NET Core Web API 和 Vue.js 搭建前后端分离项目

    一.前言 这几年前端的发展速度就像坐上了火箭,各种的框架一个接一个的出现,需要学习的东西越来越多,分工也越来越细,作为一个 .NET Web 程序猿,多了解了解行业的发展,让自己扩展出新的技能树,对自 ...

随机推荐

  1. assert(0)的作用

    捕捉逻辑错误.可以在程序逻辑必须为真的条件上设置断言.除非发生逻辑错误,否则断言对程序无任何影响.即预防性的错误检查,在认为不可能的执行到的情况下加一句ASSERT(0),如果运行到此,代码逻辑或条件 ...

  2. 剑指offer:两个链表的第一个公共结点

    题目描述: 输入两个链表,找出它们的第一个公共结点. 解题思路: 这道题一开始的题意不太理解,这里的公共结点,实际上指结点指相同,在题目不存在结点值相同的不同结点. 1. 最直接的思路是对链表一的每个 ...

  3. java查看线程的堆栈信息

    通过使用jps 命令获取需要监控的进程的pid,然后使用jstack pid 命令查看线程的堆栈信息. 通过jstack 命令可以获取当前进程的所有线程信息. 每个线程堆中信息中,都可以查看到线程ID ...

  4. postgres开启慢查询日志

    1.全局设置修改配置postgres.conf: log_min_duration_statement=5000 然后加载配置: postgres=# select pg_reload_conf() ...

  5. centos 宝塔面版 运行 thinkjs

    centos 宝塔面版 运行 thinkjs 几点要注意的地方: 1.  https ssl 如图 2. thinkjs 运行子目录在/www如图配置: 3. 代理配置(展示查看配置) server ...

  6. WebGL学习笔记(五):变换库

    在WebGL开始绘制之前,我们需要通过自己对3D空间进行矩阵和向量的运算,使用网上已经成熟的转换库,可以避免自己去实现这些复杂的数学运算. 我们这里选择的是gl-matrix库,下载地址:https: ...

  7. springboot 整合OSS

    OSS 阿里云对象存储服务(Object Storage Service,简称 OSS),是阿里云提供的海量.安全.低成本.高可靠的云存储服务.OSS可用于图片.音视频.日志等海量文件的存储.各种终端 ...

  8. git用法汇总

    使用了一年多的git命令了,昨晚竟然又出现了问题.虽然解决了,不过还是被罚了... 总结下自己常用的git命令和遇到的一些坑. 1)常用的命令 1. 从git远程分支clone代码: git clon ...

  9. [LeetCode] 549. Binary Tree Longest Consecutive Sequence II 二叉树最长连续序列之 II

    Given a binary tree, you need to find the length of Longest Consecutive Path in Binary Tree. Especia ...

  10. kubernetes之secret

    Secret解决了密码.token.密钥等敏感数据的配置问题,而不需要把这些敏感数据暴露到镜像或者Pod Spec中.Secret可以以Volume或者环境变量的方式使用. Secret类型: Opa ...