标签: asp.net-identity

如何在asp.net core中获取当前userId

我在核心中使用身份。

在启动时。

services.AddSingleton<ICurrentUserService, CurrentUserService>();
services.AddHttpContextAccessor();
Run Code Online (Sandbox Code Playgroud)

并在帐户控制器中

[ApiController]
[Route("api/[controller]")]
public class AccountController : Controller
{
    private readonly IApplicationUserManager _userManager;
    private readonly SignInManager<ApplicationUser> _signInManager;

    public AccountController
    (IApplicationUserManager userManager,
        SignInManager<ApplicationUser> signInManager)
    {
        _userManager = userManager;
        //_roleManager = roleManager;
        _signInManager = signInManager;
    }



    [HttpPost("Login")]
    [AllowAnonymous]
    public async Task<IActionResult> Login(LoginViewModel model)
    {
        try
        {
            await _signInManager.SignOutAsync();

            var result = await _signInManager.PasswordSignInAsync(model.email, model.password, true, false);


            if (result.Succeeded)
            {
                return Json(new { success = true});
            }

            var message = string.Join("; ", ModelState.Values
                .SelectMany(x => x.Errors)
                .Select(x => …
Run Code Online (Sandbox Code Playgroud)

c# asp.net-identity .net-core asp.net-core

2
推荐指数
1
解决办法
640
查看次数

自定义声明在 AspNetCore Identity cookie 中一段时间​​后丢失

我看到一个几年前就已经被问过的问题,它解释了与使用 AspNet Identity 时丢失自定义声明相关的问题。不幸的是,那里提到的解决方案对我不起作用,因为我在 .NET 6 Blazor Server 应用程序上使用 AspNet Core Identity。

问题是类似的(在下面几点解释):

  1. 我在登录期间添加了一些声明(这些声明来自某些 API 调用,而不是来自 Identity 数据库,因此我在登录期间添加它们)。

  2. 我可以从 Blazor 组件访问它们。

  3. 它在 30% 的情况下工作正常,但在 70% 的情况下,cookie 会丢失我在登录期间添加的自定义声明,并且我的应用程序会遇到问题。我什至无法弄清楚这些声明何时会丢失,因为在这两种情况下都没有发生这种情况,RevalidationInterval因为我用 1 分钟的时间跨度对其进行了测试,并且当我多次测试它时,它至少在 5 分钟内运行良好。搜索了一堆答案,但没有找到 AspNet Core Identity 的正确答案。

这就是我的代码的样子:

  1. Program.cs 中的身份设置
    builder.Services
    .AddDefaultIdentity<IdentityUser>(options =>
    {
        options.SignIn.RequireConfirmedAccount = false;
        // Set Password options here if you'd like:
        options.Password.RequiredLength = 6;
    })
    .AddRoles<IdentityRole>()
    .AddUserManager<ADUserManager<IdentityUser>>()
    .AddEntityFrameworkStores<ApplicationDbContext>();

    builder.Services.AddScoped<AuthenticationStateProvider, RevalidatingIdentityAuthenticationStateProvider<ApplicationUser>>();

Run Code Online (Sandbox Code Playgroud)
  1. 在 Login.cshtml.cs 中登录期间添加声明
    public async Task<IActionResult> OnPostAsync(string returnUrl = null)
    {
        returnUrl ??= Url.Content("~/"); …
Run Code Online (Sandbox Code Playgroud)

c# asp.net-identity asp.net-core blazor-server-side .net-6.0

2
推荐指数
1
解决办法
1062
查看次数

从ASP.NET成员身份转换为新的ASP.NET Identity API

我正在考虑将目前使用ASP.NET成员资格进行身份验证和授权的现有MVC 4转换为最近在VS 2013中发布的MVC 5等新的ASP.NET身份模型.除了升级到MVC 5之外,有没有人想过将应用程序转换为这个新框架所需的内容对现有用户的影响最小?

理想情况下,我想保留他们的密码哈希值和盐,以防止用户在转换后更改密码.此外,有人谈到将Federation作为一些客户端的备用登录,因此我也需要在新系统中使用声明功能.

对于任何反馈,我们都表示感谢.

asp.net-mvc asp.net-membership asp.net-identity

1
推荐指数
1
解决办法
1706
查看次数

ASP.Net Identity定制UserProfile

我正在用EF写一个MVC5应用程序.我在第一次注册用户时在我的数据库中创建ASPNETUser表的项目中添加了ASP.NET Identity.但是现在,当我尝试自定义UserProfile时(如本文所列:http://www.asp.net/mvc/tutorials/mvc-5/create-an-aspnet-mvc-5-app-with-facebook- and-google-oauth2-and-openid-sign-on)

我得到以下内容:

The model backing the 'ApplicationDbContext' context has changed since the database was created. Consider using Code First Migrations to update the database
Run Code Online (Sandbox Code Playgroud)

是因为我已经指定了.edmx文件(MVC5Entities)=>(参见web.config中的2个连接字符串)?

这是我的web.config:

  <connectionStrings>
    <add name="DefaultConnection" connectionString="Data Source=DILS-S1301;Initial Catalog=MVC5;Integrated Security=True" providerName="System.Data.SqlClient" />
  <add name="MVC5Entities" connectionString="metadata=res://*/Models.Mvc5Model.csdl|res://*/Models.Mvc5Model.ssdl|res://*/Models.Mvc5Model.msl;provider=System.Data.SqlClient;provider connection string=&quot;data source=DILS-S1301;initial catalog=MVC5;integrated security=True;MultipleActiveResultSets=True;App=EntityFramework&quot;" providerName="System.Data.EntityClient" />
  </connectionStrings>
Run Code Online (Sandbox Code Playgroud)

我该怎么办?

asp.net-mvc entity-framework asp.net-mvc-5 asp.net-identity

1
推荐指数
1
解决办法
2818
查看次数

UserManager.CreateAsync(用户,密码)陷入无限循环

我试图做一个非常简单的实现,IUserStore基本上:

  • 使用NHibernate
  • 将用户保存在单个表中(无索赔/登录)
  • 将角色名称存储在同一个表中的nvarchar列中('|'如果有多个项目,则为pipe()).

当我运行以下方法时:

[Fact]
public void Create_A_User()
{
    // _session is a valid NHibernate ISession object
    using (var userStore = new SimpleUserStore<SimpleIdentityUser>(_session))
    using (var userManager = new UserManager<SimpleIdentityUser>(userStore))
    {
        var user = new SimpleIdentityUser
        {
            UserName = "kenny_mccormick",
            RolesStr = "admin",
        };

        var createTask = userManager.CreateAsync(user, "the_password");

        var result = createTask.Result; // this never finishes...
    }
}
Run Code Online (Sandbox Code Playgroud)

最后一行永远不会完成执行.

奇怪的是,UserManager永远不会调用我的任何功能SimpleUserStore; 它在那之前就被卡住了.

以下是我定义的组件:

用户类:

public class SimpleIdentityUser : IUser
{
    public virtual …
Run Code Online (Sandbox Code Playgroud)

c# task-parallel-library async-await asp.net-identity

1
推荐指数
1
解决办法
1万
查看次数

asp.net mvc5表单身份验证,OWIN如何进入?

我启动了一个新的MVC5项目并实现了表单身份验证(我曾经使用自定义代码来检查用户凭据以及FormsAuthentication登录和注销的对象).

现在我已经读过身份模型已经改变了,但是我在生成的代码中看到了这行代码:

  private IAuthenticationManager AuthenticationManager
    {

        get
        {
            return HttpContext.GetOwinContext().Authentication;
        }
    }
Run Code Online (Sandbox Code Playgroud)

因为稍后登录是在该对象上完成的(AuthenticationManager.SignIn)

我想确保我有正确的对象.

我已经读过OWIN是关于将ASP.NET与IIS分离的,所以我不确定为什么我需要这个GetOwinContext,因为我没有使用OWIN(至少我认为)?

asp.net-mvc forms-authentication owin asp.net-identity

1
推荐指数
1
解决办法
4786
查看次数

MVC Bootstrap主题

我想在我的MVC 5应用程序中包含对bootswatch主题的主题支持.

我希望用户主题在登录时保存并加载.

我扩展了我的用户类以包含主题,并且可以在编辑用户页面上成功设置和保存主题.

public class User : IdentityUser
{       
public string BootstrapTheme {get;set;}
}
Run Code Online (Sandbox Code Playgroud)

在BootstrapTheme属性中,我将保存bootstrap css链接的href属性.例如 "~/Content/bootstrap.flatly.min.css"

计划是在布局页面中设置主题.

<link href="~/Content/bootstrap.spacelab.min.css" rel="stylesheet" />

如何在不加载每个页面的情况下查询数据库的情况下如何执行此操作?

能够做一些像<link href="@User.BootstrapTheme" rel="stylesheet" />理想的事情.

以下是使用localstorage http://wdtz.org/bootswatch-theme-selector.html保存一页的链接

asp.net-mvc twitter-bootstrap owin asp.net-identity

1
推荐指数
1
解决办法
2609
查看次数

EF不创建AspNet标识表

我有一个简单的aspnet Identity模式,但我无法在我的数据库中创建Identity表.继承了MVC网站用于身份的主要类:

 public class ApplicationUser : IdentityUser
{
}

public class ApplicationDbContext : IdentityDbContext<ApplicationUser>
{
    public ApplicationDbContext()
        : base("DefaultConnection")
    {
    }

    protected override void OnModelCreating(DbModelBuilder modelBuilder)
    {
        if (modelBuilder == null)
        {
            throw new ArgumentNullException("modelBuilder");
        }

        modelBuilder.Entity<IdentityUser>().ToTable("AspNetUsers");
        EntityTypeConfiguration<ApplicationUser> table =
            modelBuilder.Entity<ApplicationUser>().ToTable("AspNetUsers");

        table.Property((ApplicationUser u) => u.UserName).IsRequired();

        modelBuilder.Entity<ApplicationUser>().HasMany<IdentityUserRole>((ApplicationUser u) => u.Roles);
        modelBuilder.Entity<IdentityUserRole>().HasKey((IdentityUserRole r) =>
            new { UserId = r.UserId, RoleId = r.RoleId }).ToTable("AspNetUserRoles");

        EntityTypeConfiguration<IdentityUserLogin> entityTypeConfiguration =
            modelBuilder.Entity<IdentityUserLogin>().HasKey((IdentityUserLogin l) =>
                new
                {
                    UserId = l.UserId,
                    LoginProvider = l.LoginProvider,
                    ProviderKey
                        = l.ProviderKey
                }).ToTable("AspNetUserLogins");

        entityTypeConfiguration.HasRequired<IdentityUser>((IdentityUserLogin …
Run Code Online (Sandbox Code Playgroud)

c# entity-framework asp.net-identity

1
推荐指数
1
解决办法
5340
查看次数

为什么IsInRole总是返回false?

我正在使用ASP.NET Identity 2.0和EF 6.1.1构建MVC5应用程序.

这是我当前的Login方法的一部分:

    [HttpPost]
    [AllowAnonymous]
    [ValidateAntiForgeryToken]
    public async Task<ActionResult> Login(LoginViewModel model, string returnUrl)
    {
        if (!ModelState.IsValid)
            return View(model);

        var result = await SignInManager.PasswordSignInAsync(model.UserName, model.Password, model.RememberMe, shouldLockout: true);
        switch (result)
        {
            case SignInStatus.Success:
                {
                    var user = await UserManager.FindAsync(model.UserName, model.Password);

                    if (user == null)
                        break;

                    if (!UserManager.IsInRole(user.Id, "OfficeUser"))
                        break; // << I always hit this line - even if the user is an OfficeUser
Run Code Online (Sandbox Code Playgroud)

这个工作正常,直到我点击UserManager.IsInRole().这总是返回false.

在某处我读到IsInRole()如果相应的用户没有登录就会失败.但是因为我传递了SignInManager.PasswordSignInAsync(),我相信这应该没问题.

是的,我已经多次检查数据库并且非常小心;)我的测试用户和我的测试角色"OfficeUser"肯定是相互分配的.

有人有想法吗?

ef-code-first asp.net-identity

1
推荐指数
1
解决办法
1253
查看次数

在ASP.NET身份系统中检索密码

如何从PasswordHash列在Asp.Net Identity System中以原始形式检索密码?

.net asp.net asp.net-identity

1
推荐指数
1
解决办法
4337
查看次数