标签: asp.net-core-identity

如何使用带有IdentityServer4的ASP.Net标识添加要包含在access_token中的其他声明

如何添加要包含在令牌中的其他声明?

一旦API收到承载令牌,User.Identity对象就会填充以下声明.

[
  {
    "key": "nbf",
    "value": "1484614344"
  },
  {
    "key": "exp",
    "value": "1484615244"
  },
  {
    "key": "iss",
    "value": "http://localhost:85"
  },
  {
    "key": "aud",
    "value": "http://localhost:85/resources"
  },
  {
    "key": "aud",
    "value": "WebAPI"
  },
  {
    "key": "client_id",
    "value": "MyClient"
  },
  {
    "key": "sub",
    "value": "d74c815a-7ed3-4671-b4e4-faceb0854bf6"
  },
  {
    "key": "auth_time",
    "value": "1484611732"
  },
  {
    "key": "idp",
    "value": "local"
  },
  {
    "key": "role",
    "value": "AccountsManager"
  },
  {
    "key": "scope",
    "value": "openid"
  },
  {
    "key": "scope",
    "value": "profile"
  },
  {
    "key": "scope",
    "value": "roles" …
Run Code Online (Sandbox Code Playgroud)

asp.net-core identityserver4 asp.net-core-webapi asp.net-core-identity

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

IdentityServer4:为Client_Credential Granttype添加自定义默认声明到客户端主体

我正在使用IdentityServer4,我正在尝试在CLIENT创建令牌时向我添加自定义默认声明.如果我使用隐式流程,这是可能的,IProfileService如下所示.

public class MyProfileService : IProfileService
{
    public MyProfileService()
    {

    }
    public Task GetProfileDataAsync(ProfileDataRequestContext context)
    {
        var claims = new List<Claim>
        {
            new Claim("DemoClaimType", "DemoClaimValue")
        };
        context.IssuedClaims = claims;
        return Task.FromResult(0);
    }
    public Task IsActiveAsync(IsActiveContext context)
    {
        context.IsActive = true;
        return Task.FromResult(0);
    }
}
Run Code Online (Sandbox Code Playgroud)

在我的创业公司

services.AddIdentityServer()
            .AddProfileService<MyProfileService>()
Run Code Online (Sandbox Code Playgroud)

但是,这似乎与我的client_credential granttype客户端无关cannot request OpenID scopes in client credentials flow.事实证明,像名称暗示的Iprofileservice适用于Identity资源,其中OpenId范围如profile是有效的.因为我无法请求具有client_credential授权类型的配置文件范围GetProfileDataAsync永远不会被调用.

由于我只与客户合作而没有用户,我需要一种方法将声明注入令牌,而不必将它们添加到客户端对象,如下所示

    new Client
{
    ClientId = "myclient",
    ClientName = "My Client",
    AllowedGrantTypes = GrantTypes.ClientCredentials, …
Run Code Online (Sandbox Code Playgroud)

claims-based-identity asp.net-core-mvc asp.net-core identityserver4 asp.net-core-identity

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

如何从 ASPNET Core 控制器获取 JWTToken?

我正在尝试向受保护的 API 发出请求,因此我需要向 HttpClient 添加授权请求标头,如下所示:

client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", "Your Oauth token");
Run Code Online (Sandbox Code Playgroud)

但是如何从控制器获取身份验证令牌(“您的 Oauth 令牌”)?

PS:我已经通过了 Identity Server 4 的身份验证。在 AspNetCore 中开发的应用程序。

完整代码:

    [Authorize] //Already authenticated
    public IActionResult SomeControllerAction()
    {
        var claimsIdentity = User.Identity as ClaimsIdentity; //where is JWTToken??
        var JWTTokne = "how to get?";

        using (var client = new HttpClient())
        {
            client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", JWTTokne);
            var result = client.PostAsync("someurl", new StringContent(json, Encoding.UTF8, "application/json")).Result;
            //more code to handle result....
        }

        return View();
    }
Run Code Online (Sandbox Code Playgroud)

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

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

我们可以在Asp.NET Core中销毁/无效JWT令牌吗?

我使用ASP.NET Core和ASP.NET核心Identity来生成JWT令牌.

在客户端,我的react(SPA)应用程序调用API来创建令牌,然后包含Authorization: Bearer tokenFromApi在子请求中.

当我想注销时如何立即使服务器端的令牌过期?

目前我只是bear在客户端删除令牌而不包含在下一个请求中?

参考:https://blogs.msdn.microsoft.com/webdev/2017/04/06/jwt-validation-and-authorization-in-asp-net-core/


守则ConfigureStartup.cs

app.UseJwtBearerAuthentication(new JwtBearerOptions
{
    AutomaticAuthenticate = true,
    AutomaticChallenge = true,
    TokenValidationParameters = new TokenValidationParameters
    {
        ValidIssuer = "MySite",
        ValidAudience = "MySite",
        ValidateIssuerSigningKey = true,
        IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes("VERYL0NGKEYV@LUETH@TISSECURE")),
        ValidateLifetime = true
    }
});
Run Code Online (Sandbox Code Playgroud)

用于创建令牌的API

[HttpPost("Token")]
public async Task<IActionResult> CreateToken([FromBody] LoginModel model)
{
    try
    {
        var user = await userManager.FindByNameAsync(model.Email);
        if (passwordHasher.VerifyHashedPassword(user, user.PasswordHash, model.Password) == PasswordVerificationResult.Success)
        {

            var claims = new[]
            { …
Run Code Online (Sandbox Code Playgroud)

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

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

Asp.net核心识别单元测试控制器动作

我在研究如何测试以及测试什么方面遇到了问题.

我有一个控制器注入UserManager并调用该CreateAsync方法来创建一个新用户.

我不想测试Identity用户管理器,因为它已经经过了彻底的测试.我想做的是测试控制器是否运行正确的路径(在我的情况下,有3条路径,发回响应模型状态错误,身份响应错误或简单字符串)

我是否应该尝试创建用户管理器的模拟以创建我的测试(我不确定如何将用户管理器设置为模拟依赖项)其次,如何设置条件以验证控制器是否采用了给定的路径.

我正在使用xUnitMoq.

[Route("api/[controller]")]
public class MembershipController : BaseApiController
{
    private UserManager<ApplicationUser> _userManager;

    public MembershipController(UserManager<ApplicationUser> userManager)
    {
        _userManager = userManager;
    }

    [HttpGet("RegisterNewUser")]
    public HttpResponseMessage RegisterNewUser([FromBody] NewUserRegistration user)
    {
        if (ModelState.IsValid)
        {
            ApplicationUser newUser = new ApplicationUser();
            newUser.UserName = user.username;
            newUser.Email = user.password;
            IdentityResult result = _userManager.CreateAsync(newUser, user.password).Result;

            if (result.Errors.Count() > 0)
            {
                var errors = new IdentityResultErrorResponse().returnResponseErrors(result.Errors);
                return this.WebApiResponse(errors, HttpStatusCode.BadRequest);
            }
        }
        else
        {
            var errors = new ViewModelResultErrorResponse().returnResponseErrors(ModelState);
            return …
Run Code Online (Sandbox Code Playgroud)

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

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

.net核心身份2.1角色授权不起作用

我已经在2.1之前多次实现了基于角色的身份验证。按照步骤搭建新的2.1身份。

我扩展了IdentityUser模型以添加其他字段,登录工作正常,并且存在新字段。

startup.cs配置服务包含

         services.AddDefaultIdentity<AppUser>()
            .AddRoles<IdentityRole>()
            .AddEntityFrameworkStores<ApplicationDbContext>();
Run Code Online (Sandbox Code Playgroud)

我播下了角色

         IdentityRole role = new IdentityRole();
         role.Name = "Administrator";
         IdentityResult roleResult = roleManager.
         CreateAsync(role).Result;
Run Code Online (Sandbox Code Playgroud)

然后创建一个用户并添加到角色中

        AppUser user = new AppUser();
        user.UserName = "Admin";
        user.Email = "admin@admin.com";
        user.Name = "Administrator";
        user.LockoutEnabled = false;
        user.EmailConfirmed = true;

        IdentityResult result = userManager.CreateAsync(user, "password").Result;

        if (result.Succeeded)
        {
            userManager.AddToRoleAsync(user, "Administrator").Wait();
        }
Run Code Online (Sandbox Code Playgroud)

一切都成功了,数据库看起来还不错(AspNetUserRoles有链接)

但是,用角色装饰控制器将始终返回未经授权的状态

       [Authorize(Roles = "Administrator")]
Run Code Online (Sandbox Code Playgroud)

但是,带有[Authorize](无角色)的简单登录检查将起作用。

如何解决此问题/最简单的方法来合并源代码,以便我可以逐步/调试[Authorize]代码?

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

9
推荐指数
2
解决办法
5487
查看次数

将 .NET Core Identity 与 API 结合使用

我创建了一个 API 并从同一 API 设置了 JWT 身份验证(我选择不使用 IdentityServer4)。

我通过这样做services.AddAuthentication

然后我在控制器中创建了令牌并且它起作用了。

不过我现在想添加注册等功能。但我不想编写自己的代码来哈希密码、处理注册电子邮件等。

所以我遇到了 ASP.NET Core Identity,它似乎是我所需要的,除了它添加了一些我不需要的 UI 内容(因为它只是一个 API 和我想要完全独立的 UI)。

但MSDN上是这样写的:

ASP.NET Core Identity 向 ASP.NET Core Web 应用添加用户界面 (UI) 登录功能。要保护 Web API 和 SPA,请使用以下方法之一:

Azure 活动目录

Azure Active Directory B2C(Azure AD B2C)

身份服务器4

那么仅仅使用 Core Identity 来进行 API 的哈希和注册逻辑真的是一个坏主意吗?我不能忽略 UI 功能吗?这非常令人困惑,因为我不想使用 IdentityServer4 或创建自己的用户管理逻辑。

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

9
推荐指数
2
解决办法
3841
查看次数

更改asp.net core 2.2 IdentityUser 的Id类型

我是 dot-net core 2.x 的新手,所以......

我想将 asp.net core 2.2 IdentityUser 中的 Id 类型从 string 更改为 int。

我通过谷歌(以及 stackoverflow 搜索工具)找到的所有示例都为我提供了 asp.net core 2.0 的示例,当您搭建 Identity(2.2 未提供)时,它提供了一个 ApplicationUser。

所以,我不知所措..我尝试的第一件事(我寄予厚望)是:

services.AddDefaultIdentity<IdentityUser<int>>()
  .AddRoles<IdentityRole>()
  .AddDefaultTokenProviders()
  .AddEntityFrameworkStores<ApplicationDbContext>();
Run Code Online (Sandbox Code Playgroud)

但是,当我尝试 Add-Migration InitialCreate -Context ApplicationDbContext 时出现以下错误:

访问类“程序”上的 IWebHost 时出错。在没有应用程序服务提供商的情况下继续。错误:GenericArguments[0], 'Microsoft.AspNetCore.Identity.IdentityUser`1[System.Int32]',在 'Microsoft.AspNetCore.Identity.EntityFrameworkCore.UserStore`9[TUser,TRole,TContext,TKey,TUserClaim,TUserRole, TUserLogin,TUserToken,TRoleClaim]' 违反了类型 'TUser' 的约束

想法?想法?我可以阅读的文档?

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

8
推荐指数
2
解决办法
7161
查看次数

UserManager.FindByEmailAsync 返回 null,但用户存在于数据库中

UserManager.FindByEmailAsync返回null,但该用户存在于数据库中。

下面的代码解释了这个奇怪的问题:

var email = info.Principal.FindFirstValue(ClaimTypes.Email);
var test = new Data.ApplicationDbContext().Users.First(x => x.NormalizedEmail == email);
var usermail = await _userManager.FindByEmailAsync(email);

Console.WriteLine(test == null);      //false
Console.WriteLine(usermail == null);  //true
Run Code Online (Sandbox Code Playgroud)

编辑

同样通过_userManager其自身,可以获得所需的用户:

var test = _userManager.Users.FirstOrDefault(x => x.NormalizedEmail == email);
var usermail = await _userManager.FindByEmailAsync(email);

Console.WriteLine(test == null);      //false
Console.WriteLine(usermail == null);  //true
Run Code Online (Sandbox Code Playgroud)

需要注意的是,用户不是以“常规”方式创建的,而是通过 Data-Seed 创建的(在OnModelCreating):

protected override void OnModelCreating(ModelBuilder builder)
{
    var users = new (string email, string name)[] {
        ("xyz@gmail.com", "admin")
    };

    var …
Run Code Online (Sandbox Code Playgroud)

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

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

无法访问已释放的上下文实例

我的应用程序:使用微服务架构的.Net Core 3.1 Web应用程序;授权和身份验证的身份作为单独的微服务 API。

我使用自定义字段扩展了标准 AspNetUsers 和 AspNetRoles 表。当我尝试使用 Identity RoleManager 创建新角色时出现以下错误。

无法访问已释放的上下文实例。导致此错误的一个常见原因是处置从依赖项注入解析的上下文实例,然后尝试在应用程序的其他位置使用相同的上下文实例。如果您在上下文实例上调用“Dispose”或将其包装在 using 语句中,则可能会发生这种情况。如果您使用依赖项注入,则应该让依赖项注入容器负责处理上下文实例。对象名称:“MembershipDBContext”。

在下面找到我的代码

启动.cs

public void ConfigureServices(IServiceCollection services)
        {
            services.AddControllers();
            var idenConnectionString = Configuration["DbContextSettings:IdentityConnectionString"];
            var userConnectionString = Configuration["DbContextSettings:UserConnectionString"];
            var dbPassword = Configuration["DbContextSettings:DbPassword"];
            var builder = new NpgsqlConnectionStringBuilder(idenConnectionString)
            {
                Password = dbPassword
            };
            var userBuilder = new NpgsqlConnectionStringBuilder(userConnectionString)
            {
                Password = dbPassword
            };

            services.AddDbContext<MembershipDBContext>(opts => opts.UseNpgsql(builder.ConnectionString));
            services.AddDbContext<UserDBContext>(opts => opts.UseNpgsql(userBuilder.ConnectionString));

            

            services.AddIdentity<MembershipUser, MembershipRole>(options =>
            {
                options.Password.RequiredLength = 8;
                options.User.AllowedUserNameCharacters = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-._@+ ";
                options.SignIn.RequireConfirmedEmail = false;
            }).AddRoles<MembershipRole>().AddEntityFrameworkStores<MembershipDBContext>()
            .AddDefaultTokenProviders();


            services.AddTransient<IIdentityMSService, IdentityMSService>();//IdentityMS …
Run Code Online (Sandbox Code Playgroud)

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

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