Angular 8 call web api to login token based with owin

Angular 8 call web api to login token based with owin
0

I’m at the beginning with angular and I have a problem with the call to authenticate my web api. My web api use Owin and I’ve already used it with an old asp site. I call whith ajax without problems:

$.ajax({
				url: _TokenApi, 
				type: 'POST',
				dataType: 'json',
				contentType: 'application/x-www-form-urlencoded; charset=UTF-8',
				headers: {
					"Content-Type":"application/x-www-form-urlencoded",
					"Authorization": _CLIENTAUTH
				},
				/* data: JSON.stringify(body), /* wrong */
				data: body, /* right */
				complete: function(result) {

				},

				success: function(result) {
					sessionStorage.setItem(_GLOBALPREFIX+'xms_token',result.access_token);
					xms_Login_ok(dataLogin);
				},

				error: function(result) {
					 xms_alert('warning', 'Attenzione', 'Token non recuperato correttamente');
				},
			});	
			
		}

I want to make the same call with angular,I found an example done this way

UserAuthenticationOriginal(UserName: string,Password: string):Observable{
let credentials='username=' +UserName + '&password=' +Password +'&grant_type=password';
var reqHeader = new HttpHeaders({'Content-Type': 'application/x-www-urlencoded','No-Auth':'True' });
return this.http.post(this.ApiUrl+'token',encodeURI(credentials),{headers:reqHeader});
}

this function arrives at the web api, but obviously it doesn’t authenticate because I called with: ‘No-Auth’: ‘True’

I tried to replace with

headers.set('Content-Type', 'application/x-www-form-urlencoded');
headers.set("Authorization", 'BASIC XXXXXXX'); let credentials='username=' +UserName + '&password=' +Password +'&grant_type=password'; 
let a= this.http.post(this.ApiUrl+'token',encodeURI(credentials),{headers:headers});

But I have a Error: ERROR TypeError: “this.api.UserAuthentication(…) is undefined”

and does not make any calls to the web api

The problem not is in angular call but in web api.
I add in Startup.cs this:
app.UseCors(Microsoft.Owin.Cors.CorsOptions.AllowAll);

and remove in WebApiConfig.cs this:

var corsAttr = new EnableCorsAttribute("", "", “*”);
config.EnableCors(corsAttr);

Did that solve it?

And thank you posting the answer, someone in 6 months will find this on Google and thank you too :slight_smile: