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

查看:742
本文介绍了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);
}

此代码是用beta版本的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天全站免登陆