I am developing a web API app running using asp.net core2 and Angular. The detailed development environment config is here.
I am trying to
thanks, @Chris_Pratt for pointing out the header issue that I had. However, in order to make it clear I had other issues which will address below.
I had my CORS misconfigured, my working code is the following,
services.AddCors(options =>
{
options.AddPolicy("CorsPolicy",
builder => builder
.WithOrigins("https://www.artngcore.com:4200") //Note: The URL must be specified without a trailing slash (/).
.AllowAnyMethod()
.AllowAnyHeader()
.AllowCredentials());
});
services.AddAntiforgery(options =>
{
options.HeaderName = "X-XSRF-TOKEN";
options.SuppressXFrameOptionsHeader = false;
});
and the middleware configuration is,
app.Use(next => context =>
{
string path = context.Request.Path.Value;
var tokens = antiforgery.GetAndStoreTokens(context);
context.Response.Cookies.Append("XSRF-TOKEN", tokens.RequestToken,
new CookieOptions() { HttpOnly = false,
Secure = true // set false if not using SSL });
return next(context);
});
and in the controller,
[Route("/api/[controller]/[action]")]
[EnableCors("CorsPolicy")]
public class AccountController : ArtCoreSecuredController ....
what does the trick here is that the token has to refresh after authentication. calling an API just after authentication (login) will do it. don't forget to add the following header to your request,
const headers = new HttpHeaders({
'Content-Type': 'application/json',
'Authorization': `Bearer ${this.cookieService.get('ArtCoreToken')}`,
'X-XSRF-TOKEN': `${this.cookieService.get('XSRF-TOKEN')}`
});
i.e,
[HttpGet]
[AllowAnonymous]
public async Task RefreshToken()
{
await Task.Delay(1);
return StatusCode(200);
}
this is what worked for me. hope it helps.