.NET 请求认证之access-token(oauth2.0与owin的结合)
公司对外开放的接口,大多需要请求认证,如微信,阿里等。最近我刚好在搭建webapi框架。记录一下自己的理解。
一:请求认证的目的
之所以要对我们的接口进行请求认证,就是为了安全考虑的。以前都是在用别人给我的规则去生成token,现在也轮到自己开发了。嘿嘿
二:开发思路
1:请求接口之前,用户必须先去请求获得我们的access-token。每次请求必须得带上access-token来请求我的接口。否则我们会拒绝外部请求。
2:access-token有时间的限制,过期的请求我们依然会拒绝。
3:对不同的外部者,应有不同的clientID。以便分配不同的权限。以后不合作了,我们可以取消他们的认证,并不会影响其他的客户。类似于微信的 Appid,Appsecret
三:创建Access-Token
在api项目里token验证发生在进入接口之前,需要有一个启动文件来执行token的判断。在API项目下创建Startup.cs类。
我们需要在Nuget引用以下DLL:
- Microsoft.Owin.Security.OAuth
- Microsoft.Owin.Security
- Microsoft.Owin
- Microsoft.Owin.Host.SystemWeb
- OWIN
- Microsoft ASP.Net Web API 2.2 OWIN
- Microsoft ASP.Net Identity OWIN
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web.Http;
using Bn.Common;
using Microsoft.Owin;
using Microsoft.Owin.Cors;
using Microsoft.Owin.Security;
using Microsoft.Owin.Security.OAuth;
using Owin; [assembly: OwinStartup(typeof(BnWebApi.Startup))] namespace BnWebApi
{
/// <summary>
/// wuchen19-4-15
/// </summary>
public partial class Startup
{
//public void Configuration(IAppBuilder app)
//{
// ConfigureAuth(app);
//}
public void Configuration(IAppBuilder app)
{
HttpConfiguration config = new HttpConfiguration();
WebApiConfig.Register(config);
ConfigureOAuth(app);
app.UseCors(CorsOptions.AllowAll);
app.UseWebApi(config);
} public void ConfigureOAuth(IAppBuilder app)
{
var OAuthServerOptions = new OAuthAuthorizationServerOptions()
{
AllowInsecureHttp = true, //允许客户端使用Http协议请求
TokenEndpointPath = new PathString("/token"), //请求地址
//AccessTokenExpireTimeSpan = TimeSpan.FromDays(1), //token过期时间
AccessTokenExpireTimeSpan = TimeSpan.FromHours(),
Provider = new SimpleAuthorizationServerProvider(),//提供认证策略
RefreshTokenProvider = new SimpleRefreshTokenProvider() //refresh_token 授权服务
};
app.UseOAuthAuthorizationServer(OAuthServerOptions);
app.UseOAuthBearerAuthentication(new OAuthBearerAuthenticationOptions());
} }
}
这个SimpleRefreshTokenProvider()方法就是我们验证Client信息和生成Token的地方
using System;
using System.Collections.Generic;
using System.Linq;
using System.Security.Claims;
using System.Text;
using System.Threading.Tasks;
using Microsoft.Owin.Security;
using Microsoft.Owin.Security.OAuth;
using System.Configuration; namespace Bn.Common
{
/// <summary>
/// Token验证 wuchen 5-17
/// </summary>
public class SimpleAuthorizationServerProvider : OAuthAuthorizationServerProvider
{ #region AccessToken生成机制 密码模式
////Oauth AccessToken grant_type=password //public override async Task ValidateClientAuthentication(OAuthValidateClientAuthenticationContext context)
//{
// await Task.Factory.StartNew(() => context.Validated());
//}
//public override async Task GrantResourceOwnerCredentials(OAuthGrantResourceOwnerCredentialsContext context)
//{
// await Task.Factory.StartNew(() => context.OwinContext.Response.Headers.Add("Access-Control-Allow-Origin", new[] { "*" }));
// var identity = new ClaimsIdentity(context.Options.AuthenticationType);
// var bnauth = ConfigurationManager.AppSettings["Oauth"]; //BnUser-123456
// var bnstr = bnauth.Split('-');
// var bnuser = bnstr[0];
// var bnpassword = bnstr[1];
// if (context.UserName != bnuser || context.Password != bnpassword)
// {
// context.SetError("invalid_client", "账号密码认证失败");
// return;
// }
// identity.AddClaim(new Claim("sub", context.UserName));
// identity.AddClaim(new Claim("role", "user"));
// context.Validated(identity);
//}
#endregion #region AccessToken生成机制 客户端模式
// grant_type= client_credentials
public override async Task ValidateClientAuthentication(OAuthValidateClientAuthenticationContext context)
{
string clientId;
string clientSecret;
context.TryGetFormCredentials(out clientId, out clientSecret);
//验证
//var bnauth = ConfigurationManager.AppSettings["Oauth"]; //BnUser-123456
//var bnstr = bnauth.Split('-');
//var bnuser = bnstr[0];
//var bnpassword = bnstr[1];
//if (clientId != bnuser || clientSecret != bnpassword)
//{
// context.SetError("invalid_client", "账号密码认证失败");
// return;
//} var gkey = ConfigurationManager.AppSettings[clientId]; //BnUser-123456
if (clientSecret != gkey)
{
context.SetError("invalid_client", "账号密码认证失败");
return;
} context.OwinContext.Set("as:client_id", clientId);
await Task.Factory.StartNew(() => context.Validated(clientId));
//context.Validated(clientId);
}
/// <summary>
/// 客户端授权[生成access token]
/// </summary>
/// <param name="context"></param>
/// <returns></returns>
public override Task GrantClientCredentials(OAuthGrantClientCredentialsContext context)
{
var oAuthIdentity = new ClaimsIdentity(context.Options.AuthenticationType);
oAuthIdentity.AddClaim(new Claim(ClaimTypes.Name, context.OwinContext.Get<string>("as:client_id")));
var ticket = new AuthenticationTicket(oAuthIdentity, new AuthenticationProperties { AllowRefresh = true });
context.Validated(ticket);
return base.GrantClientCredentials(context);
}
#endregion }
}
两种模式都是可以用的。。密码模式和客户端模式。GrantClientCredentials方法为我们生成Token的方法。。有了这些我们就可以生成token啦。
Oauth支持的5类 grant_type 及说明(
authorization_code — 授权码模式(即先登录获取code,再获取token)
password — 密码模式(将用户名,密码传过去,直接获取token)
client_credentials — 客户端模式(无用户,用户向客户端注册,然后客户端以自己的名义向’服务端’获取资源)
implicit — 简化模式(在redirect_uri 的Hash传递token; Auth客户端运行在浏览器中,如JS,Flash)
refresh_token — 刷新access_token)
四:获取Token
输入参数:grant_type:验证模式 , client_id :服务端定义 , client_secret:秘钥 服务端和客户端共同保存 类似于微信的Appsecrret
生成项目,然后本地用Postman调试

返回的参数分别是:access_token:我们需要的token token_type :bearer (协议固定) expires_in:有效期(可以自定义) refresh_token:token重新过期后,重新获取token用到(暂时没用)
五:使用access_token访问接口路由
在Webapi中 ,我们用在方法加上 Authorize ,来表示这个方法访问需要授权, 如果不加Authorize ,那么token就没有意义。。 如下

我们不带token访问一下看看:

显示已拒绝我们的请求授权。
加了access-Token之后,注意token放的位置,在请求头Headers里 添加 Authorization:bearer token。 bearer与token之间有一个空格

验证的过程,是在我们Oauth2.0封装起来啦,可以查看。
到这里,用Oauth2.0加Owin的Webapi请求验证--accesstoken完成。。基本每一步都有注释,很好理解
简单的两句代码,双倍的快乐
.NET 请求认证之access-token(oauth2.0与owin的结合)的更多相关文章
- 使用Fiddler获取OAuth2认证的access token时候返回502
微软动态CRM专家罗勇 ,回复322或者20190402可方便获取本文,同时可以在第一间得到我发布的最新博文信息,follow me! 我这里Fiddler的Composer功能来获取OAuth2 认 ...
- Github 最简单的认证方式 - Access Token
Github 本身提供了多种认证方式,所有开发人员可以各取所需. SSH,这是最原始的方式,如果使用git bash只要按照官方文档一步一步配置就好了 小心坑:SSH有可能需要配置代理,否则无法解析服 ...
- C# 网络编程之豆瓣OAuth2.0认证具体解释和遇到的各种问题及解决
近期在帮人弄一个豆瓣API应用,在豆瓣的OAuth2.0认证过程中遇到了各种问题,同一时候自己须要一个个的尝试与解决,终于完毕了豆瓣API的訪问.作者这里就不再吐槽豆瓣的认证文档了,毕 ...
- OAuth2.0的refresh token
最近看人人网的OAuth认证,发现他是OAuth2.0,之前一直看的是新浪的OAuth,是OAuth1.0. 二者还是有很多不同的,主要的不同点在access token的获取方式. OAuth1.0 ...
- 【转】OAuth2.0的refresh token
转载自http://www.html-js.com/?p=1297 最近看人人网的OAuth认证,发现他是OAuth2.0,之前一直看的是新浪的OAuth,是OAuth1.0. 二者还是有很多不同的, ...
- Spring Security OAuth2.0认证授权五:用户信息扩展到jwt
历史文章 Spring Security OAuth2.0认证授权一:框架搭建和认证测试 Spring Security OAuth2.0认证授权二:搭建资源服务 Spring Security OA ...
- OAuth2.0学习(1-11)新浪开放平台微博认证-使用OAuth2.0调用微博的开放API
使用OAuth2.0调用API 使用OAuth2.0调用API接口有两种方式: 1. 直接使用参数,传递参数名为 access_token URL 1 https://api.weibo.com/2/ ...
- OAuth2.0学习(1-2)OAuth2.0的一个企业级应用场景 - 新浪开放平台微博OAuth2.0认证
http://open.weibo.com/wiki/%E9%A6%96%E9%A1%B5 开发者可以先浏览OAuth2.0的接口文档,熟悉OAuth2.0的接口及参数的含义,然后我们根据应用场景各自 ...
- 使用微服务架构思想,设计部署OAuth2.0授权认证框架
1,授权认证与微服务架构 1.1,由不同团队合作引发的授权认证问题 去年的时候,公司开发一款新产品,但人手不够,将B/S系统的Web开发外包,外包团队使用Vue.js框架,调用我们的WebAPI,但是 ...
随机推荐
- 小程序开发顶部TAB栏和侧边分类点击
先上一个效果图: 根据这个效果图我来说内容. 首先是顶部tab栏 效果实现依靠的是一个组件scroll-view.这个组件很有意思,可以多层嵌套,当然它的属性也很多. 这里主要用的是scroll-x, ...
- JQuery去实现校验用户名
JQuery 是什么? javascript 的代码框架. 有什么用? 简化代码,提高效率. 核心 write less do more , 写得更少,做的更多. load //找到这个元素, 去执行 ...
- List实体类、DataTable与xml互转
序列化常用Attribute讲解说明 [XmlRootAttribute("MyCity", Namespace="abc.abc", IsNullable=f ...
- goroutine简介
一.goroutine简介 Golang中最迷人的一个优点就是从语言层面就支持并发 在Golang中的goroutine(协程)类似于其他语言的线程 并发和并行 并行(parallelism)指不同的 ...
- express连接数据库 读取表
connection 连接数据库 connection.query 查询表 1.依赖 const mysql = require('mysql'); 连接数据库代码 var connecti ...
- 洛谷P1433 吃奶酪 题解 状态压缩DP
题目链接:https://www.luogu.com.cn/problem/P1433 题目大意 房间里放着 \(n\) 块奶酪.一只小老鼠要把它们都吃掉,问至少要跑多少距离?老鼠一开始在 \((0, ...
- js库链接
1.autoHeightTextarea自适应高度的textarea是一款jquery插件,支持链式调用,支持设置最小行数.最小高度.最大行数和最大高度,在输入文字的时候实现textarea的高度自适 ...
- blkid命令 获取文件系统类型、UUID
在Linux下可以使用blkid命令对查询设备上所采用文件系统类型进行查询.blkid主要用来对系统的块设备(包括交换分区)所使用的文件系统类型.LABEL.UUID等信息进行查询.要使用这个命令必须 ...
- 十五、CI框架之自动加载数据库
一.在config的autoload.php文件中,如果写入以下代码,那么在控制器中无需再次加载数据库了,相当于全局自动加载数据库了 不忘初心,如果您认为这篇文章有价值,认同作者的付出,可以微信二维码 ...
- 文献阅读报告 - Context-Based Cyclist Path Prediction using RNN
原文引用 Pool, Ewoud & Kooij, Julian & Gavrila, Dariu. (2019). Context-based cyclist path predic ...