【问题标题】:How can I use basic authentication in my application?如何在我的应用程序中使用基本身份验证?
【发布时间】:2019-01-29 11:11:52
【问题描述】:

如何在 ASP.NET Core API 中使用基本身份验证?

我有以下 ASP.NET Web API 控制器。如何使用中间件进行身份验证或任何其他方法来实现 ASP.NET Core Web API 中的基本身份验证?

namespace Test.Web.Controllers
{
    [Route("api/[controller]")]
    public class TestAPIController : Controller
    {
        // GET: api/<controller>
        [HttpGet]
        public IEnumerable<string> Get()
        {
            return new string[] { "value1", "value2" };
        }

        // GET api/<controller>/5
        [HttpGet("{id}")]
        public string Get(int id)
        {
            return "value";
        }

        // POST api/<controller>
        [HttpPost]
        public void Post([FromBody]string value)
        {
        }

        // PUT api/<controller>/5
        [HttpPut("{id}")]
        public void Put(int id, [FromBody]string value)
        {
        }

        // DELETE api/<controller>/5
        [HttpDelete("{id}")]
        public void De`enter code here`lete(int id)
        {
        }

    }
}

我看过下面的中间件。如何在控制器中使用中间件?

我需要配置任何其他设置吗?

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;
        }
    }
}

【问题讨论】:

  • 你注册你的中间件了吗?另外,为什么不做一个 IAuthenticationFilter 呢?
  • 您最好使用内置授权系统和this。像这样编写自己的安全相关代码几乎总是一个坏主意 - 把它留给专家。

标签: c# authentication asp.net-core asp.net-core-webapi


【解决方案1】:

你快到了。

  1. 如果您想全局使用基本身份验证,只需在UseMvc() 之前添加一个UseMiddleware&lt;YourBasicMiddleware&gt;()
  2. 我猜您想为某些特定的控制器和操作使用基本身份验证中间件。为此,

只需添加一个具有公共void Configure(IApplication) 方法的类:

public class BasicFilter
{
    public void Configure(IApplicationBuilder appBuilder) {
        // Note the AuthencitaionMiddleware here is your Basic Authentication Middleware,
        // not the middleware from the Microsoft.AspNetCore.Authentication;
        appBuilder.UseMiddleware<AuthenticationMiddleware>();
    }
}

现在你可以使用中间件来过滤一些动作:

[Route("api/[controller]")]
[MiddlewareFilter(typeof(BasicFilter))]
[ApiController]
public class TestApiController : ControllerBase
{
    // ...
}

现在,当您发送没有身份验证标头的请求时:

GET https://localhost:44371/api/TestApi HTTP/1.1

响应将是:

HTTP/1.1 401 Unauthorized
Server: Kestrel
X-SourceFiles: =?UTF-8?B?RDpccmVwb3J0XDgtMjNcU08uQmFzaWNBdXRoTWlkZGxld2FyZVxXZWJBcHBcV2ViQXBwXGFwaVxUZXN0QXBp?=
X-Powered-By: ASP.NET
Date: Thu, 23 Aug 2018 09:49:24 GMT
Content-Length: 0

如果您发送带有基本身份验证标头的请求,

GET https://localhost:44371/api/TestApi HTTP/1.1
Authorization: Basic dGVzdDp0ZXN0

它会采取正确的行动。

【讨论】:

    猜你喜欢
    • 2011-11-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-01-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多