ASP.NET CORE API Swagger+IdentityServer4授权验证
简介
本来不想写这篇博文,但在网上找到的文章博客都没有完整配置信息,所以这里记录下。
不了解IdentityServer4的可以看看我之前写的入门博文
Swagger 官方演示地址
配置IdentityServer4服务端
首先创建一个新的ASP.NET Core项目。

这里选择空白项,新建空白项目

等待创建完成后,右键单击项目中的依赖项选择管理NuGet程序包,搜索IdentityServer4并安装:

等待安装完成后,下载官方提供的UI文件,并拖放到项目中。下载地址:https://github.com/IdentityServer/IdentityServer4.Quickstart.UI
配置IdentityServer4
在项目中新建文件Config.cs文件,源码如下:
using IdentityServer4;
using IdentityServer4.Models;
using IdentityServer4.Test;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks; namespace IdentityServer
{
public static class Config
{
public static IEnumerable<IdentityResource> GetIdentityResources()
{
return new IdentityResource[]
{
new IdentityResources.OpenId(),
new IdentityResources.Profile(),
};
}
/// <summary>
/// API信息
/// </summary>
/// <returns></returns>
public static IEnumerable<ApiResource> GetApis()
{
return new[]
{
new ApiResource("demo_api", "Demo API with Swagger")
};
}
/// <summary>
/// 客服端信息
/// </summary>
/// <returns></returns>
public static IEnumerable<Client> GetClients()
{
return new[]
{
new Client
{
ClientId = "demo_api_swagger",//客服端名称
ClientName = "Swagger UI for demo_api",//描述
AllowedGrantTypes = GrantTypes.Implicit,//指定允许的授权类型(AuthorizationCode,Implicit,Hybrid,ResourceOwner,ClientCredentials的合法组合)。
AllowAccessTokensViaBrowser = true,//是否通过浏览器为此客户端传输访问令牌
RedirectUris =
{
"http://localhost:5001/swagger/oauth2-redirect.html"
},
AllowedScopes = { "demo_api" }//指定客户端请求的api作用域。 如果为空,则客户端无法访问
}
};
}
}
}
打开Startup.cs文件配置,修改如下:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using IdentityServer4.Quickstart.UI;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.DependencyInjection; namespace IdentityServer
{
public class Startup
{
// This method gets called by the runtime. Use this method to add services to the container.
// For more information on how to configure your application, visit https://go.microsoft.com/fwlink/?LinkID=398940
public void ConfigureServices(IServiceCollection services)
{
services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1);
//配置身份服务器与内存中的存储,密钥,客户端和资源
services.AddIdentityServer()
.AddDeveloperSigningCredential()
.AddInMemoryApiResources(Config.GetApis())//添加api资源
.AddInMemoryClients(Config.GetClients())//添加客户端
.AddInMemoryIdentityResources(Config.GetIdentityResources())//添加对OpenID Connect的支持
.AddTestUsers(TestUsers.Users); //添加测试用户
} // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
} //IdentityServe
app.UseIdentityServer();
//添加静态资源访问
app.UseStaticFiles();
//
app.UseMvcWithDefaultRoute();
}
}
}
修改启动端口为5000,启动访问:http://localhost:5000/,效果如下:

API配置
新建ASP.NET CORE API项目,使用NuGet添加包:IdentityServer4.AccessTokenValidation、Swashbuckle.AspNetCore

在API中添加 AuthorizeCheckOperationFilter用于管理IdentityServer4认证处理,代码如下:
using Microsoft.AspNetCore.Authorization;
using Swashbuckle.AspNetCore.Swagger;
using Swashbuckle.AspNetCore.SwaggerGen;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks; namespace TPL.API
{
/// <summary>
/// IdentityServer4认证过滤器
/// </summary>
public class AuthorizeCheckOperationFilter : IOperationFilter
{
public void Apply(Operation operation, OperationFilterContext context)
{
//获取是否添加登录特性
var authAttributes = context.MethodInfo.DeclaringType.GetCustomAttributes(true)
.Union(context.MethodInfo.GetCustomAttributes(true))
.OfType<AuthorizeAttribute>().Any(); if (authAttributes)
{
operation.Responses.Add("", new Response { Description = "暂无访问权限" });
operation.Responses.Add("", new Response { Description = "禁止访问" });
//给api添加锁的标注
operation.Security = new List<IDictionary<string, IEnumerable<string>>>
{
new Dictionary<string, IEnumerable<string>> {{"oauth2", new[] {"demo_api"}}}
};
}
}
}
}
修改API的Startup文件,修改如下:
using System;
using System.Collections.Generic;
using IdentityServer4.AccessTokenValidation;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Swashbuckle.AspNetCore.Swagger; namespace TPL.API
{
public class Startup
{
public Startup(IConfiguration configuration)
{
Configuration = configuration;
} public IConfiguration Configuration { get; } // This method gets called by the runtime. Use this method to add services to the container.
public void ConfigureServices(IServiceCollection services)
{
services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1);
//用户校验
services.AddAuthentication(IdentityServerAuthenticationDefaults.AuthenticationScheme)
.AddIdentityServerAuthentication(options =>
{
options.Authority = "http://localhost:5000"; // IdentityServer服务器地址
options.ApiName = "demo_api"; // 用于针对进行身份验证的API资源的名称
options.RequireHttpsMetadata = false; // 指定是否为HTTPS
});
//添加Swagger.
services.AddSwaggerGen(options =>
{
options.SwaggerDoc("v1", new Info { Title = "Protected API", Version = "v1" });
//向生成的Swagger添加一个或多个“securityDefinitions”,用于API的登录校验
options.AddSecurityDefinition("oauth2", new OAuth2Scheme
{
Flow = "implicit", // 只需通过浏览器获取令牌(适用于swagger)
AuthorizationUrl = "http://localhost:5000/connect/authorize",//获取登录授权接口
Scopes = new Dictionary<string, string> {
{ "demo_api", "Demo API - full access" }//指定客户端请求的api作用域。 如果为空,则客户端无法访问
}
}); options.OperationFilter<AuthorizeCheckOperationFilter>(); // 添加IdentityServer4认证过滤
});
} // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
app.UseAuthentication(); // Swagger JSON Doc
app.UseSwagger(); // Swagger UI
app.UseSwaggerUI(options =>
{
options.SwaggerEndpoint("/swagger/v1/swagger.json", "My API V1");
options.OAuthClientId("demo_api_swagger");//客服端名称
options.OAuthAppName("Demo API - Swagger-演示"); // 描述
});
app.UseMvc();
}
}
}
修改Properties文件夹下的launchSettings启动端口为5001,这里端口必须跟IdentityServer4中的Config配置的客服端资源中保持一致。
{
"$schema": "http://json.schemastore.org/launchsettings.json",
"iisSettings": {
"windowsAuthentication": false,
"anonymousAuthentication": true,
"iisExpress": {
"applicationUrl": "http://localhost:5001",
"sslPort":
}
},
"profiles": {
"IIS Express": {
"commandName": "IISExpress",
"launchBrowser": true,
"launchUrl": "swagger",
"environmentVariables": {
"ASPNETCORE_ENVIRONMENT": "Development"
}
},
"TPL.API": {
"commandName": "Project",
"launchBrowser": true,
"launchUrl": "swagger",
"applicationUrl": "http://localhost:5001",
"environmentVariables": {
"ASPNETCORE_ENVIRONMENT": "Development"
}
}
}
}
访问呈现效果如下,从中效果图中可以看出添加登录按钮,API控制器中如果添加Authorize特性,对应接口会有一把锁的标志:

如果未授权访问接口返回401,未授权提示:

点击Authorize按钮会跳转到IdentityServer4登录页面,登录授权成功后会自动获取登录后服务器返回Token,再次访问接口即可正常访问,授权前后效果如下:


到此演示项目完毕。如果需求配合自己的数据库使用请看我前面写过的博文 自定义登录即可。
ASP.NET CORE API Swagger+IdentityServer4授权验证的更多相关文章
- C#中缓存的使用 ajax请求基于restFul的WebApi(post、get、delete、put) 让 .NET 更方便的导入导出 Excel .net core api +swagger(一个简单的入门demo 使用codefirst+mysql) C# 位运算详解 c# 交错数组 c# 数组协变 C# 添加Excel表单控件(Form Controls) C#串口通信程序
C#中缓存的使用 缓存的概念及优缺点在这里就不多做介绍,主要介绍一下使用的方法. 1.在ASP.NET中页面缓存的使用方法简单,只需要在aspx页的顶部加上一句声明即可: <%@ Outp ...
- asp.net core系列 49 Identity 授权(上)
一.概述 授权是指用户能够访问资源的权限,如页面数据的查看.编辑.新增.删除.导出.下载等权限.ASP.NET Core 授权提供了多种且灵活的方式,包括:Razor pages授权约定.简单授权.R ...
- 详解ASP.NET Core API 的Get和Post请求使用方式
上一篇文章帮助大家解决问题不彻底导致博友使用的时候还是遇到一些问题,欢迎一起讨论.所以下面重点详细讲解我们常用的Get和Post请求( 以.net core2.2的Http[Verb]为方向 ,推荐该 ...
- ASP.NET Core API 接收参数去掉烦人的 [FromBody]
在测试ASP.NET Core API 项目的时候,发现后台接口参数为类型对象,对于PostMan和Ajax的Post方法传Json数据都获取不到相应的值,后来在类型参数前面加了一个[FromBody ...
- ASP.NET Core API ——Dapper的使用
ASP.NET Core API ——Dapper的使用 简介:Dapper是一个ORM框架,负责数据库和程序语言之间的映射. 使用步骤: l 创建一个IDBConnection的接口对象 l 编 ...
- ASP.NET Core API总结(一)
ASP.NET Core API 问题:当应用收到一个http请求之后,API应用程序是怎么一步步执行的. 注册服务——构造容器——使用服务——创建对象 1. 创建一个新的API之后, ...
- asp.net core 3.1多种身份验证方案,cookie和jwt混合认证授权
开发了一个公司内部系统,使用asp.net core 3.1.在开发用户认证授权使用的是简单的cookie认证方式,然后开发好了要写几个接口给其它系统调用数据.并且只是几个简单的接口不准备再重新部署一 ...
- Asp.Net Core Api 使用Swagger管理文档教程的安装与使用
这周因为公司的需求需要我做一个Api的程序,这周的三天时间我一直在Core Api和 framework Api之间做纠结.不知道要使用哪一个去做项目,想着想着就决定了.既然两个我都没用过那个何不来使 ...
- asp.net core系列 53 IdentityServer4 (IS4)介绍
一.概述 在物理层之间相互通信必须保护资源,需要实现身份验证和授权,通常针对同一个用户存储.对于资源安全设计包括二个部分,一个是认证,一个是API访问. 1 认证 认证是指:应用程序需要知道当前用户的 ...
随机推荐
- 【动态规划】POJ-3176
一.题目 Description The cows don't use actual bowling balls when they go bowling. They each take a numb ...
- js如何判断一个值是不是Array类型
本来判断一个对象类型用typeof是最好的,不过对于Array类型是不适用的可以使用 instanceof操作符var arrayStr=new Array("1","2 ...
- [2017BUAA软工]第2次个人作业
软工第2次个人作业--代码复审 一.代码复审Check List 1.概要部分 代码能符合需求和规格说明么? 能正确处理题目要求,代码能符合需求和规格. 代码设计是否有周全的考虑? 能正确生成和解出数 ...
- 关于“scrum站立会议”
每日站立会议是SCRUM方法中的一条关键实践,整个会议可能会比较混乱粗略,但推进进度的目标却非常清晰明确,并促使团队齐心协力朝共同目标迈进. 站立会议的功能很简单,作为一个以简短为特点的项目会议,所有 ...
- HDU 2061 Treasure the new start, freshmen!
http://acm.hdu.edu.cn/showproblem.php?pid=2061 Problem Description background:A new semester comes , ...
- java 自定义异常的回顾
一.异常的分类: 1.编译时异常:编译时被检测的异常 (throw后,方法有能力处理就try-catch处理,没能力处理就必须throws).编译不通过,检查语法(其实就是throw和throws的配 ...
- 聚合函数count里面加条件
聚合函数中如果想汇总某一类数据,可以在括号中增加条件: sum(case when 字段>0 then 1 else 0 end) as 字段 *注意:count(case when 字段> ...
- TCP/IP协议三次握手和四次挥手大白话解说
前言 昨天晚上被一位师傅问到了TCP/IP的工作机制,心里很清楚三次握手,然而对于四次挥手却忘了,这是大学习里学过的,奋而翻阅书籍和网络对之前所学的做一个温顾,算是夯实自我吧. TCP(Transmi ...
- how to disabled iframe page open new window / new tab
how to disabled iframe page open new window / new tab 禁用 iframe 中的页面打开新页面 <!DOCTYPE html> < ...
- 深入理解JAVA虚拟机阅读笔记4——虚拟机类加载机制
虚拟机把描述类的Class文件加载到内存,并对数据进行校验.转换解析和初始化,最终形成可以被虚拟机直接使用的Java类型,这就是虚拟机的类加载机制. 在Java语言中,类型的加载.连接和初始化过程都是 ...