Warning: file_get_contents(/data/phpspider/zhask/data//catemap/0/asp.net-core/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# ASP.Net核心Web API和持久基本身份验证_C#_Asp.net Core_.net Core_Basic Authentication - Fatal编程技术网

C# ASP.Net核心Web API和持久基本身份验证

C# ASP.Net核心Web API和持久基本身份验证,c#,asp.net-core,.net-core,basic-authentication,C#,Asp.net Core,.net Core,Basic Authentication,我正在开发一些Web API,对于身份验证,我使用基本身份验证来实现安全性,并实现了一个名为BasicAuthenticationHandler的类,该类继承自AuthenticationHandler,如下所示: namespace WebApi.Helpers { public class BasicAuthenticationHandler : AuthenticationHandler<AuthenticationSchemeOptions> {

我正在开发一些Web API,对于身份验证,我使用基本身份验证来实现安全性,并实现了一个名为
BasicAuthenticationHandler
的类,该类继承自
AuthenticationHandler
,如下所示:

namespace WebApi.Helpers
{
    public class BasicAuthenticationHandler : AuthenticationHandler<AuthenticationSchemeOptions>
    {
        private readonly IUserService _userService;

        public BasicAuthenticationHandler(
            IOptionsMonitor<AuthenticationSchemeOptions> options,
            ILoggerFactory logger,
            UrlEncoder encoder,
            ISystemClock clock,
            IUserService userService)
            : base(options, logger, encoder, clock)
        {
            _userService = userService;
        }

        protected override async Task<AuthenticateResult> HandleAuthenticateAsync()
        {
            if (!Request.Headers.ContainsKey("Authorization"))
                return AuthenticateResult.Fail("Missing Authorization Header");

            User user = null;
            try 
            {
                var authHeader = AuthenticationHeaderValue.Parse(Request.Headers["Authorization"]);
                var credentialBytes = Convert.FromBase64String(authHeader.Parameter);
                var credentials = Encoding.UTF8.GetString(credentialBytes).Split(':');
                var username = credentials[0];
                var password = credentials[1];
                user = await _userService.Authenticate(username, password);
            } 
            catch 
            {
                return AuthenticateResult.Fail("Invalid Authorization Header");
            }

            if (user == null)
                return AuthenticateResult.Fail("Invalid Username or Password");

            var claims = new[] { 
                new Claim(ClaimTypes.NameIdentifier, user.Id.ToString()),
                new Claim(ClaimTypes.Name, user.Username),
            };
            var identity = new ClaimsIdentity(claims, Scheme.Name);
            var principal = new ClaimsPrincipal(identity);
            var ticket = new AuthenticationTicket(principal, Scheme.Name);

            return AuthenticateResult.Success(ticket);
        }
    }
}
名称空间WebApi.Helpers
{
公共类BasicAuthenticationHandler:AuthenticationHandler
{
专用只读IUserService\u userService;
公共基本身份验证处理程序(
IOPTIONS监视器选项,
iLogger工厂记录器,
URL编码器,
ISystemClock时钟,
IUserService(用户服务)
:基本(选项、记录器、编码器、时钟)
{
_userService=userService;
}
受保护的重写异步任务handleAuthenticateAync()
{
if(!Request.Headers.ContainsKey(“授权”))
返回AuthenticateResult.Fail(“缺少授权标头”);
User=null;
尝试
{
var authHeader=AuthenticationHeaderValue.Parse(Request.Headers[“Authorization”]);
var credentialBytes=Convert.FromBase64String(authHeader.Parameter);
var credentials=Encoding.UTF8.GetString(credentialBytes).Split(':');
var username=凭证[0];
var password=凭证[1];
user=wait\u userService.Authenticate(用户名、密码);
} 
抓住
{
返回AuthenticateResult.Fail(“无效授权头”);
}
if(user==null)
返回AuthenticateResult.Fail(“无效的用户名或密码”);
var索赔=新[]{
新声明(ClaimTypes.NameIdentifier,user.Id.ToString()),
新索赔(ClaimTypes.Name、user.Username),
};
var标识=新的索赔实体(索赔、方案、名称);
var principal=新的ClaimsPrincipal(身份);
var票证=新的身份验证票证(主体,Scheme.Name);
返回AuthenticateResult.Success(票证);
}
}
}
代码运行良好,没有任何问题。我唯一的问题是在第一次请求之后,我调用了
user=wait\u userService.Authenticate(用户名、密码)
并检查数据库以查看用户名和密码是否有效。在第一次身份验证之后的web开发中,我们在cookie中保留了一个令牌,所以我们不需要再次检查数据库。我想做类似的事情来删除对Authenticate函数的调用,因此我需要知道开发具有持久身份验证的Web API的正确方法和最佳实践


作为测试,我还尝试将令牌保存在会话中,供经过身份验证的用户使用。但它似乎是
Context.Session.SetString(“SystemToken”,token)BasicAuthenticationHandler

内调用时,code>不保存令牌。您不希望在API中使用cookie或会话。您还希望在令牌中包含到期日,否则在数据库中被禁用或从数据库中删除的用户可以继续使用您的API。API客户端通常使用作为请求头发送的令牌进行身份验证。他们登录以获取令牌,并在每次后续请求中发送该令牌。@CodeMaster,但我的客户要求我使用基本身份验证,因此我没有使用令牌的选项。每个请求都应在Web API上进行身份验证,不要使会话保持活动状态。