ASP. NET Web API and Owin OAuth: Use Access Toke to call protected API, owinoauth

Source: Internet
Author: User
Tags oauth

ASP. NET Web API and Owin OAuth: Use Access Toke to call protected API, owinoauth

In the previous blog, we used the Client Credential Grant Authorization method of OAuth to successfully issue Access tokens on the Server through CNBlogsAuthorizationServerProvider (an implementation of Authorization Server, the Access Token is successfully obtained on the client.

What is the use of Access Token? In OAuth, Resource Server (such as Web API) Access permissions are verified based on Access Token. No matter what client calls it, the Resource Server is always selfless and only recognizes the Access Token.

Enabling OAuth Access Token verification in ASP. NET Web APIs is very simple. You only need to add the [Authorize] mark to the corresponding Controller or Action, for example:

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

After [Authorize] is added, if you do not use the Access Token, the following error occurs when calling the API:

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

At this time, you may ask, why does [Authorize] have this effect? Why didn't the original Forms authentication work?

When you create an ASP. NET Web API project using Visual Studio, VS automatically adds the corresponding code to open WebApiConfig. cs. You will see the following two lines of code:

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

These two lines of code change the role of [Authorize.

Enabling OAuth verification in ASP. NET Web APIs is as simple as that (Microsoft implements OWIN-based OAuth and implements the source code in the Katana project ).

How can I use the Access Token on the client to call the Web API?

You only need to add Bearer: Token to the http request header. The client call example code is 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 running result is as follows:

["value1","value2"]

Done!

The integration of ASP. NET Web APIs and Owin-based OAuth simplifies the original complicated problem.

Reference page: http://qingqingquege.cnblogs.com/p/5933752.html

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.