Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/305.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核心中的自定义身份验证和更新声明_C#_Asp.net_Asp.net Core - Fatal编程技术网

C# ASP.NET核心中的自定义身份验证和更新声明

C# ASP.NET核心中的自定义身份验证和更新声明,c#,asp.net,asp.net-core,C#,Asp.net,Asp.net Core,我正在用ASP.NET核心开发一个网站,该网站使用声明进行用户身份验证和用户Id以及声明中保留的其他信息,是否安全 ClaimsIdentity identity = new ClaimsIdentity( new[] { new Claim(ClaimTypes.Name, userInfo.Name), new Claim(ClaimTypes.Su

我正在用ASP.NET核心开发一个网站,该网站使用声明进行用户身份验证和用户Id以及声明中保留的其他信息,是否安全

ClaimsIdentity identity = new ClaimsIdentity(
                new[]
                {
                    new Claim(ClaimTypes.Name, userInfo.Name),
                    new Claim(ClaimTypes.Surname, userInfo.Surname),
                    new Claim("Image", userInfo.Image),
                    new Claim(ClaimTypes.NameIdentifier,result.Id.ToString()),
                    new Claim(ClaimTypes.IsPersistent, loginViewModel.RememberMe.ToString())
                },
                CookieName.User);
            HttpContext.SignOutAsync(CookieName.User).Wait();
            HttpContext.SignInAsync(CookieName.User, new ClaimsPrincipal(identity),
                new AuthenticationProperties
                {
                    IsPersistent = loginViewModel.RememberMe,
                    AllowRefresh = true
                }).Wait();
有时我需要更改用户信息,它会使用它。这条路安全吗

//Get 
int id = int.Parse(new ClaimsCookie(HttpContext).GetValue(CookieName.User, KeyName.Id));

//Set Update
new ClaimsCookie(HttpContext).SetValue(CookieName.User, new[] { KeyName.Name, KeyName.Surname }, new[] { model.Name, model.Surname });
类别:

namespace ...
{
    public class ClaimsCookie
    {
        private readonly HttpContext _httpContext;
        public ClaimsCookie(HttpContext httpContext)
        {
            _httpContext = httpContext;
        }

        public string GetValue(string cookieName, string keyName)
        {
            var principal = _httpContext.User;
            var cp = principal.Identities.First(i => i.AuthenticationType == cookieName.ToString());
            return cp.FindFirst(keyName).Value;
        }
        public async void SetValue(string cookieName, string[] keyName, string[] value)
        {
            if (keyName.Length != value.Length)
            {
                return;
            }
            if (_httpContext == null)
                return;
            var principal = _httpContext.User;
            var cp = principal.Identities.First(i => i.AuthenticationType == cookieName.ToString());
            for (int i = 0; i < keyName.Length; i++)
            {
                if (cp.FindFirst(keyName[i]) != null)
                {
                    cp.RemoveClaim(cp.FindFirst(keyName[i]));
                    cp.AddClaim(new Claim(keyName[i], value[i]));
                }

            }
            await _httpContext.SignOutAsync(cookieName);
            await _httpContext.SignInAsync(cookieName, new ClaimsPrincipal(cp),
                new AuthenticationProperties
                {
                    IsPersistent = bool.Parse(cp.FindFirst(KeyName.IsPersistent).Value),
                    AllowRefresh = true
                });
        }
        public async void SetValue(string cookieName, string keyName, string value)
        {
            var principal = _httpContext.User;
            var cp = principal.Identities.First(i => i.AuthenticationType == cookieName.ToString());

            if (cp.FindFirst(keyName) != null)
            {
                cp.RemoveClaim(cp.FindFirst(keyName));
                cp.AddClaim(new Claim(keyName, value));
            }
            await _httpContext.SignOutAsync(cookieName);
            await _httpContext.SignInAsync(cookieName, new ClaimsPrincipal(cp),
                new AuthenticationProperties
                {
                    IsPersistent = bool.Parse(cp.FindFirst(KeyName.IsPersistent).Value),
                    AllowRefresh = true
                });
        }
    }
    public static class CookieName
    {
        public static string Company => "CompanyUserProfilCookie";
        public static string User => "UserProfilCookie";
        public static string Admin => "AdminPanelCookie";
    }

    public static class KeyName
    {
        public static string Id => ClaimTypes.NameIdentifier;
        public static string Name => ClaimTypes.Name;
        public static string Surname => ClaimTypes.Surname;
        public static string IsPersistent => ClaimTypes.IsPersistent;
        public static string Image => "Image";
    }
}
我正在从任何控制器将HttpContext设置为此类。有没有办法静态HttpContext,我不想从控制器设置?

一个选项是从DI注入IHttpContextAccessor并从它访问HttpContext

更改ClaimsCookie构造函数以反映:

private readonly HttpContext _httpContext;
public ClaimCookie(IHttpContextAccessor contextAccessor)
{
    _httpContext = contextAccessor.HttpContext;
}
接下来,您需要在Startup.ConfigureServices中注册IHttpContextAccessor和ClaimCookie:

public void ConfigureServices(IServiceCollection services)
{
    services.AddHttpContextAccessor();
    services.AddTransient<ClaimCookie>();
    ...rest of code ommited...
}
然后注入您的类并在不提供HttpContext的情况下使用is:

public class SomeController : Controller
{
    private readonly ClaimCookie _claimCookie;

    public SomeController(ClaimCookie claimCookie)
    {
        _claimCookie = claimCookie;
    }

    public async Task<IActionResult> SomeAction()
    {
        int id = int.Parse(_claimCookie.GetValue(CookieName.User, KeyName.Id));
        await _claimCookie.SetValue(CookieName.User, new[] { KeyName.Name, KeyName.Surname }, new[] { model.Name, model.Surname });
        ...
    }
还要阅读为什么不应该使用async void。 关于安全性,我不是专家,你也不应该在cookies中存储敏感数据,如果你需要,那么就存储加密数据