简体   繁体   中英

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.

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.

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.

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

在此处输入图片说明

Make sure that you wait for the DOM to be loaded before subscribing to the click event of the login button:

$(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:

$(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).


UPDATE:

It looks like your Web API simply doesn't allow CORS and thus the request is blocked.

You may have a look at the following article for enabling CORS in Web API.

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 .

HTH

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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