标签: asp.net-core-identity

.NetCore JwtBearerAuthentication不拒绝过期的令牌

我正在生成JWT以用于我的WebApi项目.我将令牌设置为在一分钟后到期,以便我可以测试它是否在到期日期之后提交时拒绝令牌.

CreateToken控制器

public async Task<IActionResult> CreateToken([FromBody] CredentialModel model)
{
    var user = await _unitOfWork.UserManager.FindByNameAsync(model.UserName);

    if (user == null) return BadRequest();
    if (Hasher.VerifyHashedPassword(user, user.PasswordHash, model.Password) !=
        PasswordVerificationResult.Success) return BadRequest();

    var userClaims = await UserManager.GetClaimsAsync(user);

    var claims = new[]
    {
        new Claim(JwtRegisteredClaimNames.Sub, user.UserName),
        new Claim(JwtRegisteredClaimNames.Jti, Guid.NewGuid().ToString()),
        new Claim(JwtRegisteredClaimNames.Iat, DateTime.UtcNow.ToString()),
        new Claim(JwtRegisteredClaimNames.GivenName, user.FirstName), 
        new Claim(JwtRegisteredClaimNames.FamilyName, user.LastName),
        new Claim(JwtRegisteredClaimNames.Email, user.Email)
    }
    .Union(userClaims);

    var cert = new Certificate(Configuration["Tokens:Certificate"]);
    var token = new JwtSecurityToken(
        issuer: Configuration["Tokens:Issuer"],
        audience: Configuration["Tokens:Audience"],
        claims: claims,
        expires: DateTime.UtcNow.AddMinutes(1),
        signingCredentials: cert.Signature
    );

    return …
Run Code Online (Sandbox Code Playgroud)

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

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

如何在ASP.NET Core 2.1中使用角色?

我使用以下方法创建了一个测试项目:

dotnet new razor --auth Individual --output Test
Run Code Online (Sandbox Code Playgroud)

这将创建一个Startup.cs,其中包含:

public void ConfigureServices(IServiceCollection services)
{
    services.Configure<CookiePolicyOptions>(options =>
    {
        // This lambda determines whether user consent for non-essential cookies is needed for a given request.
        options.CheckConsentNeeded = context => true;
        options.MinimumSameSitePolicy = SameSiteMode.None;
    });

    services.AddDbContext<ApplicationDbContext>(options =>
        options.UseSqlite(
            Configuration.GetConnectionString("DefaultConnection")));

    services.AddDefaultIdentity<IdentityUser>()
        .AddEntityFrameworkStores<ApplicationDbContext>();

    services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1);
}
Run Code Online (Sandbox Code Playgroud)

我想为一些用户和角色提供种子.用户和角色都将使用同一个商店(SQLite).我正在使用一个静态类来播种它Program.

我可以播种用户,但不能播放角色,因为上面似乎没有注入RoleManager.

在ASP.NET Core 2.0中使用以下内容:

services.AddIdentity<IdentityUser, IdentityRole>()
Run Code Online (Sandbox Code Playgroud)

我猜测AddDefaultIdentity2.1是新的,但问题是它没有注入RoleMnager,所以我该怎么办?

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

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

如何翻译身份密码验证消息

到目前为止,我已经能够翻译 ASP.Net Core 2.1 Web 应用程序中的所有内容。

事实证明这是一个小挑战,因为脚手架帐户页面需要一些设置。

但是我找不到一种翻译密码验证消息的方法。此外,翻译模型绑定消息是一个小挑战(感谢 stackoverflow)。

有任何想法吗?

我包括我的Startup.cs文件的相关部分:

public void ConfigureServices(IServiceCollection services)
{
     ...

     services.AddMvc(options =>
     {
         var type = typeof(SharedResources);
         var assemblyName = new AssemblyName(type.GetTypeInfo().Assembly.FullName);
         var factory = services.BuildServiceProvider().GetService<IStringLocalizerFactory>();
         var L = factory.Create("SharedResources", assemblyName.Name);

         options.ModelBindingMessageProvider.SetValueIsInvalidAccessor(x => L["The value '{0}' is invalid.", x]);
         options.ModelBindingMessageProvider.SetValueMustNotBeNullAccessor(x => L["The value '{0}' is invalid.", x]);
         options.ModelBindingMessageProvider.SetValueMustBeANumberAccessor(x => L["The field {0} must be a number.", x]);
         options.ModelBindingMessageProvider.SetMissingBindRequiredValueAccessor(x => L["A value for the '{0}' property was not provided.", x]);
         options.ModelBindingMessageProvider.SetAttemptedValueIsInvalidAccessor((x, y) …
Run Code Online (Sandbox Code Playgroud)

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

13
推荐指数
2
解决办法
6071
查看次数

使用AspNetUserTokens表在ASP.NET Core Web Api中存储刷新令牌

我正在使用ASP.NET Core Web API应用程序.我正在尝试在ASP.NET Identity(内置数据库表)之上实现基于Jwt令牌的身份验证.

我已经实现了所有方案,如注册用户,登录等,但现在尝试实现刷新令牌流(访问令牌过期,客户端需要使用刷新令牌获取替换访问令牌).我看到有人正在创建新表(refreshToken)来存储刷新令牌,因此可以使用访问令牌进行验证,并生成新访问和刷新令牌

https://www.blinkingcaret.com/2018/05/30/refresh-tokens-in-asp-net-core-web-api/

https://www.c-sharpcorner.com/article/handle-refresh-token-using-asp-net-core-2-0-and-json-web-token/

我创建了新表(refreshToken)来存储刷新令牌并验证它以生成访问令牌,它工作正常,但我想看看我是否可以使用现有的AspNetUserTokens表来处理相同的场景.据我所知,AspNetUserTokens表用于确认电子邮件,忘记密码等.

我的问题是:如果有人使用AspNetUserTokens存储refreshtoken,请分享想法,因为usermanager类不公开直接令牌模型(AspNetUserTokens)并且不确定我是否使用IdentityDbContext,有什么代词和缺点?我已经实现了IdentityDbContext,但是我没有在Microsoft.AspNetCore.Identity中看到内置类来在AspNetUserTokens中存储令牌

非常感谢一些指导.

谢谢

security authentication jwt asp.net-core-identity asp.net-core-2.1

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

ASP.Net核心本地化

ASP.Net核心为本地化提供了新的支持.

在我的项目中,我只需要一种语言.对于大多数文本和注释,我可以用我的语言指定内容,但对于来自ASP.Net Core本身的文本,语言是英语.

例子:

  • 密码必须至少有一个大写字母('A' - 'Z').
  • 密码必须至少有一位数('0' - '9').
  • 用户名'x@x.com'已被占用.
  • 电子邮件字段不是有效的电子邮件地址.
  • 值''无效.

我已经尝试手动设置文化,但语言仍然是英语.

app.UseRequestLocalization(new RequestLocalizationOptions
{
    DefaultRequestCulture = new RequestCulture("nb-NO"),
    SupportedCultures = new List<CultureInfo> { new CultureInfo("nb-NO") },
    SupportedUICultures = new List<CultureInfo> { new CultureInfo("nb-NO") }
});
Run Code Online (Sandbox Code Playgroud)

如何更改ASP.Net Core的语言,或覆盖其默认文本?

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

12
推荐指数
3
解决办法
6521
查看次数

向 .NET Core 3 应用程序添加身份服务器身份验证失败,并显示“未指定密钥类型”。

我正在尝试向 .NET Core 3 API 项目添加身份服务器身份验证。

我已经添加了这个代码

public void ConfigureServices(IServiceCollection services)
{
    … 

    var identityBuilder = services.AddIdentityServer();

    identityBuilder.AddApiAuthorization<ApplicationUser, DbContext>();

    services
        .AddAuthentication()
        .AddIdentityServerJwt();

    var fileName = Path.Combine("Certificates", "certificatefile.pfx");
    var cert = new X509Certificate2(fileName, "veryDifficultPassword");
    identityBuilder.AddSigningCredential(cert);

    … 
}
Run Code Online (Sandbox Code Playgroud)

和:

public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
    … 
    app.UseAuthentication();
    app.UseIdentityServer(); // <--- this line throws error.
    app.UseAuthorization();
    … 
}

Run Code Online (Sandbox Code Playgroud)

文件/Certificates夹中有一个文件可以正确读取和加载- 我可以检查cert变量并且它看起来是正确的。

到目前为止,我所尝试的一切都以线路app.UseIdentityServer();炸毁而告终:

System.InvalidOperationException: '未指定密钥类型。'

有什么建议?

更新:包括堆栈跟踪

System.InvalidOperationException
  HResult=0x80131509
  Message=Key type not specified.
  Source=Microsoft.AspNetCore.ApiAuthorization.IdentityServer
  StackTrace:
   at Microsoft.AspNetCore.ApiAuthorization.IdentityServer.ConfigureSigningCredentials.LoadKey()
   at …
Run Code Online (Sandbox Code Playgroud)

.net-core asp.net-core identityserver4 asp.net-core-identity asp.net-core-3.0

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

如何在ASP.NET Core Identity中注销其他用户

如何在ASP.NET Core Identity中注销另一个用户(不是当前记录的用户).

我知道有一个SignOutAsync()方法SignInManager,但似乎没有覆盖接受用户作为参数.我正在寻找类似的东西:

signInManager.SignOutAsync(user);
Run Code Online (Sandbox Code Playgroud)

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

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

更改角色后刷新声明主要内容

我在改变dotnetcore身份中的角色时遇到了一些问题.

我有以下代码.

private async Task SetRoleToX(ClaimsPrincipal claimsPrincipal, string X)
{
    var currentUser = await UserManager.GetUserAsync(claimsPrincipal);
    var roles = await UserManager.GetRolesAsync(currentUser);

    await UserManager.RemoveFromRolesAsync(currentUser, roles);
    await UserManager.AddToRoleAsync(currentUser, X);
    await SignInManager.RefreshSignInAsync(currentUser);
}
Run Code Online (Sandbox Code Playgroud)

我无法更新ClaimsPrincipal.

我尝试过使用登录并注销.

如果我手动登录和退出,角色切换工作正常.

我一直在网上搜索,很多人说这应该工作:(

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

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

IdentityServer4 + Asp.Net核心标识 - 将标识映射到应用程序数据库用户

我正在尝试使用Asp.Net核心身份实现IdentityServer4.我想使用IdentityServer4作为使用始终相同标识的API的集中身份验证/授权点.因此,我们的想法是将Asp.Net核心标识内容存储在充当身份存储库的SQL数据库中.

现在的问题是如何将集中身份映射到特定于应用程序的数据.我想在多个应用程序中使用相同的身份用户,但在每个应用程序中,用户都有其他相关实体,角色等.

我阅读了IdentityServer4的文档,但找不到与建议的结构相关的任何内容.

据我所知,您以某种方式将身份ID映射到本地应用程序用户.诸如firstname等的基本数据存储在集中式身份存储中,并且应用程序特定数据存储在应用程序特定数据库中.所以你不会在应用程序特定的数据库中保存名字等吗?在您需要的每个请求中,用户特定数据将查询身份服务器以获取信息/声明?注册流程怎么样?

有没有人有一个清晰的结构设置,可用于了解整个设置?(与Asp.Net Identity Provider,IdentityServer4,Protected Api等分离.)

asp.net-authorization asp.net-core identityserver4 asp.net-core-identity

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

ASP.NET Core 2.0中的多个身份

我正在将ASP.NET Core 1.0应用程序迁移到ASP.NET Core 2.0.

在我的启动中,我正在配置两个身份:

services.AddIdentity<IdentityUser, IdentityRole>(configureIdentity)
   .AddDefaultTokenProviders()
   .AddUserStore<IdentityUserStore<IdentityUser>>()
   .AddRoleStore<IdentityRoleStore<IdentityRole>>();

services.AddIdentity<Customer, CustomerRole>(configureIdentity)
   .AddDefaultTokenProviders()
   .AddErrorDescriber<CustomerIdentityErrorDescriber>()
   .AddUserStore<CustomerStore<Customer>>()
   .AddRoleStore<CustomerRoleStore<CustomerRole>>();
Run Code Online (Sandbox Code Playgroud)

这在ASP.NET Core 1.0中运行良好,但失败并出现错误:System.InvalidOperationException:' ASP.NET 已存在:Identity.Application'在ASP.NET Core 2.0中.

在ASP.NET Core 2.0中,如果我删除其中一个对AddIdentity错误的调用就会消失.如何迁移我的代码,以便在我的应用程序中使用两种不同类型的身份用户和角色?或者,当我在ASP.NET Core 1.0中编写此内容时,我是否只是在理解事情如何工作方面犯了一个根本错误?

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

11
推荐指数
2
解决办法
5095
查看次数