标签: asp.net-core-identity

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
查看次数

Asp.net Core按用户ID获取用户

使用Asp.net核心身份和实体框架核心,如何通过它的UserId属性获取asp.net用户对象?我知道可以使用以下方法从HttpContext.User对象获取当前登录用户:

UserManager.GetUserAsync(HttpContext.User)
Run Code Online (Sandbox Code Playgroud)

但是,当管理员登录时,我希望他们能够访问/修改任何用户的数据,以便更新用户电子邮件和PhoneNumbers,默认情况下,这些用户电子邮件和电话号码是asp.net用户对象的一部分.

理想情况下,我希望能够做到这样的事情:

var userRecord = _userManager.GetUserById(model.userId);
//update user record
userRecord.Email = model.Email;
userRecord.PhoneNumber = model.PhoneNumber;

var newRecord = await _userManager.UpdateAsync(userRecord);
Run Code Online (Sandbox Code Playgroud)

但很明显,UserManager.GetUserById()方法目前不存在.

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

10
推荐指数
2
解决办法
6800
查看次数

根据ASP.NET Core中请求标头中提供的API密钥授权用户

我正在尝试重写我目前在ASP.NET Core中为ASP.NET 4.6提供的一些授权.

我知道Authorization已经发生了一些变化,我发现很难在ASP.NET Core中实现我非常简单的auth策略.

我的要求:

对服务器的每个请求都应包含一个名为"key"的标头.根据该密钥的值,我将能够查询数据库并检查该密钥是代表普通用户还是管理员用户.如果请求不包含有效密钥,则不会授权该请求.

我将如何在ASP.NET Core中实现它?我发现的每一个例子对我的需求来说都显得过于苛刻.

在ASP.NET 4.6中,我使用自己的自定义AuthorizeAttributes在我的控制器上使用,例如

[User]
public IHttpActionResult DoSomethingOnlyUsersCanDo() {}
Run Code Online (Sandbox Code Playgroud)

[Admin]
public IHttpActionResult DoSomethingOnlyAdminsCanDo() {}
Run Code Online (Sandbox Code Playgroud)

我可以在ASP.NET Core中执行相同的操作吗?

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

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

ASP.NET Identity UserManager UpdateAsync删除角色

我们的应用程序中有一个屏幕,允许管理员角色的成员编辑用户帐户详细信息.

最终,任何用户对象都将发送到服务器并使用以下方式进

await userManager.UpdateAsync(user);
Run Code Online (Sandbox Code Playgroud)

这正在按预期更新用户记录.我们可以对数据库进行持久更改,例如用户名,电话号码等.

我看到的问题是,有时更新角色而不是向用户添加其他角色时,它会删除所有角色.

在我们的ApplicationUser对象上,我们有这样的属性:

public virtual ICollection<IdentityUserRole<string>> Roles { get; set; } = new List<IdentityUserRole<string>>();
Run Code Online (Sandbox Code Playgroud)

因此,我们可以在客户端和服务器之间作为用户对象的一部分进行反弹.

我正在努力理解的是userManager.UpdateAsync(user);我所看到的方法的不一致行为.它显然有效,或者永远无法向用户添加任何角色.

到达服务器的对象每次提交时都会正确填充角色.基本流程是:

  1. 添加角色并提交
  2. 该角色正确添加到用户
  3. 添加其他角色并提交
  4. 所有角色都被删除

如何防止它删除角色?

谢谢!

UPDATE

正如@amirani的答案中详述的那样,我尝试过滤现有的列表.我已经设置AutoMapper完全忽略该属性.

.ForMember(x => x.Roles, opt => opt.Ignore());
Run Code Online (Sandbox Code Playgroud)

我现在只是像这样过滤(目前仅添加):

foreach (var userDtoRole in userDto.Roles)
{
  if (user.Roles.FirstOrDefault(x => x.RoleId == userDtoRole) == null)
  {
    user.Roles.Add(new IdentityUserRole<string> {RoleId = userDtoRole, UserId = user.Id });
  }
}
Run Code Online (Sandbox Code Playgroud)

其他角色永远不会添加到基础数据库.我已经确认在执行UpdateUser方法之前,正在更新的用户对象具有正确的角色列表.

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

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

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
查看次数

我们可以在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 Core 2 API调用被重定向(302)

我正在尝试将此项目https://github.com/asadsahi/AspNetCoreSpa从.net core 1.1 迁移 到2.0,但在成功登录后出现问题.登录后我的GET api调用例如https:// localhost:44331/api/profile/test结束重定向(302),我不知道为什么.我收到了持票人令牌,看起来不错.

请求标头格式:授权:承载[令牌]

[Route("api/[controller]")]
public class ProfileController : BaseController
{
    private readonly UserManager<ApplicationUser> _userManager;
    private readonly ILogger _logger;

    public ProfileController(ILoggerFactory loggerFactory, UserManager<ApplicationUser> userManager)
    {
        _logger = loggerFactory.CreateLogger<ProfileController>();
        _userManager = userManager;
    }

    [HttpGet("test")]
    public async Task<IActionResult> Test()
    {
        return  Json(ModelState.GetModelErrors());
    }
}

[Authorize]
[ServiceFilter(typeof(ApiExceptionFilter))]
[ResponseCache(Location = ResponseCacheLocation.None, NoStore = true)]
public class BaseController : Controller
{
    public BaseController()
    {
    }
}
Run Code Online (Sandbox Code Playgroud)

Startup.cs:

public void ConfigureServices(IServiceCollection services)
{
    if (_hostingEnv.IsDevelopment())
    {
        services.AddSslCertificate(_hostingEnv);
    } …
Run Code Online (Sandbox Code Playgroud)

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

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

.NET核心身份与IdentityServer4

问题:我应该使用.Net Core Identity或IdentityServer 4 with Identity

我需要使用登录/注册功能构建应用程序,并允许用户使用API​​从我的软件导入/导出数据.我也希望有外部登录,如谷歌,推特等.

而且我无法理解为什么在只使用Identity可以完成所有事情时我需要Identity Server.

我为什么需要或想要IdentityServer?我只需要尽可能简单地完成工作.

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

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

HTTP错误500.30-ASP.NET Core 2.2中的ANCM进程内启动失败错误

我正在配置此应用程序, 确认帐户并在ASP.NET Core中恢复密码, 但出现错误:

HTTP错误500.30-ANCM进程内启动失败导致此问题的常见原因:应用程序无法启动应用程序已启动但随后停止应用程序已启动但在启动过程中引发了异常故障排除步骤:检查系统事件日志中是否有错误消息启用日志记录功能应用程序进程的stdout消息将调试器附加到应用程序进程,并在IdentityHostingStartup中替换此代码时检查http 500

下面是我的配置:

[assembly: HostingStartup(typeof(Misioneros.Stella.Maris.Web.Areas.Identity.IdentityHostingStartup))]
namespace Misioneros.Stella.Maris.Web.Areas.Identity
{
    public class IdentityHostingStartup : IHostingStartup
    {
        public void Configure(IWebHostBuilder builder)
        {
            builder.ConfigureServices((context, services) => {
                services.AddDbContext<ApplicationDbContext>(options =>
                    options.UseSqlServer(
                        context.Configuration.GetConnectionString("DefaultConnection")));

                services.AddDefaultIdentity<IdentityUser>(config =>
                {
                    config.SignIn.RequireConfirmedEmail = true;
                })
                    .AddEntityFrameworkStores<ApplicationDbContext>();
            });
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

知道是什么问题吗?

asp.net-core asp.net-core-identity asp.net-core-2.2

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