C# ASP.Net核心2.2身份验证

C# ASP.Net核心2.2身份验证,c#,asp.net-core,C#,Asp.net Core,我正在尝试确定处理我的应用程序当前身份验证的最佳方法。我的应用程序没有任何身份验证,但在进入我的应用程序之前,将从登录页面进行处理。如果他们成功验证,我的应用程序将收到一个包含凭据和其他用户信息的cookie 确定cookie在整个用户会话中是否存在的最佳方法是什么?我目前正在读取启动页面上的cookie,但如果用户将超过该页面的页面添加书签,则会导致问题。我应该检查每个页面请求中是否存在cookie,还是可以在用户点击默认页面时提前检查并以某种方式存储cookie 下面是我目前如何从cooki

我正在尝试确定处理我的应用程序当前身份验证的最佳方法。我的应用程序没有任何身份验证,但在进入我的应用程序之前,将从登录页面进行处理。如果他们成功验证,我的应用程序将收到一个包含凭据和其他用户信息的cookie

确定cookie在整个用户会话中是否存在的最佳方法是什么?我目前正在读取启动页面上的cookie,但如果用户将超过该页面的页面添加书签,则会导致问题。我应该检查每个页面请求中是否存在cookie,还是可以在用户点击默认页面时提前检查并以某种方式存储cookie

下面是我目前如何从cookie中抓取用户

UserId=\u ltpaToken.ltpatokenpasse();
如果(UserId==“”)
{
_logger.错误(“未找到用户”);
返回重定向Topage(“/Error”);
}
其他的
{
HttpContext.Session.SetString(“UserId”,UserId);
返回重定向Topage();
//用户是好的
}
然后在另一个页面上再次检查用户ID

UserId=\u httpContextAccessor.HttpContext.Session.GetString(“UserId”);
if(UserId==null)
{
响应。重定向(“到公司登录页面”);
}
//继续页面加载

有更好的方法吗?

var currentUserName=User.Identity.Name

在任何地方都可以工作,角色也是不错的选择

var currentUserRole=User.IsInRole(“管理员”)

控制器

public class PersonAuthorizationController : Controller
{
    private readonly SignInManager<IdentityUser> _signInManager;
    private readonly UserManager<IdentityUser> _userManager;
    private readonly MainDbContext _context;

    public PersonAuthorizationController(
        MainDbContext context, 
        UserManager<IdentityUser> userManager,
        SignInManager<IdentityUser> signInManager)
    {
        _userManager = userManager;
        _signInManager = signInManager;
        _context = context;
    }

    // GET: Contact/PersonAuthorization
    public async Task<IActionResult> Index()
    {
        var currentUserId = _userManager.GetUserId(User);
        return View();
    }
公共类PersonAuthorizationController:控制器
{
专用只读签名管理器\u签名管理器;
私有只读用户管理器_UserManager;
私有只读MainDbContext_context;
公共人物授权控制器(
MainDbContext上下文,
用户管理器用户管理器,
SignInManager(签名管理员)
{
_userManager=userManager;
_signInManager=signInManager;
_上下文=上下文;
}
//获取:联系人/个人授权
公共异步任务索引()
{
var currentUserId=\u userManager.GetUserId(用户);
返回视图();
}

如果您需要的不是的东西,您可以使用这样的东西

首先创建一个简单的用户类

public class MyCustomUser
{
    public int Id { get; set; }
    public string Name { get; set; }
    public string GivenName { get; set; }
}
startup.cs内部
ConfigureServices
方法中

services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme)
    .AddCookie(options =>
        {
            options.ExpireTimeSpan = TimeSpan.FromDays(7);
            options.LoginPath = "/Account/CustomLogin";
            options.Cookie.Name = "MyAuthCookieName";
        }
    );
startup.cs内部
Configure
方法中

app.UseAuthentication();
然后在控制器中的
登录
操作中,您可以编写类似这样的内容,将用户的信息保存在声明中()

//在您的SignIn方法中
//用户信息应取自数据库
MyCustomUser=新的MyCustomUser()
{
Id=1,
Name=“真棒先生”,
givename=“约翰·多伊”
};
//添加用户信息
清单索赔=新清单
{
新声明(ClaimTypes.NameIdentifier,user.Id.ToString()),
新索赔(ClaimTypes.Name、user.Name),
新索赔(ClaimTypes.GivenName,user.GivenName)
};
//从声明中创建主要用户
ClaimsIdentity identity=新的ClaimsIdentity(claims,CookieAuthenticationDefaults.AuthenticationScheme);
ClaimsPrincipal principal=新的ClaimsPrincipal(标识);
AuthenticationProperties AuthenticationProperties=新建AuthenticationProperties(){IsPersistent=false};
//创建身份验证cookie并将其存储
等待this.HttpContext
.SignInAsync(CookieAuthenticationDefaults.AuthenticationScheme,
委托人(身份验证属性);
//完成了!

我建议您在问题中添加一些代码。这将增加获得答案的机会。此外,这将防止您的问题被标记和关闭。请从正式的Asp.net核心文档开始。这里有一些关于设置身份验证的教程。@acarlstein感谢您的建议!
//Inside your SignIn method
    //User info should be taken from DB
    MyCustomUser user = new MyCustomUser()
    {
        Id = 1,
        Name = "Mr.Awesome",
        GivenName = "John Doe"
    };

    //Add user information
    List<Claim> claims = new List<Claim>
    {
        new Claim(ClaimTypes.NameIdentifier, user.Id.ToString()),
        new Claim(ClaimTypes.Name, user.Name),
        new Claim(ClaimTypes.GivenName, user.GivenName)
    };

    //Create the principal user from the claims
    ClaimsIdentity identity = new ClaimsIdentity(claims, CookieAuthenticationDefaults.AuthenticationScheme);
    ClaimsPrincipal principal = new ClaimsPrincipal(identity);
    AuthenticationProperties authenticationProperties = new AuthenticationProperties() {IsPersistent = false};

    //Create the authentication cookie and store it
    await this.HttpContext
            .SignInAsync(CookieAuthenticationDefaults.AuthenticationScheme, 
             principal, authenticationProperties);

   // DONE!