Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ASP.NET Core Web API Authentication

I'm struggling with how to set up authentication in my web service. The service is build with the ASP.NET Core web api.

All my clients (WPF applications) should use the same credentials to call the web service operations.

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.

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.

So what is the right way to achieve my goal - simple authentication with username and password in a ASP.NET Core web service?

Thanks in advance!

like image 445
Felix Avatar asked Aug 16 '16 14:08

Felix


People also ask

How will you implement authentication and authorization in ASP.NET web API?

Web API assumes that authentication happens in the host. For web-hosting, the host is IIS, which uses HTTP modules for authentication. You can configure your project to use any of the authentication modules built in to IIS or ASP.NET, or write your own HTTP module to perform custom authentication.

How does NET Core handle authentication and authorization?

Authentication is the process of determining a user's identity. Authorization is the process of determining whether a user has access to a resource. In ASP.NET Core, authentication is handled by the authentication service, IAuthenticationService, which is used by authentication middleware.


1 Answers

Now, after I was pointed in the right direction, here's my complete solution:

This is the middleware class which is executed on every incoming request and checks if the request has the correct credentials. If no credentials are present or if they are wrong, the service responds with a 401 Unauthorized error immediately.

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

The middleware extension needs to be called in the Configure method of the service Startup class

public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory) {     loggerFactory.AddConsole(Configuration.GetSection("Logging"));     loggerFactory.AddDebug();      app.UseMiddleware<AuthenticationMiddleware>();      app.UseMvc(); } 

And that's all! :)

A very good resource for middleware in .Net Core and authentication can be found here: https://www.exceptionnotfound.net/writing-custom-middleware-in-asp-net-core-1-0/

like image 50
Felix Avatar answered Oct 12 '22 00:10

Felix