我有IIS托管的ASP.Net core 2 WebApi,受JWT授权保护。有什么方法可以允许本地主机未经授权访问API?即来自同一服务器上的nodejs应用的请求。
答案 0 :(得分:0)
您可以在JWT事件的OnMessageReceived
中验证本地主机请求,并为上下文设置Principal
并像这样调用context.Success()
:
public class Startup
{
...
public void ConfigureServices(IServiceCollection services)
{
// jwt auth.
services
.AddAuthentication(options =>
{
options.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
options.DefaultSignInScheme = JwtBearerDefaults.AuthenticationScheme;
options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
})
.AddJwtBearer(cfg =>
{
...
cfg.Events = new JwtBearerEvents
{
OnMessageReceived = context =>
{
var ip = context.Request.HttpContext.Connection.RemoteIpAddress.ToString();
if (ip == "127.0.0.1" || ip == "::1")
{
var claims = new[]
{
new Claim(
ClaimTypes.NameIdentifier,
"LocalHostUser",
ClaimValueTypes.String,
context.Options.ClaimsIssuer),
new Claim(
ClaimTypes.Name,
"LocalHostUser",
ClaimValueTypes.String,
context.Options.ClaimsIssuer)
};
context.Principal = new ClaimsPrincipal(
new ClaimsIdentity(claims, context.Scheme.Name));
context.Success();
}
return Task.CompletedTask;
},
};
});
}
}