久久国产成人av_抖音国产毛片_a片网站免费观看_A片无码播放手机在线观看,色五月在线观看,亚洲精品m在线观看,女人自慰的免费网址,悠悠在线观看精品视频,一级日本片免费的,亚洲精品久,国产精品成人久久久久久久

分享

ASP.NET Web API與Owin OAuth:調用與用戶相關的Web API

 ThinkTank_引擎 2015-12-17

在前一篇博文中,我們通過以 OAuth 的 Client Credential Grant 授權方式(只驗證調用客戶端,,不驗證登錄用戶)拿到的 Access Token ,,成功調用了與用戶無關的 Web API。

在這篇博文中,,我們將以 OAuth 的 Resource Owner Password Credentials Grant 的授權方式( grant_type=password )獲取 Access Token,,并以這個 Token 調用與用戶相關的 Web API。

對應的應用場景是:為自家的網站開發(fā)手機 App(非第三方 App),,只需用戶在 App 上登錄,,無需用戶對 App 所能訪問的數據進行授權。

根據 OAuth 規(guī)范,,客戶端獲取 Access Token 的請求方式如下:

復制代碼
POST /token HTTP/1.1
Host: server.example.com
Authorization: Basic czZCaGRSa3F0MzpnWDFmQmF0M2JW
Content-Type: application/x-www-form-urlencoded

grant_type=password&username=johndoe&password=A3ddj3w
復制代碼

根據上面的請求方式,,在 C# 中用 HttpClient 實現一個簡單的客戶端,代碼如下:

復制代碼
public class OAuthClientTest
{
    private HttpClient _httpClient;

    public OAuthClientTest()
    {
        _httpClient = new HttpClient();
        _httpClient.BaseAddress = new Uri("http://openapi.cnblogs.com");
    } 

    [Fact]
    public async Task Get_Accesss_Token_By_Resource_Owner_Password_Credentials_Grant()
    {
        Console.WriteLine(await GetAccessToken());
    }

    private async Task<string> GetAccessToken()
    {
        var clientId = "1234";
        var clientSecret = "5678";

        var parameters = new Dictionary<string, string>();            
        parameters.Add("grant_type", "password");
        parameters.Add("username", "博客園團隊");
        parameters.Add("password", "cnblogs.com");

        _httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue(
            "Basic",
            Convert.ToBase64String(Encoding.ASCII.GetBytes(clientId + ":" + clientSecret))
            );

        var response = await _httpClient.PostAsync("/token", new FormUrlEncodedContent(parameters));
        var responseValue = await response.Content.ReadAsStringAsync();
        if (response.StatusCode == System.Net.HttpStatusCode.OK)
        {
            return JObject.Parse(responseValue)["access_token"].Value<string>();
        }
        else
        {
            Console.WriteLine(responseValue);
            return string.Empty;
        }
    }
}
復制代碼

(注:與之前相比,這里的 client_id/client_secret 改為了 Basic Authorization,,以更好的遵循 OAuth 規(guī)范)

在服務端,,基于 Owin OAuth, 針對 Resource Owner Password Credentials Grant 的授權方式,,只需重載 OAuthAuthorizationServerProvider.GrantResourceOwnerCredentials() 方法即可,。代碼如下:

復制代碼
public class CNBlogsAuthorizationServerProvider : OAuthAuthorizationServerProvider
{
    //...

    public override async Task GrantResourceOwnerCredentials(
        OAuthGrantResourceOwnerCredentialsContext context)
    {
        //調用后臺的登錄服務驗證用戶名與密碼

        var oAuthIdentity = new ClaimsIdentity(context.Options.AuthenticationType);
        oAuthIdentity.AddClaim(new Claim(ClaimTypes.Name, context.UserName));
        var ticket = new AuthenticationTicket(oAuthIdentity, new AuthenticationProperties());
        context.Validated(ticket);

        await base.GrantResourceOwnerCredentials(context);
    }
}
復制代碼

完整的CNBlogsAuthorizationServerProvider實現代碼如下(與之前相比,context.TryGetFormCredentials 改為了 context.TryGetBasicCredentials):

CNBlogsAuthorizationServerProvider

這樣,,運行客戶端程序就可以拿到 Access Token 了,。

接下來,我們拿著以這種方式獲取的 Access Token,,就可以調用與用戶相關的 Web API 了,。

在服務端我們通過一個簡單的 Web API 測試一下,代碼如下:

復制代碼
public class UsersController : ApiController
{
    [Authorize]
    public string GetCurrent()
    {
        return User.Identity.Name;
        //這里可以調用后臺用戶服務,,獲取用戶相關數所,,或者驗證用戶權限進行相應的操作
    }
}
復制代碼

然后,客戶端用以 grant_type=password 方式拿到的 Access Token 調用這個Web API,,客戶端增加的代碼如下:

復制代碼
[Fact]
public async Task Call_WebAPI_By_Resource_Owner_Password_Credentials_Grant()
{
    var token = await GetAccessToken();
    _httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", token);
    Console.WriteLine(await (await _httpClient.GetAsync("/api/users/current")).Content.ReadAsStringAsync());
}
復制代碼

客戶端運行結果如下:

"博客園團隊"

調用成功,!運行結果正是獲取 Access Token 時所用的 username 。 

結合 ASP.NET 現有的安全機制,,借助 OWIN 的威力,,Microsoft.Owin.Security.OAuth 的確讓開發(fā)基于 OAuth 的 Web API 變得更簡單。

    本站是提供個人知識管理的網絡存儲空間,,所有內容均由用戶發(fā)布,,不代表本站觀點。請注意甄別內容中的聯(lián)系方式,、誘導購買等信息,,謹防詐騙。如發(fā)現有害或侵權內容,,請點擊一鍵舉報,。
    轉藏 分享 獻花(0

    0條評論

    發(fā)表

    請遵守用戶 評論公約

    類似文章 更多