ASP.NET Core Web API 身份验证 [英] ASP.NET Core Web API Authentication

查看:55
本文介绍了ASP.NET Core Web API 身份验证的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I'm struggling with how to set up authentication in my web service. The service is build with the ASP.NET Core web api.

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

All my clients (WPF applications) should use the same credentials to call the web service operations.

经过一番研究,我想出了基本的身份验证 - 在 HTTP 请求的标头中发送用户名和密码.但经过数小时的研究,在我看来,在 ASP.NET Core 中基本身份验证并不是要走的路.

After some research, I came up with basic authentication - sending a username and password in the header of the HTTP request. But after hours of research, it seems to me that basic authentication is not the way to go in ASP.NET Core.

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

Most of the resources I found are implementing authentication using OAuth or some other middleware. But that seems to be oversized for my scenario, as well as using the Identity part of ASP.NET Core.

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

So what is the right way to achieve my goal - simple authentication with username and password in a ASP.NET Core web service?

提前致谢!

推荐答案

您可以实现一个处理基本身份验证的中间件.

You can implement a middleware which handles Basic authentication.

public async Task Invoke(HttpContext context)
{
    var authHeader = context.Request.Headers.Get("Authorization");
    if (authHeader != null && authHeader.StartsWith("basic", StringComparison.OrdinalIgnoreCase))
    {
        var token = authHeader.Substring("Basic ".Length).Trim();
        System.Console.WriteLine(token);
        var credentialstring = Encoding.UTF8.GetString(Convert.FromBase64String(token));
        var credentials = credentialstring.Split(':');
        if(credentials[0] == "admin" && credentials[1] == "admin")
        {
            var claims = new[] { new Claim("name", credentials[0]), new Claim(ClaimTypes.Role, "Admin") };
            var identity = new ClaimsIdentity(claims, "Basic");
            context.User = new ClaimsPrincipal(identity);
        }
    }
    else
    {
        context.Response.StatusCode = 401;
        context.Response.Headers.Set("WWW-Authenticate", "Basic realm="dotnetthoughts.net"");
    }
    await _next(context);
}

此代码是用 ASP.NET Core 的测试版编写的.希望有帮助.

This code is written in a beta version of asp.net core. Hope it helps.

这篇关于ASP.NET Core Web API 身份验证的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆