You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
68 lines
2.6 KiB
68 lines
2.6 KiB
using System;
|
|
using System.Net.Http.Headers;
|
|
using System.Security.Claims;
|
|
using System.Text;
|
|
using System.Text.Encodings.Web;
|
|
using System.Threading.Tasks;
|
|
using Microsoft.AspNetCore.Authentication;
|
|
using Microsoft.Extensions.Logging;
|
|
using Microsoft.Extensions.Options;
|
|
|
|
namespace Win_in.Sfs.Scp.WebApi.XmlHost
|
|
{
|
|
public class BasicAuthenticationHandler : AuthenticationHandler<AuthenticationSchemeOptions>
|
|
{
|
|
private readonly BasicAuthenticationOptions _basicOptions;
|
|
|
|
public BasicAuthenticationHandler(
|
|
IOptions<BasicAuthenticationOptions> basicOptions,
|
|
IOptionsMonitor<AuthenticationSchemeOptions> options,
|
|
ILoggerFactory logger,
|
|
UrlEncoder encoder,
|
|
ISystemClock clock)
|
|
: base(options, logger, encoder, clock)
|
|
{
|
|
_basicOptions = basicOptions.Value;
|
|
}
|
|
|
|
protected override async Task<AuthenticateResult> HandleAuthenticateAsync()
|
|
{
|
|
if (!Request.Headers.ContainsKey("Authorization"))
|
|
{
|
|
Response.Headers.Add("WWW-Authenticate", @"Basic realm='Secure Area'");
|
|
return AuthenticateResult.Fail("Missing Authorization Header");
|
|
}
|
|
BasicUser basicUser = null;
|
|
try
|
|
{
|
|
var authHeader = AuthenticationHeaderValue.Parse(Request.Headers["Authorization"]);
|
|
var credentialBytes = Convert.FromBase64String(authHeader.Parameter);
|
|
var credentials = Encoding.UTF8.GetString(credentialBytes).Split(new[] { ':' }, 2);
|
|
var username = credentials[0];
|
|
var password = credentials[1];
|
|
if (username.Equals(_basicOptions.Username) && password.Equals(_basicOptions.Password))
|
|
{
|
|
basicUser = new BasicUser { Id = 1, Username = "admin"};
|
|
}
|
|
}
|
|
catch
|
|
{
|
|
// Base64×Ö·û´®½âÂëʧ°Ü
|
|
return AuthenticateResult.Fail("Invalid Authorization Header");
|
|
}
|
|
|
|
if (basicUser == null)
|
|
return AuthenticateResult.Fail("Invalid Username or Password");
|
|
|
|
var claims = new[] {
|
|
new Claim(ClaimTypes.NameIdentifier, basicUser.Id.ToString()),
|
|
new Claim(ClaimTypes.Name, basicUser.Username),
|
|
};
|
|
var identity = new ClaimsIdentity(claims, Scheme.Name);
|
|
var principal = new ClaimsPrincipal(identity);
|
|
var ticket = new AuthenticationTicket(principal, Scheme.Name);
|
|
|
|
return AuthenticateResult.Success(ticket);
|
|
}
|
|
}
|
|
}
|