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。
查看本欄目