gpt4 book ai didi

c# - ASP.NET Core Web API 身份验证

转载 作者:IT王子 更新时间:2023-10-29 03:42:20 31 4
gpt4 key购买 nike

我正在为如何在我的网络服务中设置身份验证而苦恼。该服务是使用 ASP.NET Core Web API 构建的。

我的所有客户端(WPF 应用程序)都应该使用相同的凭据来调用 Web 服务操作。

经过一些研究,我想到了基本身份验证——在 HTTP 请求的 header 中发送用户名和密码。但经过数小时的研究,在我看来,基本身份验证并不是在 ASP.NET Core 中采用的方式。

我发现的大多数资源都使用 OAuth 或其他一些中间件实现身份验证。但这对于我的场景以及使用 ASP.NET Core 的身份部分来说似乎太大了。

那么实现我的目标的正确方法是什么 - 在 ASP.NET Core Web 服务中使用用户名和密码进行简单例份验证?

提前致谢!

最佳答案

现在,在我指出正确的方向之后,这是我的完整解决方案:

这是在每个传入请求上执行并检查请求是否具有正确凭据的中间件类。如果不存在凭据或凭据错误,服务会立即响应 401 Unauthorized 错误。

public class AuthenticationMiddleware
{
private readonly RequestDelegate _next;

public AuthenticationMiddleware(RequestDelegate next)
{
_next = next;
}

public async Task Invoke(HttpContext context)
{
string authHeader = context.Request.Headers["Authorization"];
if (authHeader != null && authHeader.StartsWith("Basic"))
{
//Extract credentials
string encodedUsernamePassword = authHeader.Substring("Basic ".Length).Trim();
Encoding encoding = Encoding.GetEncoding("iso-8859-1");
string usernamePassword = encoding.GetString(Convert.FromBase64String(encodedUsernamePassword));

int seperatorIndex = usernamePassword.IndexOf(':');

var username = usernamePassword.Substring(0, seperatorIndex);
var password = usernamePassword.Substring(seperatorIndex + 1);

if(username == "test" && password == "test" )
{
await _next.Invoke(context);
}
else
{
context.Response.StatusCode = 401; //Unauthorized
return;
}
}
else
{
// no authorization header
context.Response.StatusCode = 401; //Unauthorized
return;
}
}
}

中间件扩展需要在服务启动类的Configure方法中调用

public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
{
loggerFactory.AddConsole(Configuration.GetSection("Logging"));
loggerFactory.AddDebug();

app.UseMiddleware<AuthenticationMiddleware>();

app.UseMvc();
}

仅此而已! :)

可以在此处找到 .Net Core 中的中间件和身份验证的非常好的资源: https://www.exceptionnotfound.net/writing-custom-middleware-in-asp-net-core-1-0/

关于c# - ASP.NET Core Web API 身份验证,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38977088/

31 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com