我可能只是在这里错过了一个简单的技巧,但我在 ASP.NET Core 项目中创建了 Identity 框架,用我自己的类创建了我自己的字段,运行了迁移,然后一旦确认它全部与默认 UI 一起使用。它工作得很好,所以我去自定义身份用户界面,这样我就可以更好地控制特定页面。问题是,我以为我会冒险并选择每个页面进行自定义...是的,我知道很愚蠢..现在我有一些 80 页或我不再想要的东西。
我真的只想搭建注册和管理数据页面的脚手架,如果我再次运行脚手架,是否会简单地创建新页面或因页面已存在而失败,或者会删除我未选择的任何页面?我不愿意尝试,因为害怕破坏某些东西。
也许是因为手动删除了我不想要的页面,但这会导致我未选择自定义的那些页面出现问题。看起来很棒,有一个脚手架选项来创建页面,但是删除它们......这不是那么明显......
customization scaffolding asp.net-core asp.net-core-identity
我想添加自定义策略以进行两步授权,因此在第一步之后,用户将可以访问第二步,然后再访问所有内容。当我有一项政策时,一切正常,但当我添加另一项政策时,我开始收到此错误。我如何添加策略:
AuthorizationOptions authOptions = new AuthorizationOptions();
authOptions.AddPolicy("FirstStepCompleted", policy => policy.RequireClaim("FirstStepCompleted"));
authOptions.AddPolicy("Authorized", policy => policy.RequireClaim("Authorized"));
services.AddAuthorization(o => o = authOptions);
Run Code Online (Sandbox Code Playgroud)
当我有一项政策时,我像这样添加它:
services.AddAuthorization
(
options => options.AddPolicy("FirstStepCompleted",
policy => policy.RequireClaim("FirstStepCompleted"))
);
Run Code Online (Sandbox Code Playgroud)
我究竟做错了什么?
UPD1。忘记了例外:
处理请求时发生未处理的异常。InvalidOperationException:未找到名为“FirstStepCompleted”的 AuthorizationPolicy。Microsoft.AspNetCore.Authorization.AuthorizationPolicy.CombineAsync(IAuthorizationPolicyProviderpolicyProvider,IEnumerableauthorizeData)
我已经设置了我的身份模型,就像这里描述的那样: https: //learn.microsoft.com/en-us/aspnet/core/security/authentication/customize-identity-model ?view=aspnetcore-2.2#add-user-and -角色导航属性
所以我的每个User类都有一个Roles的集合,通过UserRole“包装器”。所有实体关系都已设置。
当我查询我的用户时,我得到每个用户的所有角色(此处使用延迟加载,但“包含”没有区别):
var users = _userManager.Users
.AsNoTracking()
.ToList();
Run Code Online (Sandbox Code Playgroud)
但是,当检查 EF Core 创建的日志时,我发现每个用户都有另一个查询来获取角色:
[Parameters=[@_outer_Id='d550f61b-ed3d-4d90-8e7b-31552de50d3b' (Size = 450)], CommandType='"Text"', CommandTimeout='30']
SELECT [r].[RoleId] AS [Id], [r.Role].[Name], [r.Role].[DisplayName]
FROM [AspNetUserRoles] AS [r]
INNER JOIN [AspNetRoles] AS [r.Role] ON [r].[RoleId] = [r.Role].[Id]
WHERE ([r].[Discriminator] = N'UserRole') AND (@_outer_Id = [r].[UserId])
Run Code Online (Sandbox Code Playgroud)
这会针对数据库中的每个用户 ID 重复进行。
如何仅使用一个查询即可获得结果?
以防万一,我的模型:
public class User : IdentityUser
{
public virtual ICollection<UserRole> UserRoles { get; set; }
}
public class UserRole : IdentityUserRole<string>
{
public virtual User User …Run Code Online (Sandbox Code Playgroud) 对于普通的 MVC 风格网站,我获得了一组可以自定义的 ASP.NET Core Identity 预生成页面。有了它,我可以做一些事情,比如在注册页面上询问用户的年龄。
服务器端 Blazor 的等效项是什么?
将我的网站从 .NET Core 2.2 迁移到 3.1.1 后,我的 api 端点突然开始尝试将我的 api 请求重定向到默认登录页面(/Account/Login?ReturnUrl=,我的任何路由中都没有该页面)。
我的 api 使用 JWT 承载身份验证方案和 JWT 挑战方案,但仍然发生了重定向。
services.AddAuthentication(options =>
{
options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
options.DefaultScheme = JwtBearerDefaults.AuthenticationScheme;
options.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
})
Run Code Online (Sandbox Code Playgroud)
我终于找到了问题的解决方案,但我不知道为什么它实际上有帮助。
最初我的服务设置为:
services
.AddIdentity<IdentityUser, IdentityRole>()
.AddSignInManager()
.AddEntityFrameworkStores<CleWebToolsIdentityDbContext>();
Run Code Online (Sandbox Code Playgroud)
但这确实实现了重定向。
最终解决我的问题的是将它们设置为:
services
.AddIdentityCore<IdentityUser>()
.AddRoles<IdentityRole>()
.AddSignInManager()
.AddEntityFrameworkStores<CleWebToolsIdentityDbContext>();
Run Code Online (Sandbox Code Playgroud)
有人能告诉我这是怎么回事吗?
即使质询方案应该是 JWT,AddIdentity 方法如何导致重定向?
我想从 Identity-table 检索数据dbo.AspNetUsers,但我还没有弄清楚如何查询它。
这是我的数据库上下文:
public class ProjectsDbContext : IdentityDbContext<IdentityUser>
{
public ProjectsDbContext(DbContextOptions<ProjectsDbContext> options) : base(options) { }
public DbSet<Project> Projects { get; set; }
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
if (modelBuilder == null)
{
throw new NullReferenceException();
}
base.OnModelCreating(modelBuilder);
modelBuilder.Entity<Project>()
.HasMany(c => c.ChildProjects)
.WithOne(p => p.ParentProject)
.HasForeignKey(p => p.ParentProjectId);
}
}
Run Code Online (Sandbox Code Playgroud)
这是我的User班级:
public class User : IdentityUser
{
public string FirstName { get; set; }
public string LastName { get; set; }
}
Run Code Online (Sandbox Code Playgroud)
这是我的查询,但不起作用:
List<User> …Run Code Online (Sandbox Code Playgroud) c# entity-framework-core asp.net-core-mvc asp.net-core-identity
在尝试从此处实现答案时>如何在 ASP.NET Core 中获取当前登录的用户 Id 以及用户将我重定向到此处> https://github.com/dotnet/aspnetcore/issues/18348
var UserId = User.FindFirstValue(ClaimTypes.Name);
^ 这不起作用,并打印以下错误'User' does not contain a definition for 'FindFirstValue'
编辑:添加控制器片段
我的控制器的完整片段...
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Logging;
using ProjectName.Processing;
using ProjectName.Repository;
using Newtonsoft.Json;
namespace ProjectName.Controllers
{
[ApiController]
[Route("api/[controller]/[action]")]
public class ClassNameController : ControllerBase
{
private readonly ILogger<ClassNameController> _logger;
private OtherClassNameProcessing proc = new OtherClassNameProcessing();
public ClassNameController(ILogger<ClassNameController> logger)
{
_logger = logger;
}
[HttpGet]
[ProducesResponseType(typeof(List<2ndOtherClassNameRepository>), StatusCodes.Status200OK)]
public IActionResult GetUserName()
{ …Run Code Online (Sandbox Code Playgroud) 我必须根据“钥匙”和“门”的存在来迁移具有自定义授权的应用程序。基本上,许多钥匙被分配给用户,并且该用户不能根据他获得的钥匙做事/打开门。
显而易见的解决方案是转向 ASP.Net Core Identity 的基于声明的授权。每个键都成为一个声明。重点是我想直接检查是否存在开门索赔,而不是保单。这是为了避免编写(很多,因为有数百个键)代码。
所以,从:
Startup.cs:
options.AddPolicy("Key1", policy => policy.RequireClaim("Key1"));
Controller:
[Authorize(Policy = "Key1")]
Run Code Online (Sandbox Code Playgroud)
对于类似的事情:
Controller:
[Authorize(Claim = "Key1")]
Run Code Online (Sandbox Code Playgroud)
实现这一目标的最佳方法是什么?
我使用以下代码添加了声明
var claims = new List<Claim>
{
new Claim(Constants.ClaimTypes.BUSINESS_ID, user.BusinessID.ToString()),
new Claim(Constants.ClaimTypes.NAME, user.FullName),
new Claim(Constants.ClaimTypes.IMAGE, user.ProfileUrl ?? user.LogoUrlEn ?? user.LogoUrlEn ?? ""),
new Claim(Constants.ClaimTypes.EMAIL, user.Email),
new Claim(Constants.ClaimTypes.USER_ID, user.UserID.ToString()),
new Claim(Constants.ClaimTypes.ROLE, user.RoleID.ToString()),
new Claim(Constants.ClaimTypes.RIGHTS, string.Join(',', user.RolesRights.Select(S => $"{S.EntityName}|{S.EntityID}|{S.RightID}")))
};
var claimsIdentity = new ClaimsIdentity(claims, CookieAuthenticationDefaults.AuthenticationScheme);
var authProperties = new AuthenticationProperties
{
AllowRefresh = true,
IsPersistent = true,
RedirectUri = "/Authentication/Login"
};
await HttpContext.SignInAsync(CookieAuthenticationDefaults.AuthenticationScheme,
new ClaimsPrincipal(claimsIdentity),
authProperties);
Run Code Online (Sandbox Code Playgroud)
当有人更新个人资料图片时,我需要更新声明,我需要更新它,我该怎么做?
我尝试了几种解决方案,但没有任何效果。
当有人更新个人资料图片时,必须注销并再次登录才能看到效果。
我有一个ASP.NET Core Web应用程序.用户可以登录,它使用Identity.
我现在正在使用Xamarin构建一个Android应用程序,该应用程序将提供网站的缩小部分 - 从库存中添加/删除产品.
这是登录操作:
[HttpPost]
[AllowAnonymous]
[ValidateAntiForgeryToken]
public async Task<IActionResult> Login(LoginViewModel model, string returnUrl = null)
{
ViewData["ReturnUrl"] = returnUrl;
if (ModelState.IsValid)
{
var result = await _signInManager.PasswordSignInAsync (model.Email, model.Password, model.RememberMe, lockoutOnFailure: true);
if (result.Succeeded)
{
var user = await UserManager.FindByNameAsync( model.Email );
if ( !user.IsApproved ) {
await _signInManager.SignOutAsync();
_logger.LogWarning(2, "User account not approved.");
return RedirectToAction("NotApproved");
}
AddAutoLogoutCookie();
_logger.LogInformation(1, "User logged in.");
return RedirectToLocal(returnUrl);
}
if (result.RequiresTwoFactor)
{
return RedirectToAction("VerifyCode", new { Provider = AppSettings.GoogleAuthenticatorProviderName, ReturnUrl …Run Code Online (Sandbox Code Playgroud)