1. 場景 根據(jù)OAuth 2.0規(guī)范,該場景發(fā)生于下面的流程圖中的(D)(E)節(jié)點,根據(jù)已經(jīng)得到的authorization code獲取access token。 2. 實現(xiàn)環(huán)境 DotNetOpthAuth v5.0.0-alpha3, ASP.NET MVC 5, .NET Framework 4.5.1。 2. 主要實現(xiàn)示例代碼 2.1. Authorization Server實現(xiàn)代碼 2.1.1. ASP.NET MVC Controller實現(xiàn)代碼 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接口實現(xiàn) 需要實現(xiàn)IsAuthorizationValid與CreateAccessToken這兩個方法,實現(xiàn)代碼如下: 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實現(xiàn)代碼 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. 參考資料:
|
|
來自: ThinkTank_引擎 > 《DEMO》