在 ASP.NET Core-6 Web API 中,此基本身份驗證代碼將用作我的 POST、PUT 和 Get 請求的標頭:
--header '授權:基本 GGATEIIIFFFF12234JJKKKKKFFFFFFFFFFFFFF'
在我的appsettings.Json中,我擁有如下所示的憑據:
"BasicCredentials": {
"username": "Akwetey",
"password": "#12345677**87" //Basic Auth
},
然后我有這個獲取請求:
public IEnumerable<Employee> GetEmployees()
{
List<Employee> employeelist = new List<Employee>();
using (con = new SqlConnection(connection))
{
con.Open();
command = new SqlCommand("sp_employees", con);
command.CommandType = CommandType.StoredProcedure;
dataReader = command.ExecuteReader();
while (dataReader.Read())
{
Employee employee = new Employee();
employee.EmployeeId = Convert.ToInt32(dataReader["EmployeeId"]);
employee.Firstname = dataReader["Firstname"].ToString();
employee.Lastname = dataReader["Lastname"].ToString();
employee.Email = dataReader["Email"].ToString();
employee.EmploymentDate = Convert.ToDateTime(dataReader["EmploymentDate"].ToString());
employeelist.Add(employee);
}
con.Close();
}
return employeelist;
}
如何使用 Basic Auth Credentials 作為標頭來授權上面的 Get Get Request 代碼?
謝謝
uj5u.com熱心網友回復:
您需要在這些方面添加一些內容
builder.Services.AddAuthentication()
.AddScheme<MyAuthenticationOptions, MyAuthenticationHandler>(MyAuthenticationSchemeName, options => {});
在哪里:
public class MyAuthenticationOptions : AuthenticationSchemeOptions
{}
和
public class MyAuthenticationHandler : AuthenticationHandler<MyAuthenticationOptions>
{
private IConfiguration Configuration;
public MyAuthenticationHandler(
IOptionsMonitor<MyAuthenticationOptions> options,
ILoggerFactory logger,
UrlEncoder encoder,
ISystemClock clock,
IConfiguration configuration
) : base(options, logger, encoder, clock)
{
Configuration = configuration;
}
protected async override Task<AuthenticateResult> HandleAuthenticateAsync()
{
// Get the header
string authHeader = Request.Headers[HeaderNames.Authorization];
// Parse config this way
var pwd = Configuration.GetValue<string>("BasicCredentials:password")
// Check if the header is valid comparing to your config
// Create here your claims principal
ClaimsPrincipal principal;
//...//
var ticket = new AuthenticationTicket(principal, Scheme.Name);
return AuthenticateResult.Success(ticket);
// Or otherwise
return AuthenticateResult.Fail("Invalid secret.");
}
}
最后,您可以擁有這樣的經過身份驗證的控制器
[Authorize]
[HttpGet("employees")]
public IEnumerable<Employee> GetEmployees()
{
List<Employee> employeelist = new List<Employee>();
using (con = new SqlConnection(connection))
{
con.Open();
command = new SqlCommand("sp_employees", con);
command.CommandType = CommandType.StoredProcedure;
dataReader = command.ExecuteReader();
while (dataReader.Read())
{
Employee employee = new Employee();
employee.EmployeeId = Convert.ToInt32(dataReader["EmployeeId"]);
employee.Firstname = dataReader["Firstname"].ToString();
employee.Lastname = dataReader["Lastname"].ToString();
employee.Email = dataReader["Email"].ToString();
employee.EmploymentDate = Convert.ToDateTime(dataReader["EmploymentDate"].ToString());
employeelist.Add(employee);
}
con.Close();
}
return employeelist;
}
uj5u.com熱心網友回復:
這是dotnetthoughtsBasicAuthenticationHandler的實作,修改為使用以下方式讀取憑據:appsettings.jsonIConfiguration
public class BasicAuthenticationHandler : AuthenticationHandler<AuthenticationSchemeOptions>
{
private readonly IConfiguration _configuration;
public BasicAuthenticationHandler(
IOptionsMonitor<AuthenticationSchemeOptions> options,
ILoggerFactory logger,
UrlEncoder encoder,
ISystemClock clock,
IConfiguration configuration) : base(options, logger, encoder, clock)
{
_configuration = configuration;
}
protected override Task<AuthenticateResult> HandleAuthenticateAsync()
{
var authHeader = Request.Headers["Authorization"].ToString();
if (authHeader != null && authHeader.StartsWith("basic", StringComparison.OrdinalIgnoreCase))
{
var token = authHeader.Substring("Basic ".Length).Trim();
Console.WriteLine(token);
var credentialstring = Encoding.UTF8.GetString(Convert.FromBase64String(token));
var credentials = credentialstring.Split(':');
var username = _configuration["BasicCredentials:username"];
var password = _configuration["BasicCredentials:password"];
if (credentials[0] == username && credentials[1] == password)
{
var claims = new[] { new Claim("name", credentials[0]), new Claim(ClaimTypes.Role, "Admin") };
var identity = new ClaimsIdentity(claims, "Basic");
var claimsPrincipal = new ClaimsPrincipal(identity);
return Task.FromResult(AuthenticateResult.Success(new AuthenticationTicket(claimsPrincipal, Scheme.Name)));
}
Response.StatusCode = 401;
Response.Headers.Add("WWW-Authenticate", "Basic realm=\"dotnetthoughts.net\"");
return Task.FromResult(AuthenticateResult.Fail("Invalid Authorization Header"));
}
else
{
Response.StatusCode = 401;
Response.Headers.Add("WWW-Authenticate", "Basic realm=\"dotnetthoughts.net\"");
return Task.FromResult(AuthenticateResult.Fail("Invalid Authorization Header"));
}
}
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/512595.html
