通过不同域上的 REST Web 服务进行用户身份验证 - asp.net

发布于 2024-11-01 00:18:54 字数 928 浏览 0 评论 0原文

我希望连接到不同域上的 Web 服务以对用户进行身份验证。 Web 服务本身是一个用 Java 编写的 RESTful 服务。数据以 JSON 格式传入和传出。

我最初尝试使用 jQuery 进行连接(见下文),

        function Login()
    {
        $.ajax({
        url: "http://www.externaldomain.com/login/authenticate",  
        type: "POST",
        dataType: "json",
        contentType: "application/json",
        data: "{'emailAddress':'[email protected]', 'password':'Password1'}", 
        success: LoadUsersSuccess,
            error: LoadUsersError
        });         
    }
    function LoadUsersSuccess(){
        alert(1);
    }
    function LoadUsersError(){
        alert(2);
    }

但是,在检查 Firebug 时,这会出现 405 Method Not allowed 错误。

在这个阶段,由于这是我第一次真正使用 Web 服务,我真的想知道这是否是最好的做事方式?为了找到解决方案是否值得坚持使用这种方法,或者我最好尝试找到此问题的服务器端答案?如果是这样,有人可以发布任何示例吗?

非常感谢

I am looking to connect to a web service on a different domain in order to authenticate users. The Web Service itself is a RESTful service, written in Java. Data is passed to and from it in JSON.

I initially tried to connect using jQuery (see below)

        function Login()
    {
        $.ajax({
        url: "http://www.externaldomain.com/login/authenticate",  
        type: "POST",
        dataType: "json",
        contentType: "application/json",
        data: "{'emailAddress':'[email protected]', 'password':'Password1'}", 
        success: LoadUsersSuccess,
            error: LoadUsersError
        });         
    }
    function LoadUsersSuccess(){
        alert(1);
    }
    function LoadUsersError(){
        alert(2);
    }

However, when checking on Firebug, this brought up a 405 Method Not Allowed error.

At this stage, as this is the first time I've really worked with web services, I really just wondered whether this was the best way to do things? Is it worth persevering with this method in order to find a solution, or am I best to maybe try and find a server-side answer to this issue? If so, does anyone have any examples they could post up?

Many thanks

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

明月夜 2024-11-08 00:18:54

在浏览器中进行跨域 Web 服务调用非常棘手。由于这是一个潜在的安全漏洞,浏览器会阻止这些类型的请求。不过,有一个名为 JSONP 的解决方法。如果您使用 JSONP 而不是普通 JSON,您应该能够发出跨域请求。

Doing cross-domain web service calls in a browser is very tricky. Because it's a potential security vulnerability, browsers block these types of requests. However, there is a workaround called JSONP. If you use JSONP instead of plain JSON, you should be able to make the cross-domain request.

獨角戲 2024-11-08 00:18:54

好吧,为了更新我所在的位置,我检查了 firebug 和外部服务器,我收到 405 错误的原因是因为我正在执行 Get 而不是 Post。

我需要做的是发送用户名和密码,然后接收返回的 GUID,该 GUID 将用于将来的任何请求。我认为在代码中包含“type:post”就足够了,但显然还不够。有人知道我在这里可能会出错吗?正如我所说,作为网络服务的新手,我在网上尝试过的任何尝试都没有任何效果。非常感谢

Right ok, to update where I am, I checked in firebug and on the external server and the reason why I'm getting a 405 error is because I'm doing a Get rather than a Post.

What I need to do is send the username and password, then receive a GUID back which will then be used for any future requests. I thought by having 'type:post' in the code would be enough but apparently not. Anyone know where I might be going wrong here? As I said, a novice to web services and nothing I have tried from looking online has had any effect. Many thanks

暮凉 2024-11-08 00:18:54

好的,我解决了问题,我通过返回 C# 并在那里完成它,而不是使用 jQuery 或 JSONP,并且我使用 Json.Net 来处理收到的数据。这是代码:

protected void uxLogin_Click(object sender, EventArgs e)
{
StringBuilder data = new StringBuilder();
data.Append("{");
data.Append("'emailAddress': '" + uxEmail.Text + "', ");
data.Append("'password': '" + uxPassword.Text + "'");
data.Append("}");

byte[] byteData = UTF8Encoding.UTF8.GetBytes(data.ToString());
string url = System.Configuration.ConfigurationManager.AppSettings["AuthenticationURL"].ToString();

string JSONCallback = string.Empty;
Uri address = new Uri(url);

// Create the web request  
HttpWebRequest request = WebRequest.Create(address) as HttpWebRequest;

// Set type to POST  
request.Method = "POST";
request.ContentType = "application/json";
// Create a byte array of the data we want to send  

// Set the content length in the request headers  
request.ContentLength = byteData.Length;

// Write data  
using (Stream postStream = request.GetRequestStream())
{
    postStream.Write(byteData, 0, byteData.Length);
}

// Get response  
using (HttpWebResponse response = request.GetResponse() as HttpWebResponse)
{
    // Get the response stream  
    StreamReader reader = new StreamReader(response.GetResponseStream());

    // Console application output  
    JSONCallback = reader.ReadToEnd().ToString();
}


if (!String.IsNullOrEmpty(JSONCallback))
{
    JObject jObject = JObject.Parse(JSONCallback);
    if ((bool)jObject["loginResult"] == false)
    {
        string errorMessage = jObject["errorMessage"].ToString();
        int errorCode = (int)jObject["errorCode"];
    }
    else
    {
        string idToken = jObject["idToken"].ToString();
        Session["Userid"] = idToken;
        Response.Redirect("~/MyDetails.aspx");
    }
}
else
{
    uxReturnData.Text = "The web service request was not successful - no data was returned";
}

}

无论如何,谢谢:)

Ok, I got the problem solved, and I did it by going back to C# and doing it there instead of using jQuery or JSONP and I used Json.Net for handling the data received. Here is the code:

protected void uxLogin_Click(object sender, EventArgs e)
{
StringBuilder data = new StringBuilder();
data.Append("{");
data.Append("'emailAddress': '" + uxEmail.Text + "', ");
data.Append("'password': '" + uxPassword.Text + "'");
data.Append("}");

byte[] byteData = UTF8Encoding.UTF8.GetBytes(data.ToString());
string url = System.Configuration.ConfigurationManager.AppSettings["AuthenticationURL"].ToString();

string JSONCallback = string.Empty;
Uri address = new Uri(url);

// Create the web request  
HttpWebRequest request = WebRequest.Create(address) as HttpWebRequest;

// Set type to POST  
request.Method = "POST";
request.ContentType = "application/json";
// Create a byte array of the data we want to send  

// Set the content length in the request headers  
request.ContentLength = byteData.Length;

// Write data  
using (Stream postStream = request.GetRequestStream())
{
    postStream.Write(byteData, 0, byteData.Length);
}

// Get response  
using (HttpWebResponse response = request.GetResponse() as HttpWebResponse)
{
    // Get the response stream  
    StreamReader reader = new StreamReader(response.GetResponseStream());

    // Console application output  
    JSONCallback = reader.ReadToEnd().ToString();
}


if (!String.IsNullOrEmpty(JSONCallback))
{
    JObject jObject = JObject.Parse(JSONCallback);
    if ((bool)jObject["loginResult"] == false)
    {
        string errorMessage = jObject["errorMessage"].ToString();
        int errorCode = (int)jObject["errorCode"];
    }
    else
    {
        string idToken = jObject["idToken"].ToString();
        Session["Userid"] = idToken;
        Response.Redirect("~/MyDetails.aspx");
    }
}
else
{
    uxReturnData.Text = "The web service request was not successful - no data was returned";
}

}

Thanks anyway :)

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文