[OAuth]基于DotNetOpenAuth实现Client Credentials Grant

 

Client Credentials Grant是指直接由Client向Authorization Server请求access token,无需用户(Resource Owner)的授权。比如我们提供OpenAPI让大家可以获取园子首页最新随笔,只需验证一下Client是否有权限调用该API,不需要用户的授权。而如果Client需要进行发布博客的操作,就需要用户的授权,这时就要采用Authorization Code Grant

DotNetOpenAuth是当前做得做好的基于.NET的OAuth开源实现,项目网址:https://github.com/DotNetOpenAuth

Client Credentials Grant的流程图如下(图片1来源图片2来源):

一、Client向Authorization Server请求access token

主要操作如下:

1. 由client_id和client_secret构建出credentials。

2. 将credentials以http basic authentication的方式发送给Authorization Server。

3. 从Authorization Server的响应中提取access token

Client的实现代码如下:

public async Task<ActionResult> SiteHome()
{
var client_id = "m.cnblogs.com";
var client_secret = "20140213";
var credentials = Convert.ToBase64String(Encoding.ASCII.GetBytes(client_id + ":" + client_secret)); var httpClient = new HttpClient();
httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Basic", credentials);
var httpContent = new FormUrlEncodedContent(new
Dictionary<string, string>
{
{"grant_type", "client_credentials"}
}); var response = await httpClient.PostAsync("https://authserver.open.cnblogs.com/oauth/token", httpContent); var responseContent = await response.Content.ReadAsStringAsync();
if (response.StatusCode == System.Net.HttpStatusCode.OK)
{
var accessToken = JObject.Parse(responseContent)["access_token"].ToString();
return Content("AccessToken: " + accessToken);
}
else
{
return Content(responseContent);
}
}

二、Authorization Server验证Client,发放access token

主要操作如下:

1. Authorization Server通过IAuthorizationServerHost.GetClient()获取当前Client。

2. Authorization Server通过IClientDescription.IsValidClientSecret()验证当前Client。

3. 验证通过后,将access token包含在响应中发送给Client。

主要实现代码如下(基于ASP.NET MVC):

1. Authorization Server中Client实体类的实现代码(关键代码是IsValidClientSecret()的实现):

    public class Client : IClientDescription
{
public string Id { get; set; } public string Secret { get; set; } public Uri DefaultCallback
{
get { throw new NotImplementedException(); }
} private ClientType _clientType;
public ClientType ClientType
{
get { return _clientType; }
set { _clientType = value; }
} public bool HasNonEmptySecret
{
get { throw new NotImplementedException(); }
} public bool IsCallbackAllowed(Uri callback)
{
throw new NotImplementedException();
} public bool IsValidClientSecret(string secret)
{
return this.Secret == secret;
}
}

AuthorizationServerHost的代码(关键代码是GetClient()与CreateAccessToken()的实现):

public class AuthorizationServerHost : IAuthorizationServerHost
{
public static readonly ICryptoKeyStore HardCodedCryptoKeyStore = new HardCodedKeyCryptoKeyStore("..."); public IClientDescription GetClient(string clientIdentifier)
{
return ServiceLocator.GetService<IClientService>().GetClient(clientIdentifier);
} public AccessTokenResult CreateAccessToken(IAccessTokenRequest accessTokenRequestMessage)
{
var accessToken = new AuthorizationServerAccessToken
{
Lifetime = TimeSpan.FromHours(10),
SymmetricKeyStore = this.CryptoKeyStore,
};
var result = new AccessTokenResult(accessToken);
return result;
} public AutomatedAuthorizationCheckResponse CheckAuthorizeClientCredentialsGrant(IAccessTokenRequest accessRequest)
{
//...
} public AutomatedUserAuthorizationCheckResponse CheckAuthorizeResourceOwnerCredentialGrant
(string userName, string password, IAccessTokenRequest accessRequest)
{
//...
} public DotNetOpenAuth.Messaging.Bindings.ICryptoKeyStore CryptoKeyStore
{
get { return HardCodedCryptoKeyStore; }
} public bool IsAuthorizationValid(IAuthorizationDescription authorization)
{
return true;
} public INonceStore NonceStore
{
get { return null; }
}
}

三、Client通过access token调用Resource Server上的API

主要实现代码如下:

public async Task<ActionResult> HomePosts(string blogApp)
{
//获取access token的代码见第1部分
//...
var accessToken = JObject.Parse(responseContent)["access_token"].ToString();
httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", accessToken);
response = await httpClient.GetAsync("https://api.open.cnblogs.com/blog/posts/sitehome");
return Content(await response.Content.ReadAsStringAsync());
}

四、Resource Server验证Client的access token,响应Client的API调用请求

主要实现代码如下(基于ASP.NET Web API):

1. 通过MessageHandler统一验证access token

public static class WebApiConfig
{
public static void Register(HttpConfiguration config)
{
config.MessageHandlers.Add(new BearerTokenHandler());
}
}

2. BearerTokenHandler的实现代码(来自DotNetOpenAuth的示例代码):

public class BearerTokenHandler : DelegatingHandler
{
protected override async System.Threading.Tasks.Task<HttpResponseMessage> SendAsync(
HttpRequestMessage request, System.Threading.CancellationToken cancellationToken)
{
if (request.Headers.Authorization != null && request.Headers.Authorization.Scheme == "Bearer")
{
var resourceServer = new DotNetOpenAuth.OAuth2.ResourceServer
(new StandardAccessTokenAnalyzer
(AuthorizationServerHost.HardCodedCryptoKeyStore)); var principal = await resourceServer.GetPrincipalAsync(request, cancellationToken);
HttpContext.Current.User = principal;
Thread.CurrentPrincipal = principal;
} return await base.SendAsync(request, cancellationToken);
}
}

3. Web API的示例实现代码:

public class PostsController : ApiController
{
[Route("blog/posts/sitehome")]
public async Task<IEnumerable<string>> GetSiteHome()
{
return new string[] { User.Identity.Name };
}
}

四、Client得到Resouce Server的响应结果

根据上面的Resouce Server中Web API的示例实现代码,得到的结果是:

["client:m.cnblogs.com"] 

小结

看起来比较简单,但实际摸索的过程是曲折的。分享出来,也许可以让初次使用DotNetOpenAuth的朋友少走一些弯路。

【参考资料】

The OAuth 2.0 Authorization Framework

Claim-based-security for ASP.NET Web APIs using DotNetOpenAuth

Implementing an API Key with DotNetOpenAuth

 
 
 

实现Client Credentials Grant的更多相关文章

  1. 在ASP.NET中基于Owin OAuth使用Client Credentials Grant授权发放Token

    OAuth真是一个复杂的东东,即使你把OAuth规范倒背如流,在具体实现时也会无从下手.因此,Microsoft.Owin.Security.OAuth应运而生(它的实现代码在Katana项目中),帮 ...

  2. [OAuth]基于DotNetOpenAuth实现Client Credentials Grant

    Client Credentials Grant是指直接由Client向Authorization Server请求access token,无需用户(Resource Owner)的授权.比如我们提 ...

  3. (转)基于OWIN WebAPI 使用OAuth授权服务【客户端模式(Client Credentials Grant)】

    适应范围 采用Client Credentials方式,即应用公钥.密钥方式获取Access Token,适用于任何类型应用,但通过它所获取的Access Token只能用于访问与用户无关的Open ...

  4. 基于 IdentityServer3 实现 OAuth 2.0 授权服务【客户端模式(Client Credentials Grant)】

    github:https://github.com/IdentityServer/IdentityServer3/ documentation:https://identityserver.githu ...

  5. 基于OWIN WebAPI 使用OAuth授权服务【客户端模式(Client Credentials Grant)】

    适应范围 采用Client Credentials方式,即应用公钥.密钥方式获取Access Token,适用于任何类型应用,但通过它所获取的Access Token只能用于访问与用户无关的Open ...

  6. OAuth2.0学习(1-7)授权方式4-客户端模式(Client Credentials Grant)

    授权方式4-客户端模式(Client Credentials Grant) 客户端模式(Client Credentials Grant)指客户端以自己的名义,而不是以用户的名义,向"服务提 ...

  7. Oauth Client Credentials Grant

    http://www.cnblogs.com/dudu/p/4569857.html OAuth真是一个复杂的东东,即使你把OAuth规范倒背如流,在具体实现时也会无从下手.因此,Microsoft. ...

  8. 基于OWIN WebAPI 使用OAuth授权服务【客户端验证授权(Resource Owner Password Credentials Grant)】

    适用范围 前面介绍了Client Credentials Grant ,只适合客户端的模式来使用,不涉及用户相关.而Resource Owner Password Credentials Grant模 ...

  9. 使用Resource Owner Password Credentials Grant授权发放Token

    对应的应用场景是:为自家的网站开发手机 App(非第三方 App),只需用户在 App 上登录,无需用户对 App 所能访问的数据进行授权. 客户端获取Token: public string Get ...

随机推荐

  1. 嘿嘿。今天学习了AJAX的几个方法

    原文:嘿嘿.今天学习了AJAX的几个方法 今天学习了AJAX的几个方法,其实我很早在公司实习的时间就认识了它,但是对它一无所知,也并没有去学习它,今天学习它让我感到很兴奋因为重新了解了它,嘿嘿,下面就 ...

  2. react学习笔记2--练习Demos

    准备工作 # 0.react核心库 <script src="../build/react.js"></script> # 将JSX 语法转为 JavaSc ...

  3. 大数据系列修炼-Scala课程04

    Scala中继承实现:超类的构造.字段重写.方法重写 关于超类的构建:超类可以在子类没有位置的限制,可以在子类中调用父类的方法 类中字段重写:在重写字段前面加一个override就可以重新赋值 类中方 ...

  4. 第23章 访问者模式(Visitor Pattern)

    原文 第23章 访问者模式(Visitor Pattern) 访问者模式 导读:访问者模式是我个人认为所有行为模式中最为复杂的一种模式了,这个模式可能看一遍会看不懂,我也翻了好几个例子,依然不能很好的 ...

  5. Jquery实现 TextArea 文本框根据输入内容自动适应高度

    原文 Jquery实现 TextArea 文本框根据输入内容自动适应高度 在玩微博的时候我们可能会注意到一个细节就是不管是新浪微博还是腾讯微博在转发和评论的时候给你的默认文本框的高度都不会很高,这可能 ...

  6. 只有有lua编译能力不足200K代码吧?NO! Python 有可能。

    如今Python给人的感觉是大,东西多,在Windows上安装后竟然要占100多兆的空间. lua给人的感觉是非常小,非常轻便.Python 2.7在linux下编译出来的代码在strip之后也有3M ...

  7. CSharp设计模式读书笔记(17):迭代器模式(学习难度:★★★☆☆,使用频率:★★★★★)

    迭代器模式(Iterator Pattern):提供一种方法来访问聚合对象,而不用暴露这个对象的内部表示,其别名为游标(Cursor). 模式角色与结构: 实现代码: using System; us ...

  8. Dialog中显示倒计时,到时自己主动关闭

    这里直接用系统Dialog中加入了倒计时的显示,假设用自己定义Dialog会更美观: private TextView mOffTextView; private Handler mOffHandle ...

  9. Asp.net MVC + EF + Spring.Net 项目实践(一)

    准备用几篇文章来做一个MVC的例子,为了给新同事做参考,也为自己做个知识储备. 首先,用VS2013创建一个空白解决方案StudentManageSystem,然后添加一个MVC应用程序(可参考ASP ...

  10. Theano学习笔记(一)——代数

    标量相加 import theano.tensor as T from theano import function x = T.dscalar('x') y = T.dscalar('y') z = ...