im building some .net core
api for my angular app
i want to use both - windows authentication
and jwt
for it and because request can have only ONE Authentication header - im passing my token in own 'CustomAuthorization' headher so windows auth can be present in default.
so i added
app.UseMiddleware<CheckCustomHeader>();
i builded my middleware
public class CheckCustomHeader
{
private readonly RequestDelegate _next;
public CheckCustomHeader(RequestDelegate next)
{
_next = next;
}
public async Task Invoke(HttpContext context)
{
if (context.Request.Method == HttpMethods.Post)
{
string token = context.Request.Headers["CustomAuthorization"];
try
{
string secret = "MySecreetKey";
var key = Encoding.ASCII.GetBytes(secret);
var handler = new JwtSecurityTokenHandler();
var validations = new TokenValidationParameters
{
ValidateIssuerSigningKey = true,
IssuerSigningKey = new SymmetricSecurityKey(key),
ValidateIssuer = false,
ValidateAudience = false
};
var claims = handler.ValidateToken(token, validations, out var tokenSecure);
var x = claims.Identity.Name;
//toDo - check if this token identityName = windows auth identity
}
catch (System.Exception)
{
context.Response.Clear();
context.Response.ContentType = "text/plain; charset=utf-8";
context.Response.StatusCode = StatusCodes.Status400BadRequest;
await context.Response.WriteAsync("Invalid User Key");
// return ? // should it be there? i tryied both cases ;)
}
}
await _next(context);
}
and it does work well - if key is ok then no problem
but when jwt key is not ok i want to catch exception and return this badrequest.
in postman
it is ok - it returns 400 and this message in body,
but from my angular app i get
Access to XMLHttpRequest at 'http://localhost:51500/SP/t/generateReport/' from origin
'http://localhost:4200' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is
present on the requested resource.
data.service.ts:43 unCatch DataService post error:0{"headers":{"normalizedNames":
{},"lazyUpdate":null,"headers":{}},"status":0,"statusText":"Unknown Error",url":"http://localhost:51500/SP/t/generateReport","ok":false,"name":"HttpErrorResponse","message":"Http failure response for http://localhost:51500/SP/t/generateReport/: 0 Unknown Error","error":{"isTrusted":true}}
zone-evergreen.js:2828 POST http://localhost:51500/SP/t/generateReport/ net::ERR_FAILED
so like any cors blocked request - why ? i have corse configured and woths well for all other requests... should i manualy add some cors headers for this owerwriten by me request ? or how should i return this error in middleware?
thanks and regards !
edit cors policy is added this way
string[] HostOrigins = new string[] { "http://localhost:4200", "https://localhost:4200"};
services.AddCors(options =>
{
options.AddPolicy("CorsPolicy", builder =>
{
builder.WithOrigins(a.CorsSettings.Origins)
.AllowAnyHeader().AllowAnyMethod().AllowCredentials();
});
});
and then
app.UseCors("CorsPolicy");