基于DotNetOpenAuth的OAuth实现示例代码: 获取access token
1. 场景
根据OAuth 2.0规范,该场景发生于下面的流程图中的(D)(E)节点,根据已经得到的authorization code获取access token。
2. 实现环境
DotNetOpthAuth v5.0.0-alpha3, ASP.NET MVC 5, .NET Framework 4.5.1。
2. 主要实现示例代码
2.1. Authorization Server实现代码
2.1.1. ASP.NET MVC Controller实现代码
using System.Threading.Tasks; using System.Web.Mvc; using CNBlogs.Open.Domain.Entities.OpenAuth; using DotNetOpenAuth.OAuth2; using DotNetOpenAuth.Messaging; namespace CNBlogs.Open.Web.Controllers { public class OAuthController : Controller { public async Task<ActionResult> Token() { var authServer = new AuthorizationServer(new AuthorizationServerHost()); var response = await authServer.HandleTokenRequestAsync(Request); return response.AsActionResult(); } } }
2.1.2. IAuthorizationServerHost接口实现
需要实现IsAuthorizationValid与CreateAccessToken这两个方法,实现代码如下:
public class AuthorizationServerHost : IAuthorizationServerHost { public bool IsAuthorizationValid(IAuthorizationDescription authorization) { return authorization.ClientIdentifier == "webclientdemo" && ClientIdentifier.; } public AccessTokenResult CreateAccessToken(IAccessTokenRequest accessTokenRequestMessage) { var accessToken = new AuthorizationServerAccessToken { Lifetime = TimeSpan.FromHours(10), SymmetricKeyStore = this.CryptoKeyStore, }; var result = new AccessTokenResult(accessToken); return result; } }
2.2 Client实现代码
namespace OAuthWebClient.Controllers { public class OAuthController : Controller { private static readonly string CLIENT_ID = "webclientdemo"; public async Task<ActionResult> Redirect(string code) { var httpClient = new HttpClient(); var queryDict = new Dictionary<string, string> { {"grant_type", "authorization_code"}, {"code", code}, {"redirect_uri", Request.Url.Scheme + "://" + Request.Url.Host + Request.Url.AbsolutePath}, {"client_id", CLIENT_ID}, {"client_secret", "webclientdemosecret"} }; var httpContent = new FormUrlEncodedContent(queryDict); var response = await httpClient.PostAsync(Request.Url.Scheme + "://open.cnblogs.com/oauth/token", httpContent); return Content(await response.Content.ReadAsStringAsync()); } } }
考虑到跨平台访问的方便性,未使用DotNetOpenAuth.OAuth2.WebServerClient。
3. 参考资料:
- DotNetOpenAuth源代码:https://github.com/DotNetOpenAuth/DotNetOpenAuth
- OAuth 2.0规范:http://tools.ietf.org/html/rfc6749