Basic Authentication in ASP.NET Core

后端 未结 5 797
刺人心
刺人心 2020-12-14 13:45

Question

How can I implement Basic Authentication with Custom Membership in an ASP.NET Core web application?

Notes

5条回答
  •  天命终不由人
    2020-12-14 14:50

    Super-Simple Basic Authentication in .NET Core:

    1. Add this utility method:

    static System.Text.Encoding ISO_8859_1_ENCODING = System.Text.Encoding.GetEncoding("ISO-8859-1");
    public static (string, string) GetUsernameAndPasswordFromAuthorizeHeader(string authorizeHeader)
    {
        string encodedUsernamePassword = authorizeHeader.Substring("Basic ".Length).Trim();
        string usernamePassword = ISO_8859_1_ENCODING.GetString(Convert.FromBase64String(encodedUsernamePassword));
    
        string username = usernamePassword.Split(':')[0];
        string password = usernamePassword.Split(':')[1];
    
        return (username, password);
    }
    

    2. Update controller action to get username and password from Authorization header:

    public async Task Index([FromHeader]string Authorization)
    {
        (string username, string password) = GetUsernameAndPasswordFromAuthorizeHeader(Authorization);
    
        // Now use username and password with whatever authentication process you want 
    
        return View();
    }
    

    Example

    This example demonstrates using this with ASP.NET Core Identity.

    public class HomeController : Controller
    {
        private readonly UserManager _userManager;
    
        public HomeController(UserManager userManager)
        {
            _userManager = userManager;
        }
    
        [AllowAnonymous]
        public async Task MyApiEndpoint([FromHeader]string Authorization)
        {
            (string username, string password) = GetUsernameAndPasswordFromAuthorizeHeader(Authorization);
    
            IdentityUser user = await _userManager.FindByNameAsync(username);
            bool successfulAuthentication = await _userManager.CheckPasswordAsync(user, password);
    
            if (successfulAuthentication)
                return Ok();
            else
                return Unauthorized();
        }
    }
    

提交回复
热议问题