OWIN token authentication 400 Bad Request on OPTIONS from browser

I am using token authentication for small project based on this article: http://bitoftech.net/2014/06/09/angularjs-token-authentication-using-asp-net-web-api-2-owin-asp-net-identity/

Everything seems to work fine except one thing: OWIN based token authentication doesn't allow OPTIONS request on /token endpoint. Web API returns 400 Bad Request and whole browser app stops sending POST request to obtain token.

I have all CORS enabled in application as in sample project. Below some code that might be relevant:

public class Startup
    {
        public static OAuthBearerAuthenticationOptions OAuthBearerOptions { get; private set; }

        public void Configuration(IAppBuilder app)
        {
            AreaRegistration.RegisterAllAreas();
            UnityConfig.RegisterComponents();
            GlobalConfiguration.Configure(WebApiConfig.Register);
            FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
            RouteConfig.RegisterRoutes(RouteTable.Routes);
            BundleConfig.RegisterBundles(BundleTable.Bundles);

            HttpConfiguration config = new HttpConfiguration();

            app.UseCors(Microsoft.Owin.Cors.CorsOptions.AllowAll);

            ConfigureOAuth(app);

            WebApiConfig.Register(config);

            app.UseWebApi(config);

            Database.SetInitializer(new ApplicationContext.Initializer());
        }

        public void ConfigureOAuth(IAppBuilder app)
        {
            //use a cookie to temporarily store information about a user logging in with a third party login provider
            app.UseExternalSignInCookie(Microsoft.AspNet.Identity.DefaultAuthenticationTypes.ExternalCookie);
            OAuthBearerOptions = new OAuthBearerAuthenticationOptions();

            OAuthAuthorizationServerOptions OAuthServerOptions = new OAuthAuthorizationServerOptions()
            {
                AllowInsecureHttp = true,
                TokenEndpointPath = new PathString("/token"),
                AccessTokenExpireTimeSpan = TimeSpan.FromMinutes(60),
                Provider = new SimpleAuthorizationServerProvider(),
                RefreshTokenProvider = new SimpleRefreshTokenProvider()
            };

            // Token Generation
            app.UseOAuthAuthorizationServer(OAuthServerOptions);
            app.UseOAuthBearerAuthentication(OAuthBearerOptions);
        }
    }

Below is my login function from javascript (I am using angularjs for that purpose)

var _login = function (loginData) {

        var data = "grant_type=password&username=" + loginData.userName + "&password=" + loginData.password;

        data = data + "&client_id=" + ngAuthSettings.clientId;

        var deferred = $q.defer();

        $http.post(serviceBase + 'token', data, { headers: { 'Content-Type': 'application/x-www-form-urlencoded' } }).success(function (response) {

        localStorageService.set('authorizationData', { token: response.access_token, userName: loginData.userName, refreshToken: response.refresh_token, useRefreshTokens: true });
        _authentication.isAuth = true;
        _authentication.userName = loginData.userName;
        _authentication.useRefreshTokens = loginData.useRefreshTokens;

        deferred.resolve(response);

        }).error(function (err, status) {
            _logOut();
            deferred.reject(err);
        });

        return deferred.promise;
    };

    var _logOut = function () {

        localStorageService.remove('authorizationData');

        _authentication.isAuth = false;
        _authentication.userName = "";
        _authentication.useRefreshTokens = false;

    };

Token Based Authentication using ASP.NET Web API 2, Owin, and , except one thing: OWIN based token authentication doesn't allow OPTIONS request on /token endpoint. Web API returns 400 Bad Request and whole browser  400 Bad Request errors, like all errors of this type, could be seen in any operating system and in any browser. 400 Bad Request Errors 400 Bad Request errors appear differently on different websites, so you may see something from the short list below instead of just 400 or another simple variant like that:

Override this method inside your OAuthAuthorizationServerProvider:

    public override async Task ValidateClientAuthentication(OAuthValidateClientAuthenticationContext context)
    {
        context.Validated();
    }

"HTTP 400, NET Web API, CORS Support, and how to authenticate users in Mobile Friendly: Cookies and browsers like each other, but storing No ModelState errors are available to send, so just return an empty BadRequest. Now we passed this options to the extension method “UseOAuthAuthorizationServer”  StatusCode: 400, ReasonPhrase: 'Bad Request' When using postman to make a post with the same values to the same endpoint a response is being received. This comment has been minimized.

Are you running it locally or are you publishing it to Azure like in the blog article's sample code?

If you're running it on Azure, you can easily fix CORS problems by enabling CORS in the Azure portal:

  1. Click on your App Service in the Azure Portal to enter the management screen.
  2. In the list of management options, scroll down to the 'API' section, where you will find the 'CORS' option. (Alternatively type 'CORS' in the search box).
  3. Enter the allowed origin, or enter '*' to enable all, and click save.

This fixed the OPTIONS preflight check problem for me, which a few other people seem to have had from the code in that particular blog article.

HTTP Error 400 Bad Request, Discusses that you receive an "HTTP 400 - Bad Request (Request An HTTP request that needs Kerberos authentication is sent from a browser to a The HTTP request to the server contains the Kerberos token in the Increase the settings for the MaxFieldLength and the MaxRequestBytes registry  This Access Token contains the identity of a user and also contains the token expiry time. Then the client application includes the Access Token in the Authorization header of the HTTP request to access the restricted resources from the Server until the token is expired.

Solved it. The problem was not sending with OPTIONS request header Access-Control-Request-Method

request Spotify's /api/token got errors: 400 Bad Request · Issue #321 , Occasionally your browser will display a status code instead of the desired website content. When the What does the 400 Bad Request error mean? 400.7: Invalid Content Length; 400.8: Invalid Timeout; 400.9: Invalid Lock Token With Chrome, you will find the reset functions in the system settings. According to below references.., Enable OAuth Refresh Tokens in AngularJS App using ASP .NET Web API 2, and Owin Dissecting the Web API Individual Accounts Template–Part 2: Local Accounts I got

This should do the trick:

app.UseCors(CorsOptions.AllowAll);

The OAuth 2.0 Authorization Framework: Bearer Token , I tried both the Web API and this made by what looks like 2 spotify devs. i've tried 'Authorization': 'Bearer ' + token }, json: true }; request.get(options, Client Credential auth flow: 400 Bad Request (local browser JS) #639. I am looking for a way to combine Windows Authentication and Identity/token based authentication. I have a Web API that currently uses OWIN to authenticate with Bearer tokens via the /token path and the ASP Membership database. The application that currently accesses this is external and will use a login form to log in.

Token Based Authentication using Web API 2, Owin, and Identity, The Bearer authentication scheme is intended primarily for server contexts where participating browsers do not have access to the Authorization request requests SHOULD contain a Cache-Control header with the "private" option. The resource server SHOULD respond with the HTTP 400 (Bad Request) status code. We’ll see how we will issue HTTP POST request to generate token in the next steps. We’ve specified the expiry for token to be 24 hours, so if the user tried to use the same token for authentication after 24 hours from the issue time, his request will be rejected and HTTP status code 401 is returned.

Why do I get Error code 400 "bad Request" when posting HTTP , There are 3 Common Methods of Web API Authentication: When a user enters the name and password into the browser or mobile Then we passed the options to the extension method "UseOAuthAuthorizationServer" which will add Here we will get status as 400 Bad Request and also get the error  I had the exact same issue. It drove me nuts!! I finally found out that my assumption around how the MachineKey works was wrong! If you don't setup a MachineKey on your PC or hard code one in the web.config file, then IIS will create one automatically for you.

request will fail with a 400 Bad Request status code, to exchange for an Oauth2 access token by using the code? post url: https://​auth.brightspace.com/core/connect/token. parameter string:. Token-Based Authentication in Web API. In this article, I am going to discuss how to implement Token Based Authentication in Web API to secure the server resources with an example. Please read our previous article where we discussed how to implement Client-Side HTTP Message Handler with some examples. As part of this article, we are going to

Comments
  • Thanks @knr, your solution works fine for me. I also add the header "Allow" in the response, giving the list of HTTP verb admitted for the resources: context.OwinContext.Response.Headers.Add("Allow", new[] { "GET, POST, PUT, DELETE, HEAD" });
  • Once more, this answer saves me hours of bug tracking. Can't thank you enough +1M
  • Was going to reply you, but you solved it, glad that my tutorial and code samples are useful :)
  • Same problem here. And I still haven't understood how to solve this.
  • I would have been nice if you elaborated on how you solved the issue.. I solved it using the solution posed by @knr
  • :) Nice solution.. but how ?
  • Please explain a little, so that other users can understand the reason for the issue and how the solution works. Thanks :)