感谢您的建议,但我不想为每个现有控制器添加 [Authorize] 属性。
我只是为 IPAuthentication 添加了新方案:
.AddScheme<IPOnlyAuthenticationOptions, IPOnlyAuthenticationHandler>("IPOnly", op => { });
然后在AuthenticationHandler中:
public class IPOnlyAuthenticationOptions : AuthenticationSchemeOptions { }
public class IPOnlyAuthenticationHandler : AuthenticationHandler<IPOnlyAuthenticationOptions>
{
private readonly IEnumerable<IPAddress> validIPs= new[]
{
"xxx"
}.Select(o => IPAddress.Parse(o));
public IPOnlyAuthenticationHandler(IOptionsMonitor<IPOnlyAuthenticationOptions> options,
ILoggerFactory logger,
UrlEncoder encoder,
ISystemClock clock)
: base(options, logger, encoder, clock) { }
protected override Task<AuthenticateResult> HandleAuthenticateAsync()
{
var ipAddress = Request.HttpContext.Connection.RemoteIpAddress;
var identity = GetIdentityFromIPAddress(ipAddress);
if (identity != null)
{
var ticket = new AuthenticationTicket(new ClaimsPrincipal(identity), this.Scheme.Name);
return Task.FromResult(AuthenticateResult.Success(ticket));
}
return Task.FromResult(AuthenticateResult.Fail($"Request not authenticated for ip address: {ipAddress}"));
}
private ClaimsIdentity GetIdentityFromIPAddress(IPAddress ipAddress)
{
if (smsApiIPs.Contains(ipAddress))
{
var claims = new[] { new Claim(ClaimTypes.NameIdentifier, "id of my integration user") };
return new ClaimsIdentity(claims, nameof(IPOnlyAuthenticationHandler));
}
return null;
}
我终于可以在我的控制器中使用它了:
[HttpPost]
[Authorize(AuthenticationSchemes = "IPOnly")]
[Route("type/sms/changeStatus")]
public async Task<IActionResult> Foo(Bar model)