ASP. NET Web API with Owin OAuth: Calling protected APIs using Access Toke

Source: Internet
Author: User
Tags oauth



In the previous blog post, we used the OAuth client credential grant authorization method on the server side via Cnblogsauthorizationserverprovider (Authorization An implementation of the server successfully issued the access token and successfully received the access token on the client.



What's the use of Access tokens? Authentication of Access to resource Server (such as Web API) in OAuth is based on access Token. No matter what kind of client to call, Resource server is always untouchables, just recognize access Token.



access token validation with OAuth enabled in the ASP. NET Web API is simple, just add the [authorize] tag to the appropriate controller or action, such as:


 
 
[Authorize]
public class ValuesController : ApiController
{
    // GET api/values
    public IEnumerable<string> Get()
    {
        return new string[] { "value1", "value2" };
    }
}


After adding [authorize], if you do not use Access Token, the following error occurs when you invoke the API:


{"Message": "Authorization have been denied for this request."}


At this point you may ask, why does the addition of [authorize] have this effect? How did the original forms verification not work?



The reason is that when you create the ASP. NET Web API project with Visual Studio, VS automatically adds the appropriate code to you, opens the WebApiConfig.cs, and you see the following 2 lines of code:


config.SuppressDefaultHostAuthentication();
config.Filters.Add(new HostAuthenticationFilter(OAuthDefaults.AuthenticationType));


This is the 2 lines of code that changed the role of [authorize].



Enabling OAuth validation in the ASP. is simple (behind the scenes, Microsoft implements the Owin-based OAuth, which implements the source code in the Katana project).



How does the client use access token to invoke the Web API?



Also very simple, as long as the HTTP request header to add Bearer:token, the client calls the sample code as follows:


  
 public class OAuthClientTest
    {
        private HttpClient _httpClient;

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

        [Fact]
        public async Task Call_WebAPI_By_Access_Token()
        {
            var token = await GetAccessToken();
            _httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", token);
            Console.WriteLine(await (await _httpClient.GetAsync("/api/values")).Content.ReadAsStringAsync());
        }

        private async Task<string> GetAccessToken()
        {
            var parameters = new Dictionary<string, string>();
            parameters.Add("client_id", "1234");
            parameters.Add("client_secret", "5678");
            parameters.Add("grant_type", "client_credentials");

            var response = await _httpClient.PostAsync("/token", new FormUrlEncodedContent(parameters));
            var responseValue = await response.Content.ReadAsStringAsync();                

            return JObject.Parse(responseValue)["access_token"].Value<string>();
        }
    }


The results of the operation are as follows:


["Value1", "value2"]


Get!



The integration of the ASP. NET Web API and OAuth based on the Owin implementation makes the original complex problem simple.


Reference page:hTTP://QINgQINgQuege.CNbLogs.Com/P/5933752.hTmL


ASP. NET Web API with Owin OAuth: Calling protected APIs using Access Toke


Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.