I have come across a situation where I make a call from my angular 7 application to my asp.net web api application. When I call an HTTP post method in angular to the application running on a different port it throws an exception.
Access to XMLHttpRequest at 'http://localhost/oauthservice/api/token' from origin 'http://localhost:4200' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.
My Angular application Running on 'http://localhost:4200' port number:4200 My asp.net web api application running on 'http://localhost/oauthservice/api/token': port number:80 Microsoft IIS .
if you have a time please help me.
sign-in.component.ts
OnSubmit(userName: any, password: any) {
this.userService.userAuthentication(userName, password).subscribe((data: any) => {
localStorage.setItem('userToken', JSON.stringify(data));
this.router.navigate(['/home']);
},
(err: HttpErrorResponse) => {
this.isLoginError = true;
});
}
user.service.ts
userAuthentication(userName, password) {
const data = 'grant_type=password&username=' + userName + '&password=' + password;
// let reqHeader = new HttpHeaders({ 'Content-Type': 'application/x-www-form-urlencoded', 'No-Auth': 'True' });
// tslint:disable-next-line:max-line-length
return this.http.post(this.apiUrl + 'token', data, { headers: {'Content-Type': 'application/x-www-form-urlencoded'}});
}
form server side
startup.cs
public void ConfigureOAuth(IAppBuilder app, HttpConfiguration config)
{
OAuthBearerOptions = new OAuthBearerAuthenticationOptions();
OAuthAuthorizationServerOptions oAuthServerOptions = new OAuthAuthorizationServerOptions()
{
TokenEndpointPath = new PathString("/api/token"),
AccessTokenExpireTimeSpan = TimeSpan.FromMinutes(30),
Provider = new AuthorizationServerProvider((IAccountsRepository)config.DependencyResolver.GetService(typeof(IAccountsRepository))),
RefreshTokenProvider = new RefreshTokenProvider(),
AllowInsecureHttp = true,
};
//Token Generation
app.UseOAuthAuthorizationServer(oAuthServerOptions);
app.UseOAuthBearerAuthentication(OAuthBearerOptions);
}
AuthorizationServerProvider.cs
public override async Task GrantResourceOwnerCredentials(OAuthGrantResourceOwnerCredentialsContext context)
{
var identity = new ClaimsIdentity(context.Options.AuthenticationType);
//Authenticate the user credentials
if (_accounts.Login(context.UserName, context.Password))
{
t_userDetail user = await _accounts.GetUserDetails(context.UserName);
identity.AddClaim(new Claim(ClaimTypes.Role, _accounts.GetUserRole(context.UserName)));
identity.AddClaim(new Claim("username", context.UserName));
identity.AddClaim(new Claim("fullName", user.firstName + " " + user.lastName));
identity.AddClaim(new Claim("Email", user.email));
identity.AddClaim(new Claim("Phone", user.phone));
identity.AddClaim(new Claim("role", _accounts.GetUserRole(context.UserName)));
identity.AddClaim(new Claim(ClaimTypes.Name, context.UserName));
identity.AddClaim(new Claim("LoggedOn",DateTime.Now.ToString()));
var props = new AuthenticationProperties(new Dictionary<string, string>
{
{
"as:client_id", context.ClientId ?? string.Empty
},
{
"userName", context.UserName
},
{
"fullName",user.firstName + " " + user.lastName
},
{
"Email", user.email
},
{
"role", _accounts.GetUserRole(context.UserName)
},
{
"Phone", user.phone
},
});
var ticket = new AuthenticationTicket(identity, props);
context.Validated(ticket);
}
else
{
context.SetError("invalid_grant", "Provided username or password is incorrect");
}
}