【问题标题】:Asp.Net Core 3.0 Authorization and AuthenticationAsp.Net Core 3.0 授权和认证
【发布时间】:2020-01-23 00:58:20
【问题描述】:

无论我在互联网上的何处查看,与 net.core 相关的登录过程都会使用身份。没有人谈论使用我们的普通用户名和密码登录。我们正在登录,但这次是在检查 我们不能使用 [Authorize(Roles="Admin")] 或 [Authorize] 属性。要使用它,我们需要如下登录。

signInManager.PasswordSignInAsync (model.email, model.password, true, true);

查看此链接,但结果相同 https://docs.microsoft.com/tr-tr/aspnet/core/fundamentals/middleware/?view=aspnetcore-3.1#ord

如果结果证明是这里的结果,我们正在努力。我需要做什么才能在不使用策略的情况下将上述属性用于我自己的登录,signInManager.PasswordSignInAsync 正在执行此操作,这正是我添加到消息中的内容,如下所示,但无论如何都没有发生。

我的登录代码 https://rextester.com/YBJ16358

我的创业

https://rextester.com/VZODZ96615

【问题讨论】:

    标签: c# authentication authorization identity principal


    【解决方案1】:

    我解决了如下问题。如果用户名和密码为真

    var identity = new ClaimsIdentity(CookieAuthenticationDefaults.AuthenticationScheme, ClaimTypes.Name, ClaimTypes.Role);
    
                identity.AddClaim(new Claim(ClaimTypes.NameIdentifier, user.UserName));
                identity.AddClaim(new Claim(ClaimTypes.Name, user.UserName));
                identity.AddClaim(new Claim(ClaimTypes.GivenName, user.Name));
                identity.AddClaim(new Claim(ClaimTypes.Surname, user.Surname));
                identity.AddClaim(new Claim(ClaimTypes.Email, user.Email));
                foreach (var role in _userManager.GetRolesAsync(user).Result)
                {
                    identity.AddClaim(new Claim(ClaimTypes.Role, role));
                }
                ClaimsPrincipal principal = new ClaimsPrincipal(identity);
                AuthenticationProperties _authentication = new AuthenticationProperties
                {
                    IsPersistent = true,
                    ExpiresUtc = DateTimeOffset.UtcNow
                };
                await _HttpContextAccessor.HttpContext.SignInAsync(CookieAuthenticationDefaults.AuthenticationScheme, principal, new AuthenticationProperties { IsPersistent = true });
    

    我的创业

     services.AddAuthentication(options =>
                {
                    options.DefaultSignInScheme = CookieAuthenticationDefaults.AuthenticationScheme;
                    options.DefaultAuthenticateScheme = CookieAuthenticationDefaults.AuthenticationScheme;
                    options.DefaultChallengeScheme = CookieAuthenticationDefaults.AuthenticationScheme;
                })
                .AddCookie(config =>
                {
                    config.Cookie.Name = "login";
                    config.LoginPath = "/Account/Login";
                    config.ExpireTimeSpan = TimeSpan.FromMinutes(5);
                });
    

    和应用程序

       app.UseAuthentication();
       app.UseAuthorization();
    

    【讨论】:

    • 在不使用时进行 _authentication 有什么意义?
    猜你喜欢
    • 1970-01-01
    • 2020-08-08
    • 2020-02-12
    • 2021-04-16
    • 1970-01-01
    • 2015-03-04
    • 2021-01-07
    • 2021-10-05
    • 1970-01-01
    相关资源
    最近更新 更多