如何在我的应用程序中使用基本身份验证? [英] How to use basic authentication in my application?
问题描述
如何在asp.net核心api中使用基本身份验证?我下面有asp.net Web API控制器.如何使用中间件进行身份验证或任何其他方法 在asp.net核心网络api中实现基本身份验证.
How to use basic authentication in asp.net core api? I have below asp.net web api controller. how to use the middleware for authentication or any other method to achieve the basic authentication in 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 below middleware. How to 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;
}
}
}
推荐答案
您快到了.
- 如果要全局使用基本身份验证,只需在
UseMvc()
之前添加UseMiddleware<YourBasicMiddleware>()
即可. - 我猜您想对某些特定的控制器和操作使用基本身份验证中间件.为此,
- if you want to use Basic Authentication globally , just add a
UseMiddleware<YourBasicMiddleware>()
beforeUseMvc()
. - I guess you want to use basic authentication middlware for some particular controller and action . To do that ,
只需添加一个具有公共void Configure(IApplication)
方法的类:
Just Add a class that has a public void Configure(IApplication)
method :
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 authencation header :
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
并且如果您发送带有基本身份验证标头的请求,
and if you send the request with a basic authentication header ,
GET https://localhost:44371/api/TestApi HTTP/1.1
Authorization: Basic dGVzdDp0ZXN0
它将执行正确的操作.
这篇关于如何在我的应用程序中使用基本身份验证?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!