ASP.NET Core Web API Authentication

后端 未结 9 750
深忆病人
深忆病人 2020-12-04 04:58

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 us

相关标签:
9条回答
  • 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/

    0 讨论(0)
  • 2020-12-04 05:41

    In this public Github repo https://github.com/boskjoett/BasicAuthWebApi you can see a simple example of a ASP.NET Core 2.2 web API with endpoints protected by Basic Authentication.

    0 讨论(0)
  • 2020-12-04 05:47

    To use this only for specific controllers for example use this:

    app.UseWhen(x => (x.Request.Path.StartsWithSegments("/api", StringComparison.OrdinalIgnoreCase)), 
                builder =>
                {
                    builder.UseMiddleware<AuthenticationMiddleware>();
                });
    
    0 讨论(0)
提交回复
热议问题