using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.Mvc.Filters; using System; using System.Linq; using System.Text; namespace WebApi.Attributes { /// <summary> /// Handles basic authentication on a Controller class/method /// </summary> public class BasicAuthenticationAttribute : ActionFilterAttribute { public void ReturnAuthorize(ActionExecutingContext context) { context.HttpContext.Response.Headers.Add("WWW-Authenticate", ""); context.Result = new UnauthorizedResult(); } public override void OnActionExecuting(ActionExecutingContext context) { var request = context?.HttpContext?.Request; if (request == null || !request.Headers.TryGetValue("Authorization", out var values)) { ReturnAuthorize(context); return; } var authHeaderParts = (values.FirstOrDefault() ?? "").Split(' '); if (authHeaderParts.Length != 2) { ReturnAuthorize(context); return; } var authType = authHeaderParts[0]; if (!"Basic".Equals(authType, StringComparison.OrdinalIgnoreCase)) { ReturnAuthorize(context); return; } var authValues = Encoding.UTF8.GetString(Convert.FromBase64String(authHeaderParts[1])).Split(':'); if (authValues.Length != 2) { ReturnAuthorize(context); return; } var username = authValues[0] ?? ""; var password = authValues[1] ?? ""; if (string.IsNullOrEmpty(username) || string.IsNullOrEmpty(password)) { ReturnAuthorize(context); return; } Console.WriteLine($"User: {username} logged in"); base.OnActionExecuting(context); } } }
204200cookie-checkC# WebAPI Basic Authentication