Swagger与OAuth 手动搭建WebApi 操作笔记
1、创建一个空的Web应用程序
2、通过nuget 安装以下插件清单,有部分会在安装其他插件时候自动安装:




3、安装完Swagger 会生成一个目录App_Start,在这个目录中增加文件ApiConfig.cs 配置路由相关信息
public static void Register(HttpConfiguration config)
{
var appsettings = ConfigurationManager.AppSettings; //跨域配置
var corsAttr = new EnableCorsAttribute("*", "*", "*");
config.EnableCors(corsAttr);
config.MapHttpAttributeRoutes();
config.Routes.MapHttpRoute(
name: "Default",
routeTemplate: "api/{controller}/{id}",
defaults: new { id = RouteParameter.Optional }
);
}
添加文件 CustomApiExplorer.cs 重写ApiExplorer中的ShouldExploreController方法,对路由进行重定向
/// <summary>
/// 构造方法
/// </summary>
/// <param name="configuration"></param>
public CustomApiExplorer(HttpConfiguration configuration) : base(configuration)
{
}
//public override bool ShouldExploreAction(string actionVariableValue, HttpActionDescriptor actionDescriptor, IHttpRoute route)
//{
// return base.ShouldExploreAction(actionVariableValue, actionDescriptor, route);
//}
public override bool ShouldExploreController(string controllerVariableValue, HttpControllerDescriptor controllerDescriptor, IHttpRoute route)
{
return base.ShouldExploreController(controllerVariableValue, controllerDescriptor, route);
}
修改 SwaggerConfig中代码; WebApi.xml 中记录Swagger接口的描述信息
public static void Register()
{
var thisAssembly = typeof(SwaggerConfig).Assembly; GlobalConfiguration.Configuration
.EnableSwagger(c =>
{
c.SingleApiVersion("v1", "WebApi"); c.IncludeXmlComments(GetXmlCommentsPath()); })
.EnableSwaggerUi(c =>
{
});
}
private static string GetXmlCommentsPath()
{
return System.String.Format(@"{0}\bin\WebApi.xml", System.AppDomain.CurrentDomain.BaseDirectory);
}
修改工程配置信息

使用 OWIN 方式实现 创建 Startup 文件:

创建完成后修改代码:
public void Configuration(IAppBuilder app)
{ HttpConfiguration config = new HttpConfiguration();
ApiConfig.Register(config);
app.UseCors(CorsOptions.AllowAll);
app.UseWebApi(config); //初始化
GlobalConfiguration.Configure(ApiConfig.Register);
//重订路由
GlobalConfiguration.Configuration.Services.Replace(typeof(IApiExplorer), new CustomApiExplorer(GlobalConfiguration.Configuration));
}
使用Global.asax实现;添加全局文件Global.asax,在Application_Start方法中对路由进行重订
protected void Application_Start(object sender, EventArgs e)
{
//初始化
GlobalConfiguration.Configure(ApiConfig.Register);
//重订路由
GlobalConfiguration.Configuration.Services.Replace(typeof(IApiExplorer), new CustomApiExplorer(GlobalConfiguration.Configuration));
}
到这里配置相关已经处理完成,创建Controller文件夹配置接口,在文件夹中创建文件DemoController.cs
[RoutePrefix("api/DemoTest")]
public class DemoController : ApiController
{
[HttpGet]
[Route("Hello")]
public string GetList()
{
return "Hello";
}
}
到这里Swagger配置以及全部完成,直接运行,在浏览器中输入http://localhost:58360/swagger 即可查看结果

开始配置验证功能,这里我使用的是OAuth ;
首先在Nuget中安装 Microsoft.Owin.Security.OAuth
安装完成后创建 SimpleAuthorizationServerProvider 文件,在这个文件中重写Oauth方法, 在此文件中做用户验证等操作
public class SimpleAuthorizationServerProvider : OAuthAuthorizationServerProvider
{ public override Task ValidateClientAuthentication(OAuthValidateClientAuthenticationContext context)
{
context.Validated();
return Task.FromResult<object>(null);
} public override async Task GrantResourceOwnerCredentials(OAuthGrantResourceOwnerCredentialsContext context)
{
context.OwinContext.Response.Headers.Add("Access-Control-Allow-Origin", new[] { "*" });
var isLogin = false;// UsersBase.Login(context.UserName, context.Password);
if (!isLogin)
{
context.SetError("Error", "账号密码验证失败");
return;
}
var identity = new ClaimsIdentity(context.Options.AuthenticationType);
identity.AddClaim(new Claim("sub", context.UserName));
identity.AddClaim(new Claim("role", "user"));
context.Validated(identity); }
}
创建 SimpleRefreshTokenProvider 文件 重写OauthToken生成规则
public class SimpleRefreshTokenProvider : AuthenticationTokenProvider
{
private static ConcurrentDictionary<string, string> _refreshTokens = new ConcurrentDictionary<string, string>(); /// <summary>
/// 生成 refresh_token
/// </summary>
public override void Create(AuthenticationTokenCreateContext context)
{
context.Ticket.Properties.IssuedUtc = DateTime.UtcNow;
context.Ticket.Properties.ExpiresUtc = DateTime.UtcNow.AddDays(); context.SetToken(Guid.NewGuid().ToString("n"));
_refreshTokens[context.Token] = context.SerializeTicket();
} /// <summary>
/// 由 refresh_token 解析成 access_token
/// </summary>
public override void Receive(AuthenticationTokenReceiveContext context)
{
string value;
if (_refreshTokens.TryRemove(context.Token, out value))
{
context.DeserializeTicket(value);
}
}
}
修改 Startup1文件中代码
public void Configuration(IAppBuilder app)
{ ConfigAuth(app);
HttpConfiguration config = new HttpConfiguration();
ApiConfig.Register(config);
app.UseCors(CorsOptions.AllowAll);
app.UseWebApi(config); //初始化
GlobalConfiguration.Configure(ApiConfig.Register);
//重订路由
GlobalConfiguration.Configuration.Services.Replace(typeof(IApiExplorer), new CustomApiExplorer(GlobalConfiguration.Configuration));
}
public void ConfigAuth(IAppBuilder app)
{
OAuthAuthorizationServerOptions option = new OAuthAuthorizationServerOptions()
{
AllowInsecureHttp = true,
TokenEndpointPath = new PathString("/token"), //获取 access_token 授权服务请求地址
AccessTokenExpireTimeSpan = TimeSpan.FromDays(), //access_token 过期时间
Provider = new SimpleAuthorizationServerProvider(), //access_token 相关授权服务
RefreshTokenProvider = new SimpleRefreshTokenProvider() //refresh_token 授权服务
};
app.UseOAuthAuthorizationServer(option);
app.UseOAuthBearerAuthentication(new OAuthBearerAuthenticationOptions());
}
接口启用验证;[Authorize] 代表此模块需要身份验证, [AllowAnonymous] 代表此方法不需要验证
[RoutePrefix("api/DemoTest")]
[Authorize]
public class DemoController : ApiController
{
[HttpGet]
[Route("Hello")]
[AllowAnonymous]
public string GetList()
{
return "Hello";
}
[HttpPost]
[Route("Hello2")]
public string GetToken(string userName,string userPwd)
{
//new SimpleRefreshTokenProvider().Create(new AuthenticationTokenCreateContext(Owin.IAppBuilder) context);
return "Hello";
}
}
Oauth已经配置完成,现在直接运行项目,由于是Post请求我这边使用Postman进行验证接口

Swagger与OAuth 手动搭建WebApi 操作笔记的更多相关文章
- WebAPI调用笔记 ASP.NET CORE 学习之自定义异常处理 MySQL数据库查询优化建议 .NET操作XML文件之泛型集合的序列化与反序列化 Asp.Net Core 轻松学-多线程之Task快速上手 Asp.Net Core 轻松学-多线程之Task(补充)
WebAPI调用笔记 前言 即时通信项目中初次调用OA接口遇到了一些问题,因为本人从业后几乎一直做CS端项目,一个简单的WebAPI调用居然浪费了不少时间,特此记录. 接口描述 首先说明一下,基于 ...
- ASP.NET WebAPI 集成 Swagger 启用 OAuth 2.0 配置问题
在 ASP.NET WebAPI 集成 Swagger 后,由于接口使用了 IdentityServer 做的认证,调试起来很不方便:看了下 Swashbuckle 的文档 ,是支持 OAuth2.0 ...
- 从零开始搭建WebAPI Core_SqlSugar管理系统 (持续更新中......)
从零开始搭建WebAPI Core_SqlSugar管理系统 前言 本系列皆在从零开始逐步搭建,后台管理系统服务端部分,后续还会推出前端部分. 这次的目的是搭出一个功能完善的 本次系列技术栈以下几个部 ...
- 手动从0搭建ABP框架-ABP官方完整解决方案和手动搭建简化解决方案实践
本文主要讲解了如何把ABP官方的在线生成解决方案运行起来,并说明了解决方案中项目间的依赖关系.然后手动实践了如何从0搭建了一个简化的解决方案.ABP官方的在线生成解决方案源码下载参考[3],手动搭 ...
- php 手动搭建环境
php手动搭建环境有好多种组合,版本号不一致,会导致搭建失败. 我搭建的组合是: php5.6+MySQL5.6+Apache2.4的组合. 一.PHP语言包下载 首先从官网上下载php5.6 htt ...
- 混合式app ionic2.x 手动搭建开发环境教程分享(nodejs,jdk,ant,androidsdk)
1.ionic简介 为什么选用ionic: 彻底开源且免费 性能优异 基于红的发紫的AngularJs 漂亮的UI 强大的命令行(基于更热门的nodejs) 开发团队非常活跃 ngCordova,将主 ...
- PHP手动搭建环境
php手动搭建环境有好多种组合,版本号不一致,会导致搭建失败. 我搭建的组合是: php5.6+MySQL5.6+Apache2.4的组合. 一.PHP语言包下载 首先从官网上下载php5.6 htt ...
- Centos7系统下修改主机名操作笔记
习惯了在Centos6系统下修改主机名的操作,但是Centos7下修改主机名的操作却大不相同!操作笔记如下: 在CentOS中,有三种定义的主机名:静态的(static),瞬态的(transient) ...
- SSM框架手动搭建
SSM框架手动搭建 创建web项目 IDEA创建Maven项目 [File]-->[new]-->[project..] 将项目变为web项目 [File]-->[Project S ...
随机推荐
- [USACO09JAN]Total Flow【网络流】
Farmer John always wants his cows to have enough water and thus has made a map of the N (1 <= N & ...
- nginx配置之后接口状态200,但是无返回数据问题小记
nginx配置可能有问题.导致nginx不能解析PHP文件,检测nginx里对于php的配置信息. location ~ \.php$ { fastcgi_pass 127.0.0.1:9000; f ...
- 在IIS中配置申请的SSL证书
第一步,右键服务器证书=>打开功能 第二步,右侧选择导入,将申请到的证书按窗体内容导入即可 第三步,右键需要加载证书的网站,选择编辑绑定=>类型选择https=>选择刚才导入的数字证 ...
- Github中进行fork后,原仓库更新了如何与原仓库同步
我们经常在Github中Fork别人优秀的项目(在自己的GitHub下面生成一个repository),如果原仓库作者或组织更新仓库,此时你Fork的项目并不会更新,如果我们想要更新操作,该如何操作? ...
- Java后端知识体系及路线【最新秘籍】
第一层(基本语法) 第一层心法,主要都是基本语法,程序设计入门,悟性高者十天半月可成,差一点的 3 到 6 个月也说不准.如果有其他开发语言的功底相助,并且有张无忌的悟性与运气,相信第一层只在片刻 ...
- android TextView 支持长按自由复制
因为EditText支持系统的长按自由复制,所以只需要把EditText通过配置达到TextView效果就行了 <EditText android:id="@+id/subject_i ...
- gflag的简单入门demo
gflags 一. 下载与安装 这里直接使用包管理器安装: sudo apt install libgflags-dev 二. gflags的简单使用 1. 定义需要的类型 格式: DEFINE_类型 ...
- C语言运算符的优先级与结合性
结合性:左结合是从左到右依次执行,右结合是从右到左依次执行. 优先级 运算符 名称或作用 运算类型 结合方向 特点 1 () [] -> . 小括号运算符 下标运算符 指向结构成员运算符 结构成 ...
- Deepin安装常用软件
Deepin安装常用软件 安装git sudo apt-get install git sudo是Debian系列以管理员运行的前缀 卸载软件 sudo apt-get remove package_ ...
- java注册界面及mysql连接
题目要求 完成注册界面及添加功能 1登录账号:要求由6到12位字母.数字.下划线组成,只有字母可以开头:(1分) 2登录密码:要求显示“• ”或“*”表示输入位数,密码要求八位以上字母.数字组成.(1 ...