一、新建一个.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. Git删除某个文件夹或整个仓库

    删除仓库: 进入仓库,选择settting: 拉到最下面,有个Danger Zone,里面有删除仓库选项: 输入仓库名称,即可删除: 删除某个文件:删除文件和文件夹只能用命令行删除. 如果直接git ...

  2. 京津冀大学生竞赛:babyphp

    京津冀大学生竞赛:babyphp 比赛的时候没做出来,回来以后一会就做出来了,难受...还是基本功不扎实,都不记得__invoke怎么触发的了 放上源码 <?php error_reportin ...

  3. JSP的工作原理

    jsp的本质就是一个servlet,jsp在第一次被访问时会被Web容器翻译成servlet index.jsp -> index_jsp.java -> 编译成index_jsp.cla ...

  4. shell | crontab 定时任务

    crontab工具 linux下自带的定时任务执行器 常用命令:crontab -l //显示用户的crontab文件的内容crontab -e //编辑用户的crontab文件的内容crontab ...

  5. kubectl -n ingress-nginx exec nginx-ingress-controller-78bd49949c-t22bl -- cat /etc/nginx/nginx.conf

    kubectl -n ingress-nginx exec nginx-ingress-controller-78bd49949c-t22bl -- cat /etc/nginx/nginx.conf

  6. Spring cloud微服务安全实战-7-6自定义metrics监控指标(1)

    自己写代码来定义一个metrics,然后让prmetheus收走,在grafana里面定义一个panel并展示出来. prometheus的四种metrics指标.虽然所有的metrics都是数字,但 ...

  7. [LeetCode] 190. Reverse Bits 翻转二进制位

    Reverse bits of a given 32 bits unsigned integer. For example, given input 43261596 (represented in ...

  8. 【VS开发】VS2015没修改源文件也导致重新编译的解决办法

    在使用VS2010编译C++程序的时候,每次修改工程中的某一个文件,点击"生成-仅用于项目-仅生成**"时,往往都是整个工程都需要重新编译一遍.由于这个工程代码量太大,每次编译完成 ...

  9. DotNetty是微软的Azure团队,使用C#实现的Netty的版本发布

    DotNetty是微软的Azure团队,使用C#实现的Netty的版本发布 Netty(DotNetty)原理解析 一.背景介绍 DotNetty是微软的Azure团队,使用C#实现的Netty的版本 ...

  10. 问题一:使用AndroidDriver而非原来的AppiumDriver的原因

    AppiumDriver升级到2.0.0版本引发的问题--Cannot instantiate the type AppiumDriver 1. 问题描述和起因在使用Appium1.7.0及其以下版本 ...