简体   繁体   English

如何在我的应用程序中使用基本身份验证?

[英]How can I use basic authentication in my application?

How can I use basic authentication in the ASP.NET Core API?如何在 ASP.NET Core API 中使用基本身份验证?

I have the below ASP.NET web API controller.我有以下 ASP.NET Web API 控制器。 How can I use the middleware for authentication or any other method to achieve the basic authentication in the ASP.NET Core 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)
        {
        }

    }
}

I have seen the below middleware.我已经看到了下面的中间件。 How can I use the middleware in the controller?如何在控制器中使用中间件?

Do I need to configure any additional setting?我需要配置任何其他设置吗?

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

You're almost there.您快到了。

  1. if you want to use Basic Authentication globally, just add a UseMiddleware<YourBasicMiddleware>() before UseMvc() .如果要全局使用基本身份验证,只需在UseMiddleware<YourBasicMiddleware>()之前添加UseMiddleware<YourBasicMiddleware>() UseMvc()
  2. I guess you want to use basic authentication middlware for some particular controller and action.我猜您想对某些特定的控制器和操作使用基本的身份验证中间件。 To do that,要做到这一点,

Just Add a class that has a public void Configure(IApplication) method:只需添加一个具有 public 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>();
    }
}

And now you can use the middleware to filter some action:现在你可以使用中间件来过滤一些动作:

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

Now when you send a request without the authentication header:现在,当您发送没有身份验证标头的请求时:

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

The response will be:响应将是:

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

And if you send the request with a basic authentication header,如果您发送带有基本身份验证标头的请求,

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

it will hit the correct action.它会击中正确的动作。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何在ASP.net Core应用程序中同时使用Bearer和Cookie身份验证? - How can I use both Bearer and Cookie authentication in my ASP.net Core application? 如何配置使用Connected Services创建的WSDL客户端以使用基本身份验证? - How can I configure a WSDL client created with Connected Services to use Basic Authentication? 如何使用WCF满足IIS基本身份验证 - How can I satisfy IIS Basic Authentication with WCF 如何从标头中检索基本身份验证凭据? - How can I retrieve Basic Authentication credentials from the header? 我可以在网站中使用基本身份验证,在 web Api 中使用令牌身份验证,这是错误的概念吗? - Can I use Basic authentication in website and Token authentication in web Api, Is this wrong concept? 如何在应用程序内部使用基本身份验证调用URL - How to call url with basic authentication inside application 如何在控制台应用程序中使用计时器? - How can I use a timer in my console application? 如何使用自带倾斜效果的应用栏? - How can I use my own application bar with tilt effec? 如何在 WinForms 应用程序中使用 Salesforce OAuth 2.0 隐式流身份验证? - How can I use Salesforce OAuth 2.0 implicit flow authentication in a WinForms application? 我可以在没有业务应用程序模板的情况下使用身份验证域服务吗? - Can I use Authentication Domain Service without Business Application Template?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM