简体   繁体   English

jQuery调用Asp.Net WebApi

[英]Jquery Call to Asp.Net WebApi

Hi Have been creating an ASP.net WebApi. 嗨,您已经在创建ASP.net WebApi。

Currently I have used the Thinktecture.IdentityModel.40 to setup a Basic Authentication Service. 当前,我已经使用Thinktecture.IdentityModel.40来设置基本身份验证服务。

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. 当我在浏览器中浏览到我的API网址时,会弹出一个用户名和密码对话框,如果输入凭据,那么我会看到正确的数据。

I would now like to create a javascript client using JQuery to authenticate to my API and then return the relevant data. 现在,我想使用JQuery创建一个JavaScript客户端以对我的API进行身份验证,然后返回相关数据。

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 我应该如何使用Jquery对我的api进行身份验证

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. 在某些情况下,如果您想通过JavaScript进行身份验证,则大多数API提供程序都使用支持三路身份验证的身份验证协议。 The most notable example is OAuth . 最著名的例子是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. 您应该在WebApi中实现某种三向身份验证协议以支持此方法。

Here are some articles that help with this: 以下是一些有助于解决此问题的文章:
http://codebetter.com/howarddierking/2011/10/11/oauth-2-0-in-web-api/ http://codebetter.com/howarddierking/2011/10/11/oauth-2-0-in-web-api/
Best way to handle authentication on .NET WCF Web API 在.NET WCF Web API上处理身份验证的最佳方法

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM