locked
Web API doesn't return token in Chrome RRS feed

  • Question

  • User-184962931 posted

    Hello,

    This post is about the problems with obtaning the authorization token from ASP.NET Identity using Web API.

    1/ Fiddler

    POST Request on http://localhost:50852/token with body:

    username=user@mail.pl&password=Haslo1!&grant_type=password

    Is token? YES.

    2/ IE

    $.ajax({
    url: 'http://localhost:50852/token',
    crossDomain: true, 
    crossOrigin:true,
    method: 'POST',
    contentType: 'application/json',
    data: {
    grant_type: 'password',
    username: $('#txtUsername').val(),
    password: $('#txtPassword').val()
    },
    success: function (response) {
    sessionStorage.setItem('accessToken', response.access_token);
    },
    error: function (jqHXR) {
    $('#divErrorText').text(jqHXR.responseText);
    $('#divError').show('fade');
    }
    });

    Is token? YES.

    3/ Google chrome: the same jQuery script as in IE case (code above)

    Is token? NO.

    Additional information: When I enter "http://localhost:50852/token" to the google textbox adress and press enter, the following message is displayed:

    {"error":"unsupported_grant_type"}

    How can I obtain the token in Google Chrome? Why it does work in IE, but not in Chrome?

    Thank you in advance.

    Wednesday, February 8, 2017 6:36 PM

All replies

  • User-2057865890 posted

    Hi Luksta,

    The OAuth 2.0 spec mandates the content-type HTTP header should be application/x-www-form-urlencoded.

    You could explicitly pass

    contentType: 'application/x-www-form-urlencoded; charset=UTF-8'

    or remove

    contentType: 'application/json'

    reference: https://tools.ietf.org/html/rfc6749#section-4.1.3

    Best Regards,

    Chris

    Thursday, February 9, 2017 6:09 AM
  • User-184962931 posted

    I have edited the whole content of my post because I got one, simple question about the CORS in general.

    What is the difference between simple request which is made in Fiddler:

    POST request on http://mywebapi.com/token

    [header]
    
    User-Agent: Fiddler
    Host: mywebapi.com
    
    
    [body]
    
    username=someLogin@domain.com&password=Haslo1!&grant_type=password


    and the request made by jQuery:

    $.ajax({
                        url: 'http://mywebapi.com/token',
                        method: 'POST',
                        contentType: 'application/x-www-form-urlencoded; charset=UTF-8',
                        data: {
                            username: $('#txtUsername').val(),
                            password: $('#txtPassword').val(),
                            grant_type: 'password'
                        },
                        success: function (response) {
                            sessionStorage.setItem("accessToken", response.access_token);
                            alert(response.access_token);
                        },
                        // Display errors if any in the Bootstrap alert <div>
                        error: function (jqXHR) {
                            $('#divErrorText').text(jqXHR.responseText);
                            $('#divError').show('fade');
                        }
                    });

    My CORS is active.

    Fiddler can obtain the token - jquery request from other origin can't (it doesn't matter if I use IE or Chrome).

    Why is that?

    Thursday, February 9, 2017 9:05 AM
  • User-184962931 posted

    Hello again, after a few attempts, I finally resolved my issue. Please, take a look below:

    1/ Cors configuration in WebApiConfig.cs - doesn't work at all.

    using System.Web.Http.Cors;

    ...

    public static void Register(HttpConfiguration config) { EnableCorsAttribute cors = new EnableCorsAttribute("*", "*", "*"); config.EnableCors(cors); // Web API configuration and services // Configure Web API to use only bearer token authentication. config.SuppressDefaultHostAuthentication(); config.Filters.Add(new HostAuthenticationFilter(OAuthDefaults.AuthenticationType)); // Web API routes config.MapHttpAttributeRoutes(); config.Routes.MapHttpRoute( name: "DefaultApi", routeTemplate: "api/{controller}/{id}", defaults: new { id = RouteParameter.Optional } ); }

    2/ Cors configuration in Web.config - works fine always, under IE, Chrome, from different origins

      <system.webServer>
        <httpProtocol>
          <customHeaders>
            <add name="Access-Control-Allow-Origin" value="*" />
            <add name="Access-Control-Allow-Headers" value="Content-Type" />
            <add name="Access-Control-Allow-Methods" value="GET, POST, PUT, DELETE, OPTIONS" />
          </customHeaders>
        </httpProtocol>
      ...
      </system.webServer>

    Why the first option doesn't work?

    Friday, February 10, 2017 8:53 PM
  • User-2057865890 posted

    Hi Luksta,

    1/ Cors configuration in WebApiConfig.cs - doesn't work at all.

    If you set the attribute at more than one scope, the order of precedence is:

    Action
    Controller
    Global

    reference: https://docs.microsoft.com/en-us/aspnet/web-api/overview/security/enabling-cross-origin-requests-in-web-api

    Best Regards,

    Chris

    Wednesday, February 15, 2017 9:59 AM