简体   繁体   English

如何使用外部登录从Web API 2获取令牌

[英]How to get token from Web API 2 using external login

I have got website and WebAPI 2 ( ASP.NET MVC 5 ) hosted at localhost but with different ports. 我已经将网站和WebAPI 2(ASP.NET MVC 5)托管在localhost上,但端口不同。

I try to get token using this javascript but no token at all and it redirects to the current website with query string containing username and password. 我尝试使用此javascript获取令牌,但根本没有令牌,它使用包含用户名和密码的查询字符串重定向到当前网站。

How to fix it? 如何解决?

 <form id="userData">
        <input type="text" name="userName" placeholder="UserName" />
        <input type="text" name="password" placeholder="Password" />
        <input type="submit" id="login" value="Login" />
 </form>

var login = function () {

  var loginData= $("#userData").serialize();
  loginData= loginData+ "&grant_type=password";

  $.ajax({
    type: 'POST',
    url: 'http://localhost:57371/Token',
    data: loginData
  }).done(function (data) {
    console.log(data);
    // Cache the access token in session storage.
    sessionStorage.setItem(tokenKey, data.access_token);
  }).fail(showError);

   return false;
};

$("#login").click(login);

var showError = function (XMLHttpRequest, textStatus, errorThrown) {
   var responseText = JSON.parse(XMLHttpRequest.responseText)
   console.log(responseText.Message + " Code: " + XMLHttpRequest.status);
   $("#output").text(JSON.stringify(responseText, null, 4));
};

Update 1. Cors is enabled OK. 更新1. Cors已启用。

public static void Register(HttpConfiguration config)
{
   EnableCrossSiteRequests(config);
}
private static void EnableCrossSiteRequests(HttpConfiguration config)
        {
            var cors = new EnableCorsAttribute(
                origins: "*",
                headers: "*",
                methods: "*");
            config.EnableCors(cors);
        }

Update 2. Error 更新2.错误

在此处输入图片说明

Make sure that you wait for the DOM to be loaded before subscribing to the click event of the login button: 在订阅登录按钮的click事件之前,请确保等待DOM加载:

$(function() {
    $("#login").click(login);
});

Also I would recommend you subscribing to the submit event of the form instead of the click event of a submit button because a form can be submitted, by for example, the user pressing Enter key while the focus is inside some if the textboxes and without clicking on any button and thus missing your AJAX call: 我也建议您订阅表单的submit事件,而不是Submit按钮的click事件,因为可以提交表单,例如,当文本框内的焦点位于某些文本框内且没有单击时,用户可以按Enter键在任何按钮上,因此错过了您的AJAX呼叫:

$(function() {
    $('#userData').submit(login);
});

This will guarantee that no matter how this form was submitted your AJAX call will execute instead of simply reloading the current page and appending the username and password as query string parameters to it (which is the behavior that you are observing at the moment). 这将确保无论以何种方式提交此表单,您的AJAX调用都将执行,而不是简单地重新加载当前页面并将用户名和密码作为查询字符串参数附加到该页面上(这是您目前正在观察的行为)。


UPDATE: 更新:

It looks like your Web API simply doesn't allow CORS and thus the request is blocked. 看起来您的Web API完全不允许CORS,因此请求被阻止。

You may have a look at the following article for enabling CORS in Web API. 您可以查看following article以在Web API中启用CORS。

Change type 变更类型

    input type="submit"

to

    input type="button"

Reason: "submit" submits the entire form so it conflicts to the desired behavior. 原因:“提交”提交了整个表单,因此与所需的行为冲突。 Whereas "button" defines a clickable button (mostly used with a JavaScript to activate a script) as described in http://www.w3schools.com/tags/att_input_type.asp . 而“按钮”定义了一个可单击的按钮(通常与JavaScript一起使用以激活脚本),如http://www.w3schools.com/tags/att_input_type.asp中所述

HTH 高温超导

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

相关问题 如何从 JS 获取和保存令牌中获取 ASP.NET Web Api 令牌(登录) - How to grab ASP.NET Web Api token (login) from a JS fetch and save token 如何使用我自己的后端 api 在 nuxt App 中获取令牌(在登录时)? - how to get token (at login) in nuxt App using my own backend api? 从Pinterest API v3获取登录令牌的正确方法 - Correct way to get login token from Pinterest API v3 如何使用 SSO oauth 2.0 登录,然后存储令牌以从邮递员自动化脚本运行所有其他 API? - How to login using SSO oauth 2.0 and then storing token to run all other API from postman automation script? 如何通过AngularJS $ http从ASP.Net Web API 2获取Access Token? - How to get Access Token from ASP.Net Web API 2 via AngularJS $http? 如何从外部API获取数据? - How to get data from external api? 如何在从javascript传递到web api 2时隐藏或保护令牌 - how to hide or secure the token when passing from javascript to web api 2 如何使用基于令牌的身份验证从ExtJS调用Web API - How to call Web API from ExtJS with token based authentication 如何在 .Net 上隐藏外部 API 令牌 - How to hide external API token at .Net 如何从Windows窗体应用程序调用Web API登录操作 - How to call web API login action from Windows form app
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM