im为我的角度应用程序构建一些.net core
API
我想同时使用-windows authentication
和jwt
,并且因为请求只能有一个Authentication头-我将令牌传递给自己的'CustomAuthorization'头,所以Windows auth可以默认存在。
所以我加了
app.UseMiddleware<CheckCustomHeader>();
我构建了中间件
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);
}
,并且效果很好-如果键正确,则没问题
但是当jwt键不正确时,我想捕获异常并返回此badrequest。
在postman
中可以,它会返回400,并且此消息在正文中,
但是从我的角度应用程序中我得到了
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
就像任何cors被阻止的请求一样-为什么? 我已经配置好了corse并且很适合其他所有请求... 我是否应该为此请求手动添加一些cors标头?还是应该在中间件中返回此错误?
感谢和问候!
编辑 这种方式添加了cors政策
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();
});
});
然后
app.UseCors("CorsPolicy");
答案 0 :(得分:0)
parse_pagination
是的,这是cors问题-在这种方法中,当“手动”生成响应时,不使用cors政策。 但是我对此不满意-有人知道如何通过这种“正确方法”吗? regatds
-----编辑------
非常简单-订购很重要! 拥有就足够了
context.Response.Clear();
context.Response.Headers.Add("Access-Control-Allow-Origin", "http://localhost:4200");
context.Response.Headers.Add("Access-Control-Allow-Methods", "POST");
context.Response.Headers.Add("Access-Control-Allow-Credentials", "true");
context.Response.ContentType = "text/plain; charset=utf-8";
context.Response.StatusCode = StatusCodes.Status400BadRequest;
await context.Response.WriteAsync("Invalid User Key");
之前
app.UseCors("CorsPolicy");
我有.....; /; P
答案 1 :(得分:0)
您可以尝试以下方法:
安装“ Microsoft.AspNet.WebApi.Cors”。 (只需在PM Console中运行以下命令即可。
Microsoft.AspNet.WebApi.Cors安装包
为此发布后,打开文件App_Start / WebApiConfig.cs。将以下代码添加到WebApiConfig.Register方法:
config.EnableCors();
您的示例文件将如下所示:
using System.Web.Http;
namespace WebService
{
public static class WebApiConfig
{
public static void Register(HttpConfiguration config)
{
// New code
config.EnableCors();
config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{id}",
defaults: new { id = RouteParameter.Optional }
);
}
}
}
接下来,将[EnableCors]属性与源,标头和方法一起添加到中间件所在的Controller中。要允许所有请求,请在标题和方法字段中使用“ *”。
示例:
using System.Net.Http;
using System.Web.Http;
using System.Web.Http.Cors;
namespace WebService.Controllers
{
[EnableCors(origins: "http://www.mywebsite.com", headers: "*", methods: "*")]
public class TestController : ApiController
{
// Controller methods not shown...
}
}
注意:可以在操作级别,控制器级别以及为您的应用程序全局添加。
要在全球范围内使用它,WebApiConfig将如下所示:
public static class WebApiConfig
{
public static void Register(HttpConfiguration config)
{
var cors = new EnableCorsAttribute("www.mywebsite.com", "*", "*");
config.EnableCors(cors);
// ...
}
}