ASP.NET Core Web API Authentication

后端 未结 9 761
深忆病人
深忆病人 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:31

    You can implement a middleware which handles Basic authentication.

    public async Task Invoke(HttpContext context)
    {
        var authHeader = context.Request.Headers.Get("Authorization");
        if (authHeader != null && authHeader.StartsWith("basic", StringComparison.OrdinalIgnoreCase))
        {
            var token = authHeader.Substring("Basic ".Length).Trim();
            System.Console.WriteLine(token);
            var credentialstring = Encoding.UTF8.GetString(Convert.FromBase64String(token));
            var credentials = credentialstring.Split(':');
            if(credentials[0] == "admin" && credentials[1] == "admin")
            {
                var claims = new[] { new Claim("name", credentials[0]), new Claim(ClaimTypes.Role, "Admin") };
                var identity = new ClaimsIdentity(claims, "Basic");
                context.User = new ClaimsPrincipal(identity);
            }
        }
        else
        {
            context.Response.StatusCode = 401;
            context.Response.Headers.Set("WWW-Authenticate", "Basic realm=\"dotnetthoughts.net\"");
        }
        await _next(context);
    }
    

    This code is written in a beta version of asp.net core. Hope it helps.

提交回复
热议问题