标签: asp.net-core-identity

如何在 ASP.NET Core Identity 控制器的构造函数中获取登录用户名

我正在使用 ASP.NET Core 1.1 和Identity 3.0 constructor 我正在尝试访问控制器中登录用户的登录名,如下所示。但我正在得到NullReferenceException. 但是,我可以在控制器的任何操作方法中获取用户名,如下所示。问题:如何在控制器的构造函数中获取用户名,以便我可以在控制器的任何操作方法中的任何位置使用它。看来我可能必须为此进行某种依赖注入(但这只是一个猜测)。

public class TestController : Controller
{
    private ProjNameContext _context;

    string selUser = "";

    public TestController(ProjNameContext context)
    {
        _context = context;
        selUser = User.Identity.Name; //Here I get error: Object reference not set to an instance of an object.
    }

    [HttpGet]
    public IActionResult TestAction()
    {
        selUser = User.Identity.Name; //Here the user name (login name) is not null
       .....
    }

    ....
}
Run Code Online (Sandbox Code Playgroud)

c# visual-studio-2015 asp.net-core asp.net-core-identity

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

为什么cookie的ExpireTimeSpan设置不起作用?

我用了:

services.AddAuthenticationCore().ConfigureApplicationCookie(o =>
{
    o.ExpireTimeSpan = TimeSpan.FromHours(1);
    o.SlidingExpiration = true;
});
Run Code Online (Sandbox Code Playgroud)

在 ASP.NET Core MVC 项目的Startup.csExpireTimeSpan中设置我的身份验证 cookie 。

我可以看到登录后网络浏览器中的 cookie 过期时间已正确设置,但每次 30 分钟后都会自动注销,即使我每 10 秒刷新一次网站也是如此。

如果我设置ExpireTimeSpan小于30分钟,可以正确超时,但是expire-time无法刷新。

为什么是30分钟?在哪里可以更改 30 分钟超时设置?或者是在IIS中设置的?

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

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

如何使用 NUnit 在 .NET Core 中模拟 UserManager?

我想使用 Razor Pages 对在 .NET Core 中制作的应用程序进行单元测试。我需要嘲笑我dbContext和我的——然而,结果UserManager我似乎一直在回来。null

假用户管理器

public class FakeUserManager : UserManager<ApplicationUser>
{
  public FakeUserManager()        
      : base(new Mock<IUserStore<ApplicationUser>>().Object,
         new Mock<IOptions<IdentityOptions>>().Object,
         new Mock<IPasswordHasher<ApplicationUser>>().Object,
         new IUserValidator<ApplicationUser>[0],
         new IPasswordValidator<ApplicationUser>[0],
         new Mock<ILookupNormalizer>().Object,
         new Mock<IdentityErrorDescriber>().Object,
         new Mock<IServiceProvider>().Object,
         new Mock<ILogger<UserManager<ApplicationUser>>>().Object)
    { }
}
Run Code Online (Sandbox Code Playgroud)

我的测试班

 [TestFixture]
 public class UserTest
 {
     private ApplicationDbContext _dbContext { get; set; }
     public void TestSetUp()
     {
         DbContextOptionsBuilder<ApplicationDbContext> optionsbuilder = new DbContextOptionsBuilder<ApplicationDbContext>();
         optionsbuilder.UseInMemoryDatabase(databaseName: "TestDB");
         _dbContext = new ApplicationDbContext(optionsbuilder.Options);
         _dbContext.Users.Add(new ApplicationUser
         {
             Id = "1",
             FirstName = "Test", …
Run Code Online (Sandbox Code Playgroud)

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

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

身份角色未添加到用户

我想将 JWT 身份验证用于我的 Web api,并将 cookie 身份验证用于 Razor 页面。我对控制器使用策略授权。在我的以下配置中,一切都适用于我的 Razor 页面Startup.cs

services.AddIdentity<User, Role>(opt =>{
                opt.Password.RequireDigit = false;
                opt.Password.RequiredLength = 4;
                opt.Password.RequireNonAlphanumeric = false;
                opt.Password.RequireUppercase = false;
                opt.Password.RequireLowercase = false;
            })
            .AddEntityFrameworkStores<DataContext>()
            .AddRoleValidator<RoleValidator<Role>>()
            .AddRoleManager<RoleManager<Role>>()
            .AddSignInManager<SignInManager<User>>();
Run Code Online (Sandbox Code Playgroud)

但是我的 Controller 端点不起作用,当我使用下面的端点时,它可以工作:

IdentityBuilder builder = services.AddIdentityCore<User>(opt =>
            {
                opt.Password.RequireDigit = false;
                opt.Password.RequiredLength = 4;
                opt.Password.RequireNonAlphanumeric = false;
                opt.Password.RequireUppercase = false;
                opt.Password.RequireLowercase = false;
            });
Run Code Online (Sandbox Code Playgroud)

但是角色没有被添加到用户声明中,因此我的 Razor 页面的授权策略属性总是返回Access Denied

public class Startup
    {
        public Startup(IConfiguration configuration)
        {
            Configuration = configuration;
        }

        public …
Run Code Online (Sandbox Code Playgroud)

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

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

.NET Core 3.0 身份问题

我正在尝试将我的项目更新到 .NET Core 3.0 和 .NET Standard 2.1(包括 .NET Core Identity)

我有2个项目。首先是我的 Web API:

<Project Sdk="Microsoft.NET.Sdk.Web">
  <PropertyGroup>
    <TargetFramework>netcoreapp3.0</TargetFramework>
    <TypeScriptToolsVersion>Latest</TypeScriptToolsVersion>
    <AspNetCoreHostingModel>InProcess</AspNetCoreHostingModel>
  </PropertyGroup>
  <ItemGroup>
    <PackageReference Include="Microsoft.AspNetCore.Identity.EntityFrameworkCore" Version="3.0.0" />
    <PackageReference Include="Microsoft.AspNetCore.Mvc.NewtonsoftJson" Version="3.0.0" />
    <PackageReference Include="Microsoft.EntityFrameworkCore" Version="3.0.0" />
    <PackageReference Include="Microsoft.EntityFrameworkCore.Design" Version="3.0.0" />
    <PackageReference Include="Microsoft.EntityFrameworkCore.SqlServer" Version="3.0.0" />
    <PackageReference Include="Microsoft.EntityFrameworkCore.Tools" Version="3.0.0" />
  </ItemGroup>
...
Run Code Online (Sandbox Code Playgroud)

在这个项目中,与身份相关的代码工作正常。

正如我在这里看到的,我需要删除包Microsoft.AspNetCore.Identity https://docs.microsoft.com/en-us/aspnet/core/migration/22-to-30?view=aspnetcore-3.0&tabs=visual-studio

二期工程:

<Project Sdk="Microsoft.NET.Sdk">
  <PropertyGroup>
    <TargetFramework>netstandard2.1</TargetFramework>
  </PropertyGroup>
  <ItemGroup>
    <!--<FrameworkReference Include="Microsoft.AspNetCore.App" />-->
    <!--<PackageReference Include="Microsoft.AspNetCore.Identity" Version="2.2.0" />-->
  </ItemGroup>
...
Run Code Online (Sandbox Code Playgroud)

所以,如果我Microsoft.AspNetCore.Identity从我的第二个项目中删除,我会看到错误:

SignInManager<>找不到类型或命名空间名称“ ”(您是否缺少 using 指令或程序集引用?)

如果我添加这一行:

<FrameworkReference Include="Microsoft.AspNetCore.App" /> …
Run Code Online (Sandbox Code Playgroud)

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

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

ASP.NET Core Identity - “手动”创建用户并提供密码哈希 - 如何正确生成哈希?

我必须手动创建用户:

var user = new User
{
    Name = "Joe",
    Email = "test@****.com",
    PasswordHash = "gdfgdfgre2132143xcxzvb=="
}

context.Users.Add(user);
Run Code Online (Sandbox Code Playgroud)

但问题是当我尝试登录该帐户时,我的密码不起作用。

复制了我知道密码的用户帐户的密码哈希,然后将其粘贴到该新用户并尝试使用相同的密码但它没有用 -password sign in failed

所以我想问 - 我这里的逻辑有什么问题,我怎样才能让它工作?

它与SecurityStamp有关吗?

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

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

尝试激活 SecurityStampValidator 时无法解析 ISystemClock 的服务

我尝试将 Identity 添加到我的 Web API,但收到此错误

InvalidOperationException:尝试激活 >'Microsoft.AspNetCore.Identity.SecurityStampValidator`1[WebAPI.Models.User>]' 时无法解析类型 >'Microsoft.AspNetCore.Authentication.ISystemClock' 的服务。

在 Startup.cs 中添加 Identity 后,我有这个

services.AddIdentityCore<User>(options => { });
            new IdentityBuilder(typeof(User), typeof(IdentityRole), services)
                .AddRoleManager<RoleManager<IdentityRole>>()
                .AddSignInManager<SignInManager<User>>()
                .AddEntityFrameworkStores<DataContext>();

app.UseAuthentication();
Run Code Online (Sandbox Code Playgroud)

usermodel 类是空的。一切都加载到数据库中。有什么不见了?我感谢您的时间和帮助。

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

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

在 Linux 上的 ASP.NET Core MVC 项目中构建身份脚手架后运行项目时出现问题

我试过添加

<PackageReference Include="Microsoft.AspNetCore.Razor.Runtime" Version="2.2.0" />
Run Code Online (Sandbox Code Playgroud)

但是 2.2.0 是目前可用的最新版本,与错误不符。重建应用程序后错误仍然相同。

项目.csproj:

<Project Sdk="Microsoft.NET.Sdk.Web">
  <PropertyGroup>
    <TargetFramework>netcoreapp3.1</TargetFramework>
    <RuntimeIdentifier>linux-x64</RuntimeIdentifier>
  </PropertyGroup>

  <ItemGroup>
    <PackageReference Include="Microsoft.AspNetCore.Identity.EntityFrameworkCore" Version="3.1.1" />
    <PackageReference Include="Microsoft.AspNetCore.Identity.UI" Version="3.1.1" />
    <PackageReference Include="Microsoft.EntityFrameworkCore" Version="3.1.1" />

    <PackageReference Include="Microsoft.EntityFrameworkCore.Design" Version="3.1.1">
      <IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
      <PrivateAssets>all</PrivateAssets>
    </PackageReference>

    <PackageReference Include="Microsoft.EntityFrameworkCore.SqlServer" Version="3.1.1" />

    <PackageReference Include="Microsoft.EntityFrameworkCore.Tools" Version="3.1.1">
      <IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
      <PrivateAssets>all</PrivateAssets>
    </PackageReference>

    <PackageReference Include="Microsoft.VisualStudio.Web.CodeGeneration.Design" Version="3.1.0" />

    <PackageReference Include="Pomelo.EntityFrameworkCore.MySql" Version="3.1.0" />
  </ItemGroup>
</Project>
Run Code Online (Sandbox Code Playgroud)

完整错误:

未处理的异常。System.IO.FileNotFoundException:无法加载文件或程序集“Microsoft.AspNetCore.Razor.Runtime,版本=3.1.1.0,Culture=neutral,PublicKeyToken=adb9793829ddae60”。该系统找不到指定的文件。

文件名:'Microsoft.AspNetCore.Razor.Runtime,版本=3.1.1.0,Culture=neutral,PublicKeyToken=adb9793829ddae60' at System.ModuleHandle.ResolveTypeHandleInternal(RuntimeModule 模块,Int32 typeToken,RuntimeTypeHandle[] typeInstantiationContext),方法IntimeContext[] System.Reflection.RuntimeModule.ResolveType(Int32 metadataToken, Type[] genericTypeArguments, Type[] genericMethodArguments) 在 System.Reflection.CustomAttribute.FilterCustomAttributeRecord(MetadataToken …

c# entity-framework-core asp.net-core-mvc asp.net-core-identity razor-pages

3
推荐指数
2
解决办法
2408
查看次数

如何从 ASP.NET Core 中的密码重置令牌中检索用户?

我有一个 ASP.NET Core 2.1 Web 应用程序,并且正在添加忘记密码功能。我看过几个例子,他们似乎采取了两种方法之一。第一种方法是在密码重置 url 中包含用户 ID 或用户的电子邮件以及密码重置令牌。第二种方法是在密码重置 url 中仅包含密码重置令牌,然后要求用户在尝试更改密码时输入识别信息(例如电子邮件)(二进制智能示例)。有没有办法在仅给定密码重置令牌的情况下查找用户?

我的团队负责人要求我只传递密码重置 url 中的令牌,然后查找用户。我最初的研究让我相信我必须手动记录用户 ID 和令牌关系,但我希望有内置的东西。我已经查看了ASP.NET Core UserManager 文档,但没有找到任何检索方法给定令牌的用户。

下面是一些将用户 ID 嵌入密码重置 URL(Microsoft 密码恢复文档)的示例代码:

var code = await _userManager.GeneratePasswordResetTokenAsync(user);
var callbackUrl = Url.Action("ResetPassword", "Account", new { userId = user.Id, code = code }, protocol: HttpContext.Request.Scheme);
Run Code Online (Sandbox Code Playgroud)

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

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

cookie 过期后从 Identity 注销会导致 http 错误 400

在我的_LoginPartial.cshtml我有这个注销按钮:

<form id="logoutForm" class="form-inline" asp-area="Identity" asp-page="/Account/Logout" asp-route-returnUrl="@Url.Action("Index", "", new { area = "" })">
    <button id="logout" type="submit">
        Log out
    </button>
</form>
Run Code Online (Sandbox Code Playgroud)

然后,据我所知,Logout.cshtml.cs被称为:

public class LogoutModel : PageModel
{
    private readonly SignInManager<ApplicationUser> _signInManager;
    private readonly ILogger<LogoutModel> _logger;

    public LogoutModel(SignInManager<ApplicationUser> signInManager, ILogger<LogoutModel> logger)
    {
        _signInManager = signInManager;
        _logger = logger;
    }

    public void OnGet()
    {
    }

    public async Task<IActionResult> OnPost(string returnUrl = null)
    {
        await _signInManager.SignOutAsync();
        _logger.LogInformation("User logged out.");
        if (returnUrl != null)
        {
            return LocalRedirect(returnUrl);
        }
        else …
Run Code Online (Sandbox Code Playgroud)

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

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