I try to communicate between dotnet webapi project and angular6 project.
Scenario: when I enter loginname and password and click login button, it should fetch access_token, username from server and display the result in displayresult.html. I Know this question is asked previously, but even after trying with all those solutions, I could not communicate my angular6 project with dotnetwebapi.
To fix CORS policy, I did some of the changes in my dotnetwebapi project.
Added
app.UseCors(Microsoft.Owin.Cors.CorsOptions.AllowAll);
inConfigureAuth(IAppBuilder app)
ofstartup.auth.cs
.In
web.config
, added custom headers, please see the code below.
authservice.ts
export class AuthService
{
private TokenAPI="http://localhost:51255/token";
login(username:string,password:string):Observable<TokenParams>
{
var headersfortokenapi = new Headers({'Content-Type':'application/x-www-form-encoded'});
var data="grant_type=password&username=" + username + "&password=" + password;
return this.objhttp.post(this.TokenAPI,data,{ headers:headersfortokenapi})
.pipe(
map(res=>res.json()
)
);
}
}
Login.component.ts
OnLoginClick()
{
this.objauthservice.login(this.username,this.password)
.subscribe
(
data=>
{
this.tokenparam=data;
this.objauthservice.AccessToken=this.tokenparam.access_token;
this.objroute.navigate(['/Displayproducts']);
}
)
}
When I click login button in login page, it goes to the above method and it calls authservice login method.
Now i have created TOKENWEBAPIPROJECT
dotnet project.
This project is running in http://localhost:51255/token
.
The code snippet where I did some changes in TOKENWEBAPIPROJECT
.
startup.cs
public void ConfigureAuth(IAppBuilder app)
{
//it has the default code for connecting to dbcontext and application
app.UseCors(Microsoft.Owin.Cors.CorsOptions.AllowAll);
}
web.config
<system.webServer>
<httpProtocol>
<customHeaders>
<add name="Access-Control-Allow-Origin" value="http://localhost:4200" />
<add name="Access-Control-Allow-Methods" value="GET, POST, PUT, DELETE, OPTIONS,token"/>
<add name="Access-Control-Allow-Headers" value="Origin, application/x-www-form-encoded, Content-Type, X-Auth-Token" />
</customHeaders>
</httpProtocol>
</system.webServer>
I tested the post request of http://localhost:51255/token
in Postman.
Here I send username, password, grant_type=password and it returns me correct access_token, username, token_type etc.
Expected: when I enter loginname and password and click login button, it should fetch access_token, username from server and display the result in displayresult.html
.
Actual: Instead I am getting the following Errors:-
1. OPTIONS http://localhost:51255/token 400 (Bad Request)
Access to XMLHttpRequest at 'http://localhost:51255/token' from origin 'http://localhost:4200' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: It does not have HTTP ok status.