Encountering a 400 bad request error while trying to retrieve an authentication token from an API url in Angular

I encountered a problem in my Angular 6 application where I am receiving an Http 400 Bad Request error when attempting to call the API url for login token.

The interesting thing is that the API works perfectly fine when accessed through POSTMAN.

However, it throws an error when called from my Angular application.

Service.ts (Angular)

Get_User_Token(Email, Password) {
    var data = "username=" + Email + "&password=" + Password + "&grant_type=password";
    var reqHeader = new HttpHeaders({ 'Content-Type': 'application/x-www-urlencoded', 'No-Auth': 'True' });
    return this.http.post(this.BASE_URL + '/token', data, { headers: reqHeader });
  }

web.config

<httpProtocol>
      <customHeaders>
        <add name="Access-Control-Allow-Origin" value="*" />
        <add name="Access-Control-Allow-Headers" value="*" />
        <add name="Access-Control-Allow-Methods" value="*" />
      </customHeaders>
    </httpProtocol>

startup.cs

   public void Configuration(IAppBuilder app)
        {

            OAuthAuthorizationServerOptions option = new OAuthAuthorizationServerOptions
            {
                TokenEndpointPath = new PathString("/token"),
                Provider = new ApplicationOAuthProvider(),
                AccessTokenExpireTimeSpan = TimeSpan.FromDays(1),
                AllowInsecureHttp = true
            };
            app.UseOAuthAuthorizationServer(option);
            app.UseOAuthBearerAuthentication(new OAuthBearerAuthenticationOptions());
        }

Could someone assist me in resolving this issue?

Answer №1

To begin, take a look at this post: Dealing with Access-Control-Allow-Origin for multiple domains

If you require more information, refer to this page: Enabling cross-origin requests in ASP.NET Web API 2

Here is a brief guide on how to enable cross-origin requests in ASP.NET Web API 2 in three simple steps:

Follow these instructions: 1. Start by installing the package

Install-Package Microsoft.AspNet.WebApi.Cors

2. Open the file App_Start/WebApiConfig.cs. Insert the following code into the WebApiConfig.Register method:

using System.Web.Http;
namespace WebService
{
    public static class WebApiConfig
    {
        public static void Register(HttpConfiguration config)
        {
            // New code
            config.EnableCors();

            config.Routes.MapHttpRoute(
                name: "DefaultApi",
                routeTemplate: "api/{controller}/{id}",
                defaults: new { id = RouteParameter.Optional }
            );
        }
    }
}

3. Then, apply the [EnableCors] attribute to the TestController class:

using System.Net.Http;
using System.Web.Http;
using System.Web.Http.Cors;

namespace WebService.Controllers
{
    [EnableCors(origins: "http://mywebclient.azurewebsites.net", headers: "*", methods: "*")]
    public class TestController : ApiController
    {
        // Controller methods not shown...
    }
}

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Associate a template reference variable with an attribute directive category

Currently, I am in the process of creating an attribute directive that will receive multiple templates containing additional data for filtering. This extra information will be utilized later to select the appropriate template. To achieve this, I have exten ...

Trouble incorporating SCSS color variables into Angular component_IMPORT issue

My Angular 9 app has a folder structure that includes: | app | app.component.ts | app.component.html | app.component.scss | assets | _colors.scss The _colors.scss file contains definitions for two colors: $red: #DA0000; $blue: #1080E1; In the a ...

Retrieve data that resets to undefined upon reloading from an array

Encountering an unusual error while working with TypeScript for the first time. Initially, when I use console.log(data), it displays an array with objects. However, upon reloading the webpage without making any changes, the console log shows undefined. con ...

Tips and techniques for performing Ahead-Of-Time (AOT) compilation using Angular-CLI in your

Currently working on an Angular4 project and exploring the necessity of using AOT with Angular-CLI. Since Angular-CLI operates Webpack2 in the backend and webpack can generate production builds using ng build, is it required to also use AOT with CLI? Furt ...

Struggle to deduce the generic parameter of a superior interface in Typescript

Struggling with the lack of proper type inference, are there any solutions to address this issue? interface I<T> {}; class C implements I<string> {}; function test<T, B extends I<T>>(b: B): T { return null as any; // simply for ...

Exploring subobjects while fetching observables (typescript/angular)

When retrieving JSON from an API into an Angular service, I am working with a collection of objects structured like this: { "data": { "id": 1, "title": "one" }, "stats" : { "voteCount": 8 } } I am particularly interested in the ' ...

I'm unable to successfully include a download link for a PDF file stored locally

Looking to provide a download link for my resume on my website. Here's the code I'm using: <a href="My Resume.pdf" class='download' download="Resume PDF">Download CV</a> Despite using what I believe to ...

Switching the focus of detection from a child to a parent

I am currently working on enhancing the functionality of my UI to display selections dynamically as they are selected or de-selected. import { Wizard } from './report-common'; import { Router } from '@angular/router'; import { DataServ ...

What is the proper way to define a new property for an object within an npm package?

Snippet: import * as request from 'superagent'; request .get('https://***.execute-api.eu-west-1.amazonaws.com/dev/') .proxy(this.options.proxy) Error in TypeScript: Property 'proxy' is not found on type 'Super ...

Generating output from a callback function in TypeScript

When I execute a graphql query, the showUsers function is supposed to display all users (styled as boxes). However, at the moment, nothing is showing up. I am utilizing a functional component instead of a class component. This function is invoked after m ...

"Exploring the best practice: Defining types in React with Typescript before or after

As a newcomer to typescript, I have noticed that some projects declare the type before the component while others declare it after the component. Can someone explain the differences between these approaches? export type TProps = { item: string; } expor ...

Angular2 is throwing an error: "NavigationService provider not found! (MenuComponent -> NavigationService)"

I am in the process of developing an angular (beta7) application. I aim to have a MenuComponent at the top that utilizes the NavigationService to navigate throughout different sections of my app. To ensure that the NavigationService remains a singleton, I ...

Issue with Angular 8: Unable to access property 'database' of undefined when using @firebase

Recently, I decided to upgrade my configuration from angularfire2 v4 to @angular/fire v5.2.1 and firebase from v4 to v6.2.4. Unfortunately, during this process, I encountered an issue that caused the console to log the following error message: TypeError: ...

Type of JavaScript map object

While exploring TypeScript Corday, I came across the following declaration: books : { [isbn:string]:Book}={}; My interpretation is that this could be defining a map (or dictionary) data type that stores key-value pairs of an ISBN number and its correspon ...

Issues arise when attempting to include the src attribute within the template tag in a Vuejs and Laravel project

After starting a project with Vuejs and Laravel using Laravel Mix, I encountered an issue. When attempting to split my component into separate files and load them in the .vue file as follows: <template src="./comp.html"></template> &l ...

Unexpected JSON end causes issue with DELETE request in Next.js version 13

I am currently working on a web app using Next 13 and I have a route.ts file located in the api folder. This file contains two different methods, POST and DELETE. While both methods successfully receive the request, I am facing an issue with JSON parsing ...

Combining TypeScript with Vue3 to implement bootstrapVue

After using BootstrapVue as any, the error was corrected but unfortunately it still doesn't work in the browser. Here is what's inside main.ts: import { createApp }from 'vue'; import App from './App.vue'; import router from & ...

Tips for extracting information from Observable that is supplied with data from an external API

Beginner in the world of Reactive programming (and Angular). I’m eager to create my first data stream and receive something other than an error message in the console output :) Here is what I've attempted: export class AppComponent { requestS ...

Guide on setting up multiple Axios instances in NestJS

I'm in the process of migrating an existing Express application to NestJS. Currently, I have a configuration file where I define multiple axios instances for each microservice: export const writeModelApi = axios.create({ baseURL: getWriteModelApiUrl ...

Display the highlighted text within the input field

Is there a library available that can create an input field with a suggestions dropdown for Male and Female where typing "M" will highlight the letters "ale," allowing for autopopulation when clicked or tabbed? The same functionality should apply for typin ...