SetiSeeker
SetiSeeker

Reputation: 6684

Jquery Call to Asp.Net WebApi

Hi Have been creating an ASP.net WebApi.

Currently I have used the Thinktecture.IdentityModel.40 to setup a Basic Authentication Service.

When I browse to my API Url in the browser, a username and password dialog popup and if I enter the credentials, I then see the correct data.

I would now like to create a javascript client using JQuery to authenticate to my API and then return the relevant data.

Here is my attempt, it appears that the username and password are not getting to the server or the server is not understanding what it is getting.

Here is my Code:

  $(document).ready(function () {
        $.ajax({
            url: "http://localhost:21095/api/customers",
            beforeSend: function (xhr) {
                xhr.setRequestHeader("UserName", "user");
                xhr.setRequestHeader("Password", "pwd");
            },
            dataType: "jsonp",
            type: "GET",
            success: function (data) {
                alert(data);
                debugger
            }
        });
    });

How should I authenticate to my api using Jquery

Upvotes: 2

Views: 3391

Answers (1)

Slavo
Slavo

Reputation: 15463

Supplying the username and password in the request header as plain text is dangerous. Anyone who listens to your traffic can intercept the data and use it to do harm. In cases, where you want to authenticate through JavaScript, most API providers use an authentication protocol which supports 3-way authentication. The most notable example is OAuth.

The purpose of all this is that the username and password themselves are not exposed to the application, but rather the user grants the application permissions to access data on his behalf. This grant is in the domain of the server, so no transport of credentials is required. You should implement some 3-way authentication protocol in your WebApi to support this.

Here are some articles that help with this:
http://codebetter.com/howarddierking/2011/10/11/oauth-2-0-in-web-api/
Best way to handle authentication on .NET WCF Web API

Upvotes: 1

Related Questions