Ankita
Ankita

Reputation: 1456

Authentication in Web API

I know this is very common question. But I really do not know how to integrate it. I want to add authentication to my web api services. Right now I have created one console application to call service's method.

I have gone through this blog. I just want to implement authentication filter as mentioned in this article.

I want to know how can I pass credentials along with HTTPClient from my console application, fetch those things to web API and authenticate them.

I have created authentication filter but it does not invoke AuthenticateAsync method of authentication filter.

To pass http client I have done this:

 public void GetData()
    {
        HttpClient cons = new HttpClient();
        cons.BaseAddress = new Uri("http://localhost:50524/");
        cons.DefaultRequestHeaders.Accept.Clear();
        cons.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
        var data = Encoding.ASCII.GetBytes("Ankita:ankita123");
        var header = new AuthenticationHeaderValue("Basic", Convert.ToBase64String(data));
        cons.DefaultRequestHeaders.Authorization = header;

        //MyAPIPost(cons).Wait();
        MyAPIGet(cons).Wait();
    }

Upvotes: 3

Views: 13719

Answers (3)

Ankita
Ankita

Reputation: 1456

I have successfully implemented authentication using this article. In that filter attribute is implemented.

Upvotes: 0

Itay Podhajcer
Itay Podhajcer

Reputation: 2664

Considering you are trying to access the API with an HttpClient, you can pass it an instance of HttpClientHandler when creating it, which allows you to set the credentials that will be used when it performs requests:

new HttpClient(new HttpClientHandler { Credentials = new NetworkCredential(userName, password) })

Hope it helps!

Upvotes: 0

jegtugado
jegtugado

Reputation: 5141

Teaching you how to implement authentication in Web API will take a lot of time. You better stick to online tutorials.

The blog you've read tackles about different authentication for ASP.NET. Since you've tagged your question as ASP.NET Web API 2, I would suggest using a token-based authentication utilizing OWIN middleware. Check this out. The guide uses a console application for checking the requests to the web API.

The gist of it is...

Client > Token Provider (Generate token for valid user) > Web API > Check if Token is Valid (Existing and not expired) > Authenticate!

Upvotes: 3

Related Questions