user3744961
user3744961

Reputation: 53

How can I use basic authentication in my application?

How can I use basic authentication in the ASP.NET Core API?

I have the below ASP.NET web API controller. How can I use the middleware for authentication or any other method to achieve the basic authentication in the 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;
        }
    }
}

Upvotes: 3

Views: 3489

Answers (1)

itminus
itminus

Reputation: 25360

You're almost there.

  1. if you want to use Basic Authentication globally, just add a UseMiddleware<YourBasicMiddleware>() before 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 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.

Upvotes: 8

Related Questions