标签: asp.net-core-identity

尝试激活'AuthController'时无法解析类型'Microsoft.AspNetCore.Identity.UserManager`的服务

我在登录控制器中收到此错误.

InvalidOperationException:尝试激活'Automobile.Server.Controllers.AuthController'时,无法解析类型'Microsoft.AspNetCore.Identity.UserManager`1 [Automobile.Models.Account]'的服务.

这是Auth Controller构造函数:

private SignInManager<Automobile.Models.Account> _signManager;
    private UserManager<Automobile.Models.Account> _userManager;

    public AuthController(UserManager<Models.Account> userManager,
                          SignInManager<Automobile.Models.Account> signManager)
    {
        this._userManager = userManager;
        this._signManager = signManager;
    }
Run Code Online (Sandbox Code Playgroud)

这是在startup.cs中的ConfigureServices:

public void ConfigureServices(IServiceCollection services)
    {
        // Add framework services.
        services.AddApplicationInsightsTelemetry(Configuration);
        services.Configure<AppConfig>(Configuration.GetSection("AppSettings"));

        //var provider = HttpContext.ApplicationServices;
        //var someService = provider.GetService(typeof(ISomeService));


        services.AddDbContext<Providers.Database.EFProvider.DataContext>(options => options
            .UseSqlServer(Configuration.GetConnectionString("DefaultConnection"),
                 b => b.MigrationsAssembly("Automobile.Server")
            ));


        services.AddIdentity<IdentityUser, IdentityRole>(options =>
        {
            options.User.RequireUniqueEmail = false;
        })
        .AddEntityFrameworkStores<Providers.Database.EFProvider.DataContext>()
        .AddDefaultTokenProviders(); 
        //services.AddScoped<SignInManager<Automobile.Models.Account>, SignInManager<Automobile.Models.Account>>();
        //services.AddScoped<UserManager<Automobile.Models.Account>, UserManager<Automobile.Models.Account>>();

        services.AddMvc();
        App.Service = services.BuildServiceProvider();

        // Adds a default in-memory implementation of IDistributedCache.
        services.AddDistributedMemoryCache();

        services.AddSession(options …
Run Code Online (Sandbox Code Playgroud)

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

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

如何覆盖ASP.NET Core Identity的密码策略

默认情况下,ASP.NET Core Identity的密码策略至少需要一个特殊字符,一个大写字母,一个数字,......

我该如何更改此限制?

文档中没有任何内容(https://docs.asp.net/en/latest/security/authentication/identity.html)

我尝试覆盖Identity的用户管理器,但我没有看到哪个方法管理密码策略.

public class ApplicationUserManager : UserManager<ApplicationUser>
{
    public ApplicationUserManager(
        DbContextOptions<SecurityDbContext> options,
        IServiceProvider services,
        IHttpContextAccessor contextAccessor,
        ILogger<UserManager<ApplicationUser>> logger)
        : base(
              new UserStore<ApplicationUser>(new SecurityDbContext(contextAccessor)),
              new CustomOptions(),
              new PasswordHasher<ApplicationUser>(),
              new UserValidator<ApplicationUser>[] { new UserValidator<ApplicationUser>() },
              new PasswordValidator[] { new PasswordValidator() },
              new UpperInvariantLookupNormalizer(),
              new IdentityErrorDescriber(),
              services,
              logger
            // , contextAccessor
              )
    {
    }

    public class PasswordValidator : IPasswordValidator<ApplicationUser>
    {
        public Task<IdentityResult> ValidateAsync(UserManager<ApplicationUser> manager, ApplicationUser user, string password)
        {
            return Task.Run(() =>
            {
                if (password.Length >= 4) …
Run Code Online (Sandbox Code Playgroud)

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

43
推荐指数
4
解决办法
2万
查看次数

ASP.NET Core 2.0 JWT验证因"用户授权失败:(null)"错误而失败

我正在使用ASP.NET Core 2.0应用程序(Web API)作为JWT发行者来生成移动应用程序的令牌消费品.不幸的是,这个令牌无法由一个控制器验证,而另一个控制器可以验证(在同一个asp.net核心2.0应用程序中使用相同的验证设置).

所以我有一个有效且可以解码的令牌,具有所有必需的声明和时间戳.但是一个端点接受它,而另一个端点给我401错误和调试输出:

Microsoft.AspNetCore.Authorization.DefaultAuthorizationService:信息:用户授权失败:(null).

[40m[32minfo[39m[22m[49m: Microsoft.AspNetCore.Authorization.DefaultAuthorizationService[2]
      Authorization failed for user: (null).
Microsoft.AspNetCore.Authorization.DefaultAuthorizationService:Information: Authorization failed for user: (null).
[40m[32minfo[39m[22m[49m: Microsoft.AspNetCore.Mvc.Internal.ControllerActionInvoker[3]
      Authorization failed for the request at filter 'Microsoft.AspNetCore.Mvc.Authorization.AuthorizeFilter'.
Microsoft.AspNetCore.Mvc.Internal.ControllerActionInvoker:Information: Authorization failed for the request at filter 'Microsoft.AspNetCore.Mvc.Authorization.AuthorizeFilter'.
Microsoft.AspNetCore.Mvc.ChallengeResult:Information: Executing ChallengeResult with authentication schemes ().
[40m[32minfo[39m[22m[49m: Microsoft.AspNetCore.Mvc.ChallengeResult[1]
      Executing ChallengeResult with authentication schemes ().
[40m[32minfo[39m[22m[49m: Microsoft.AspNetCore.Authentication.JwtBearer.JwtBearerHandler[12]
      AuthenticationScheme: Bearer was challenged.
Microsoft.AspNetCore.Authentication.JwtBearer.JwtBearerHandler:Information: AuthenticationScheme: Bearer was challenged.
[40m[32minfo[39m[22m[49m: Microsoft.AspNetCore.Mvc.Internal.ControllerActionInvoker[2]
      Executed action MyController.Get (WebApi) in 72.105ms
Microsoft.AspNetCore.Mvc.Internal.ControllerActionInvoker:Information: Executed action MyController.Get (WebApi) in 72.105ms
Microsoft.AspNetCore.Hosting.Internal.WebHost:Information: …
Run Code Online (Sandbox Code Playgroud)

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

41
推荐指数
5
解决办法
2万
查看次数

.NET Core 2.1 Identity为所有用户提供相关角色

我正在尝试为用户管理管理页面提取所有Identity用户及其相关角色.我认为这相当容易,但显然不是.我尝试过以下解决方案:https://stackoverflow.com/a/43562544/5392786但到目前为止还没有解决.

这是我到目前为止:

ApplicationUser:

public class ApplicationUser : IdentityUser
{
    public List<IdentityUserRole<string>> Roles { get; set; }
}
Run Code Online (Sandbox Code Playgroud)

的DbContext

public class ApplicationDbContext : IdentityDbContext<ApplicationUser>
{
    public ApplicationDbContext(DbContextOptions<ApplicationDbContext> options)
        : base(options)
    {
    }
}
Run Code Online (Sandbox Code Playgroud)

启动标识代码

services.AddIdentity<ApplicationUser, IdentityRole>(options => options.Stores.MaxLengthForKeys = 128)
            .AddEntityFrameworkStores<ApplicationDbContext>()
            .AddDefaultTokenProviders();
Run Code Online (Sandbox Code Playgroud)

我想要显示列表的Razor Page:

public class IndexModel : PageModel
{
    private readonly UserManager<ApplicationUser> userManager;

    public IndexModel(UserManager<ApplicationUser> userManager)
    {
        this.userManager = userManager;
    }

    public IEnumerable<ApplicationUser> Users { get; set; }

    public void OnGetAsync()
    {
        this.Users = userManager.Users.Include(u => …
Run Code Online (Sandbox Code Playgroud)

c# mysql entity-framework-core asp.net-core asp.net-core-identity

26
推荐指数
6
解决办法
3万
查看次数

如何在ASP.NET Core中返回401而不是302?

当用户未登录时,我试图让ASP.NET Core Identity返回401.我已经[Authorize]为我的方法添加了一个属性,而不是返回401,它返回302.我已经尝试了很多建议但是似乎没什么用,包括services.Configureapp.UseCookieAuthentication设置LoginPathnullPathString.Empty.

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

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

如何使用UserManager在IdentityUser上加载导航属性

我已经扩展IdentityUser为包含用户地址的导航属性,但是在获取用户时UserManager.FindByEmailAsync,不会填充导航属性.ASP.NET Identity Core是否有某种方法来填充Entity Framework的导航属性Include(),或者我是否必须手动执行此操作?

我已经设置了这样的导航属性:

public class MyUser : IdentityUser
{
    public int? AddressId { get; set; }

    [ForeignKey(nameof(AddressId))]
    public virtual Address Address { get; set; }
}

public class Address
{
    [Key]
    public int Id { get; set; }
    public string Street { get; set; }
    public string Town { get; set; }
    public string Country { get; set; }
}
Run Code Online (Sandbox Code Playgroud)

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

24
推荐指数
4
解决办法
3840
查看次数

我应该如何从MVC 6视图中访问我的ApplicationUser属性?

我正在开发一个ASP.Net vNext/MVC6项目.我正在掌握ASP.Net Identity.

ApplicationUser类显然是在那里我应该添加任何额外的用户属性,这可与实体框架和我的附加属性获取存储在数据库中的预期.

但是,当我想从我的视图中访问当前登录用户的详细信息时,问题就出现了.具体来说,我有一个_loginPartial.cshtml我想要检索并显示用户的Gravatar图标,我需要该电子邮件地址.

Razor View基类有一个User属性,它是一个ClaimsPrincipal.如何从此User属性返回到我的ApplicationUser,以检索我的自定义属性?

请注意,我不是在询问如何查找信息; 我知道如何ApplicationUserUser.GetUserId()值中查找.这是一个关于如何合理地解决这个问题的问题.具体来说,我不想:

  • 从我的视图中执行任何类型的数据库查找(关注点分离)
  • 必须为每个控制器添加逻辑以检索当前用户的详细信息(DRY原则)
  • 必须为每个ViewModel添加User属性.

这似乎是一个"横切关注点",应该有一个集中的标准解决方案,但我觉得我错过了一块拼图游戏.从视图中获取这些自定义用户属性的最佳方法是什么?

注意:似乎MVC团队通过确保UserName属性始终设置为用户的电子邮件地址,在项目模板中侧面解决了这个问题,巧妙地避免了他们执行此查找以获取用户的电子邮件地址!这对我来说似乎有点欺骗,在我的解决方案中,用户的登录名可能是也可能不是他们的电子邮件地址,所以我不能依赖这个技巧(我怀疑还有其他属性我需要稍后访问).

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

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

在ASP.NET Core Identity UI中更改路由?

自ASP.NET Core 2.1发布以来,我正在使用新的Identity UI软件包.使用新生成的MVC项目,这里有一些可用的页面URL:

/Home/About
/Home/Contact
/Identity/Account/Login
/Identity/Account/Register
Run Code Online (Sandbox Code Playgroud)

如何配置路由以/Identity/从URL中删除部分?

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

18
推荐指数
3
解决办法
6406
查看次数

NormalizedUserName VS DotNet Core中的用户名

我正在尝试为MongoDB创建IUserLoginStore的自定义实现,我在使用时注意到了

UserManager<ApplicationUser>
Run Code Online (Sandbox Code Playgroud)

用这个方法

 var userResult = await _userManager.CreateAsync(user);
Run Code Online (Sandbox Code Playgroud)

它经历了实施

GetUserNameAsync
FindByNameAsync
SetNormalizedUserNameAsync
GetUserIdAsync
Run Code Online (Sandbox Code Playgroud)

我想澄清两个问题:

  • 拥有NormalizedUsername和UserName的目的是什么?唯一的区别是我能注意到normalizedUserName是大写的.

  • 我只使用我的实现来存储来自外部登录(Google plus)的用户,有没有办法我可以省略用户名和NormilizedUserName,因为基本上,我在这三个领域使用电子邮件,我感觉我复制数据对我来说没有任何意义.

任何建议?

asp.net-identity asp.net-core-mvc asp.net-core-identity

17
推荐指数
2
解决办法
7547
查看次数

使用 Windows 身份验证的 ASP.NET Core 标识

我正在使用 .NET Core 3.0 Preview6。
我们有一个启用了 Windows 身份验证的 Intranet 应用程序,这意味着只允许有效的 AD 用户使用该应用程序。
但是,我们喜欢使用 ASP.NET Identity 运行我们自己的身份验证后端,因为它“开箱即用”。我刚刚使用用户的 Windows 登录向 AspNetUsers 表添加了一列。

我想要完成的是 Windows 用户使用他们的 Windows 登录名自动登录到应用程序。
我已经创建了一个自定义身份验证中间件,请参阅下面的代码:

public class AutoLoginMiddleware
{
    private readonly RequestDelegate _next;
    private readonly ILogger _logger;

    public AutoLoginMiddleware(RequestDelegate next, ILogger<AutoLoginMiddleware> logger)
    {
        _next = next;
        _logger = logger;
    }

    public async Task InvokeAsync(HttpContext context, UserService userService, UserManager<IntranetUser> userManager, 
        SignInManager<IntranetUser> signInManager)
    {
        if (signInManager.IsSignedIn(context.User))
        {
            _logger.LogInformation("User already signed in");
        }
        else
        {
            if (context.User.Identity as WindowsIdentity != null)
            { …
Run Code Online (Sandbox Code Playgroud)

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

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