ASP.NET Core Web API Authentication

后端 未结 9 758
深忆病人
深忆病人 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条回答
  •  一生所求
    2020-12-04 05:33

    I have implemented BasicAuthenticationHandler for basic authentication so you can use it with standart attributes Authorize and AllowAnonymous.

    public class BasicAuthenticationHandler : AuthenticationHandler
    {
        protected override Task HandleAuthenticateAsync()
        {
            var authHeader = (string)this.Request.Headers["Authorization"];
    
            if (!string.IsNullOrEmpty(authHeader) && authHeader.StartsWith("basic", StringComparison.OrdinalIgnoreCase))
            {
                //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(':', StringComparison.OrdinalIgnoreCase);
    
                var username = usernamePassword.Substring(0, seperatorIndex);
                var password = usernamePassword.Substring(seperatorIndex + 1);
    
                //you also can use this.Context.Authentication here
                if (username == "test" && password == "test")
                {
                    var user = new GenericPrincipal(new GenericIdentity("User"), null);
                    var ticket = new AuthenticationTicket(user, new AuthenticationProperties(), Options.AuthenticationScheme);
                    return Task.FromResult(AuthenticateResult.Success(ticket));
                }
                else
                {
                    return Task.FromResult(AuthenticateResult.Fail("No valid user."));
                }
            }
    
            this.Response.Headers["WWW-Authenticate"]= "Basic realm=\"yourawesomesite.net\"";
            return Task.FromResult(AuthenticateResult.Fail("No credentials."));
        }
    }
    
    public class BasicAuthenticationMiddleware : AuthenticationMiddleware
    {
        public BasicAuthenticationMiddleware(
           RequestDelegate next,
           IOptions options,
           ILoggerFactory loggerFactory,
           UrlEncoder encoder)
           : base(next, options, loggerFactory, encoder)
        {
        }
    
        protected override AuthenticationHandler CreateHandler()
        {
            return new BasicAuthenticationHandler();
        }
    }
    
    public class BasicAuthenticationOptions : AuthenticationOptions
    {
        public BasicAuthenticationOptions()
        {
            AuthenticationScheme = "Basic";
            AutomaticAuthenticate = true;
        }
    }
    

    Registration at Startup.cs - app.UseMiddleware();. With this code, you can restrict any controller with standart attribute Autorize:

    [Authorize(ActiveAuthenticationSchemes = "Basic")]
    [Route("api/[controller]")]
    public class ValuesController : Controller
    

    and use attribute AllowAnonymous if you apply authorize filter on application level.

提交回复
热议问题