一步步搭建最简单oauth2.0认证和授权
oauth2.0 最早接触这个概念是在做微信订阅号开发。当时还被深深的绕进去,关于oauth2.0的解释网上有好多,而且都讲解的比较详细,下面给大家价格参考资料。
http://owin.org/
http://brockallen.com/2013/10/24/a-primer-on-owin-cookie-authentication-middleware-for-the-asp-net-developer/
http://www.asp.net/aspnet/overview/owin-and-katana/an-overview-of-project-katana
http://www.asp.net/aspnet/overview/owin-and-katana/owin-middleware-in-the-iis-integrated-pipeline
http://www.asp.net/aspnet/overview/owin-and-katana/owin-startup-class-detection
http://msdn.microsoft.com/en-us/library/ff359101.aspx
接下来用最简短的代码实现author认证和授权。我们也可以先实现简单案例,在理解。
这里我以客户端模式为例。
1.ASP.NET MVC 4 Web API 项目或者MVC5
2. 添加引用
Owin.dll
Microsoft.Owin.dll
Microsoft.Owin.Host.SystemWeb.dll
Microsoft.Owin.Security.dll
Microsoft.Owin.Security.Oauth.dll
Microsoft.Owin.Security.Cookies.dll
MicrosoftAspNet.Identity.Owin.dll
3.修改 App_Start 文件夹下面 Startup.Auth.cs文件,把原来自动生成那些东西全部去掉。
public void ConfigureAuth(Owin.IAppBuilder app){
var OauthOptions = new Microsoft.Owin.Securtity.Oauth.OAuthAuthorizationServerOptions{
AllowInsecureHttp = true,
AuthenticationMode = Microsoft.Owin.Security.AuthenticationMode.Active,
//获取 access_token 授权服务请求地址
TokenEndpointPath = new Microsoft.Owin.PathString("/token"),
//获取 authorization_code 授权服务请求地址
AuthorizeEndpointPath = new Microsoft.Owin.PathString("/authorize"),
//access_token 过期时间
AccessTokenExpireTimeSpan = TimeSpan.FromSeconds(990),
//access_token 相关授权服务
Provider = new OpenAuthorizationServerProvider(),
//authorization_code 授权服务
RefreshTokenProvider = new OpenRefreshTokenProvider() //refresh_token 授权服务
};
app.UseOAuthBearerTokens(OAuthOptions);
}
修改Startup.cs 文件
[assembly: OwinStartup(typeof(WebApplication2.Startup))]
public partial class Startup
{
public void Configuration(IAppBuilder app)
{
ConfigureAuth(app);
var configuration = new HttpConfiguration();
WebApiConfig.Register(configuration);
app.UseWebApi(configuration);
}
}
上面这个文件的作用 相当于 Global.asax文件,在程序启动是及执行。
5. 新建 OpenAuthorizationServerProvider.cs 文件
public class OpenAuthorizationServerProvider :Microsoft.Owin.Security.OAuth.OAuthAuthorizationServerProvider
{
/// <summary>
/// 验证 client 信息
/// </summary>
public override async Task ValidateClientAuthentication(OAuthValidateClientAuthenticationContext context)
{
string clientId;
string clientSecret;
if (!context.TryGetBasicCredentials(out clientId, out clientSecret))
{
context.TryGetFormCredentials(out clientId, out clientSecret);
}
//对clientId 和 clientSecret 经行验证
context.Validated();
}
/// <summary>
/// 生成 access_token(client credentials 授权方式)
/// </summary>
public override async Task GrantClientCredentials(OAuthGrantClientCredentialsContext context)
{
var identity = new ClaimsIdentity(new GenericIdentity(
context.ClientId, OAuthDefaults.AuthenticationType),
context.Scope.Select(x => new Claim("urn:oauth:scope", x)));
context.Validated(identity);
}
}
6.新建 OpenRefreshTokenProvider.cs 文件
public class OpenRefreshTokenProvider: 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(60);
context.SetToken(Guid.NewGuid().ToString("n") + 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);
}
}
}
修改ValuesControl.cs
public class ValuesController : ApiController
{
[Authorize]
public IEnumerable<string> Get()
{
return new string[] { "value1", "value2" };
}
}
到这里整个author2.0 客户端模式 服务就待建好了。发布项目,这里发布地址我们定义:http://192.168.1.147:87。接下来我们搭建测试端。
7.新建 “控制台应用程序”。
8.新建 TokenResponse.cs 实体类。
public class TokenResponse
{
[JsonProperty("access_token")]
public string AccessToken { get; set; }
[JsonProperty("refresh_token")]
public string RefreshToken { get; set; }
[JsonProperty("token_type")]
public string TokenType { get; set; }
[JsonProperty("expires_in")]
public int expires_in { get; set; }
}
修改 Program.cs
static void Main(string[] args) {
Program p = new Program();
string result = p.Request_WebRequest("http://192.168.1.147:87/token", "ceshi", "123456", 500000);
}
public string Request_WebRequest(string uri, string username, string password, int timeout)
{
string result = string.Empty;
WebRequest request = WebRequest.Create(new Uri(uri));
if (!string.IsNullOrEmpty(username) && !string.IsNullOrEmpty(password))
{
request.Credentials = GetCredentialCache(new Uri(uri), username, password);
request.Headers.Add("Authorization", GetAuthorization(username, password));
}
if (timeout > 0)
request.Timeout = timeout;
request.Method = "POST";
request.ContentType = "application/x-www-form-urlencoded";
ASCIIEncoding asciiEncode = new ASCIIEncoding();
byte[] data = asciiEncode.GetBytes("grant_type=client_credentials");
request.ContentLength = data.Length;
Stream newStream = request.GetRequestStream();
newStream.Write(data, 0, data.Length);
newStream.Close();
WebResponse response = request.GetResponse();
Stream stream = response.GetResponseStream();
StreamReader sr = new StreamReader(stream);
result = sr.ReadToEnd();
TokenResponse tokenRes =Newtonsoft.Json.JsonConvert.DeserializeObject<TokenResponse>(result);
request = WebRequest.Create(new Uri("http://192.168.1.147:87/api/values"));
string rha = "Bearer " + tokenRes.AccessToken;
request.Headers.Add("Authorization",rha);
request.Method = "Get";
response = request.GetResponse();
stream = response.GetResponseStream();
sr = new StreamReader(stream);
result = sr.ReadToEnd();
sr.Close();
stream.Close();
return result;
}
private static CredentialCache GetCredentialCache(Uri uri, string username, string password)
{
string authorization = string.Format("{0}:{1}", username, password);
CredentialCache credCache = new CredentialCache();
credCache.Add(uri, "Basic", new NetworkCredential(username, password));
return credCache;
}
private static string GetAuthorization(string username, string password)
{
string authorization = string.Format("{0}:{1}", username, password);
return "Basic " + Convert.ToBase64String(new ASCIIEncoding().GetBytes(authorization));
}
运行测试,
得到["value1","value2"]
得到预期结果。
一步步搭建最简单oauth2.0认证和授权的更多相关文章
- OAuth2.0认证和授权以及单点登录
https://www.cnblogs.com/shizhiyi/p/7754721.html OAuth2.0认证和授权机制讲解 2017-10-30 15:33 by shizhiyi, 2273 ...
- OAuth2.0认证和授权原理
什么是OAuth授权? 一.什么是OAuth协议 OAuth(开放授权)是一个开放标准. 允许第三方网站在用户授权的前提下访问在用户在服务商那里存储的各种信息. 而这种授权无需将用户提供用户名和密 ...
- [转载] OAuth2.0认证和授权原理
转载自http://www.tuicool.com/articles/qqeuE3 什么是OAuth授权? 一.什么是OAuth协议 OAuth(开放授权)是一个开放标准,允许第三方网站在用户授权的前 ...
- OAuth2.0认证和授权机制讲解
第一章.OAuth2.0 介绍 OAuth认证 OAuth认证是为了做到第三方应用在未获取到用户敏感信息(如:账号密码.用户PIN等)的情况下,能让用户授权予他来访问开放平台(主要访问平台中的资源服务 ...
- 使用Owin中间件搭建OAuth2.0认证授权服务器
前言 这里主要总结下本人最近半个月关于搭建OAuth2.0服务器工作的经验.至于为何需要OAuth2.0.为何是Owin.什么是Owin等问题,不再赘述.我假定读者是使用Asp.Net,并需要搭建OA ...
- Spring Security OAuth2.0认证授权一:框架搭建和认证测试
一.OAuth2.0介绍 OAuth(开放授权)是一个开放标准,允许用户授权第三方应用访问他们存储在另外的服务提供者上的信息,而不 需要将用户名和密码提供给第三方应用或分享他们数据的所有内容. 1.s ...
- Owin中间件搭建OAuth2.0认证授权服务体会
继两篇转载的Owin搭建OAuth 2.0的文章,使用Owin中间件搭建OAuth2.0认证授权服务器和理解OAuth 2.0之后,我想把最近整理的资料做一下总结. 前两篇主要是介绍概念和一个基本的D ...
- Spring Security OAuth2.0认证授权二:搭建资源服务
在上一篇文章[Spring Security OAuth2.0认证授权一:框架搭建和认证测试](https://www.cnblogs.com/kuangdaoyizhimei/p/14250374. ...
- Spring Cloud Zuul 网关使用与 OAuth2.0 认证授权服务
API 网关的出现的原因是微服务架构的出现,不同的微服务一般会有不同的服务地址,而外部客户端可能需要调用多个服务的接口才能完成一个业务需求,如果让客户端直接与各个微服务通信,会有以下的问题: 客户端会 ...
随机推荐
- 转:扩展方法(C# 编程指南)
扩展方法使你能够向现有类型“添加”方法,而无需创建新的派生类型.重新编译或以其他方式修改原始类型.扩展方法是一种特殊的静态方法,但可以像扩展类型上的实例方法一样进行调用.对于用 C# 和 Visual ...
- UVa1635 - Irrelevant Elements
通过观察发现其规律符合杨辉三角 需要注意的是最后ai的系数是C(i-1,n-1) 那么,问题就可以变成判断C(0,n-1),C(1,n-1)....C(n-1,n-1)哪些是m的倍数 只需要计算出m的 ...
- mysql 中翻页
万变不离其中 select * from tableName where 条件 limit 当前页码*页面容量-1 , 页面容量
- Docker 如何支持多种日志方案?- 每天5分钟玩转 Docker 容器技术(88)
将容器日志发送到 STDOUT 和 STDERR 是 Docker 的默认日志行为.实际上,Docker 提供了多种日志机制帮助用户从运行的容器中提取日志信息.这些机制被称作 logging driv ...
- 笔记-java泛型详解
首先,先说明一下,java泛型文章的出处:http://www.cnblogs.com/lzq198754/p/5780426.html 作为学习笔记保存. 1.为什么需要泛型 泛型在Java中有很重 ...
- Spring框架学习之高级依赖关系配置(一)
上篇文章我们对Spring做了初步的学习,了解了基本的依赖注入思想.学会简单的配置bean.能够使用Spring容器管理我们的bean实例等.但这还只是相对较浅显的内容,本篇将介绍bean的相关更高级 ...
- 数据结构--KMP算法总结
数据结构—KMP KMP算法用于解决两个字符串匹配的问题,但更多的时候用到的是next数组的含义,用到next数组的时候,大多是题目跟前后缀有关的 . 首先介绍KMP算法:(假定next数组已经学会, ...
- vue小项目---管理系统
在上一篇文章中我们已经学习了vue的基本语法,常用属性,了解了vue的基本使用,现在让我们用vue配合Bootstrap来完成一个小项目. 首先导入Bootstap文件. <link rel=& ...
- javascript中数组与字符串之间的转换以及字符串的替换
数组转化为字符串: var a=['aa','bb','cc']; var b=a.join('-'); console.log(b)----->'aa-bb-cc' 字符串中的替换: 1.re ...
- form 表单处理
submit相关 当使用 submit 按钮或者 image 或者button type="submit" 来提交表单时,会触发 submit 事件,但是直接javascri ...