程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
 程式師世界 >> 編程語言 >> .NET網頁編程 >> 關於.NET >> 基於DotNetOpenAuth的OAuth實現示例代碼:如何獲取access token

基於DotNetOpenAuth的OAuth實現示例代碼:如何獲取access token

編輯:關於.NET

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。

查看本欄目

  1. 上一頁:
  2. 下一頁:
Copyright © 程式師世界 All Rights Reserved