1. 程式人生 > >OAuth客戶端調用

OAuth客戶端調用

.com blog quest path ceo form return console 參考

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; } } [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()); } }

1)是的,獲取access token的URL就是由TokenEndpointPath決定的。

2)獲取access token與Web API沒有關系,Web API對應於OAuth中的Resource Server,而獲取access token訪問的是OAuth中的Authorization Server(CNBlogsAuthorizationServerProvider)。Resource Server(Web API+ Authorize)驗證客戶端完全是根據access token。

3)是的,在access token的生命周期內,不需要再請求Authorization Server獲取token。token不是通過GrantResourceOwnerCredentials生成的。

4)如果不需要設置AuthenticationTicket的屬性,當然可以改為context.Validated(oAuthIdentity),這個方法就只是幫你new一下AuthenticationTicket。

5)從測試情況看,去掉await base.GrantResourceOwnerCredentials(context);沒影響,但由於不知道基類的這個方法中究竟幹了啥,保險起見,就沒去掉。

6)ValidateClientAuthentication驗證的是客戶端(Client),基於client_id與client_secret;GrantResourceOwnerCredentials驗證的是用戶(ResourceOwner),基於username與password。不能去掉。


參考

在ASP.NET中基於Owin OAuth使用Client Credentials Grant授權發放Token

ASP.NET Web API與Owin OAuth:使用Access Toke調用受保護的API

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

OAuth客戶端調用