我在用 @model IEnumerable<WebApplication.Models.ApplicationUser>
视图
@foreach (var user in Model)
{
<tr>
<td>
@foreach(var role in user.Roles){
role.Name; //invalid
role.RoleId; //valid
role.UserId; //valid
}
</td>
</tr>
}
Run Code Online (Sandbox Code Playgroud)
模型
public class ApplicationUser : IdentityUser
{
[Required]
public string FirstName { get; set; }
[Required]
public string LastName { get; set; }
public async Task<ClaimsIdentity> GenerateUserIdentityAsync(UserManager<ApplicationUser> manager)
{
// Note the authenticationType must match the one defined in CookieAuthenticationOptions.AuthenticationType
var userIdentity = await manager.CreateIdentityAsync(this, DefaultAuthenticationTypes.ApplicationCookie);
// Add custom user claims here
return userIdentity; …Run Code Online (Sandbox Code Playgroud) 我最近开始使用 MVC 5 和 Identity 2.0 开发一个新应用程序,为了使用不同的密码散列算法,我实现了本指南中详述的自定义标识 ( https://code.msdn.microsoft.com/ASPNET-45- MVC5-Custom-1a94ab26#content)。
我已经研究了将角色合并到这个身份实现中的各种方法,但到目前为止还没有找到一种方法让它们与这个新的身份实现一起工作。
现在有没有人指导如何向类似的自定义身份提供者添加角色?
任何指导将不胜感激。
在脚手架局部视图_Layout.cshtml内定义了应用程序的导航栏。我想对其进行修改,以便仅当登录用户为时才显示某些链接"Admin"。
在Seed()我的Configuration.cs文件迁移方法中,定义了以下内容:
bool AddUserAndRole(ApplicationDbContext context) {
IdentityResult ir;
var rm = new RoleManager<IdentityRole>(new RoleStore<IdentityRole>(context));
ir = rm.Create(new IdentityRole("Admin"));
var um = new UserManager<ApplicationUser>(new UserStore<ApplicationUser>(context));
var user = new ApplicationUser() { UserName = "admin", FirstName = "System", LastName = "Administrator" };
ir = um.Create(user, "admin");
if(ir.Succeeded == false) {
return ir.Succeeded;
}
ir = um.AddToRole(user.Id, "Admin");
return ir.Succeeded;
}
Run Code Online (Sandbox Code Playgroud)
如您所见,有一个名为“ Admin”的角色,新创建的用户已添加到该角色。
话虽这么说,我已经试过几种方法里我_Layout.cshmtl试图确定当前用户是否是"Admin"与否
@if(Roles.IsUserInRole(User.Identity.Name, "Admin")) { }
@if (User.IsInRole("Admin")) { …Run Code Online (Sandbox Code Playgroud) 我最近在 MVC 网站中实现了 asp.net identity 2。我按照这里的演练将我的 pk 更改为 INT Here
一切似乎都很好,我可以按如下方式将用户分配给角色:
var result = await userManager.AddToRoleAsync(User.Identity.GetUserId<int>(), "Edit");
Run Code Online (Sandbox Code Playgroud)
但是,我使用 Authorize 属性和在操作方法上指定的角色的那一刻,例如:
[HttpPost]
[ValidateAntiForgeryToken]
[Authorize(Roles = "Edit")]
public async Task<ActionResult> Edit(UdlDownload model)
Run Code Online (Sandbox Code Playgroud)
我收到以下错误:
The user instance login flag is not supported on this version of SQL Server. The connection will be closed.
Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the …Run Code Online (Sandbox Code Playgroud) 我有非典型的情况来验证密码的最大长度要求.我正在尝试调整密码验证器以达到我的要求,但密码的最大长度是我遇到的问题.这是我的密码验证器看起来像.
manager.PasswordValidator = new PasswordValidator
{
RequiredLength = 6,
RequireNonLetterOrDigit = false, //Overrode per requirement
RequireDigit = true,
RequireLowercase = true,
RequireUppercase = true,
MaxLength = 10 //TODO:Max length requirement
};
Run Code Online (Sandbox Code Playgroud)
有人能帮我一下吗?看起来我需要定义一些自定义验证器.
我已经扩展了Asp.net Identity 2模型,通过跟随这样和这样的帖子来使用整数键.但是,这行代码始终返回0.
User.Identity.GetUserId<int>()
Run Code Online (Sandbox Code Playgroud)
即使User.Identity.IsAuthenticated为true且User.Identity.GetUserName()返回正确的用户名.我已经看过这篇文章,但它没有帮助,因为我已经在控制器方法中调用User.Identity.GetUserId()而不是构造函数.该帖子中对"getUserIdCallback"的引用很有意思,也许我需要这样的东西.任何帮助深表感谢.
我尝试了很多搜索,然后尝试了其他选项,但似乎没有任何效果。
我正在使用ASP.net Identity 2.0,并且具有UpdateProfileViewModel。更新用户信息时,我想将UpdateProfileViewModel映射到ApplicationUser(即,身份模型)。但是我想保留这些值,我是从用户数据库中获得的。即用户名和电子邮件地址,不需要更改。
我试着做:
Mapper.CreateMap<UpdateProfileViewModel, ApplicationUser>()
.ForMember(dest => dest.Email, opt => opt.Ignore());
Run Code Online (Sandbox Code Playgroud)
但是映射后我仍然将Email设置为null:
var user = await UserManager.FindByIdAsync(User.Identity.GetUserId());
user = Mapper.Map<UpdateProfileViewModel, ApplicationUser>(model);
Run Code Online (Sandbox Code Playgroud)
我也试过了,但是没有用:
public static IMappingExpression<TSource, TDestination> IgnoreAllNonExisting<TSource, TDestination>(this IMappingExpression<TSource, TDestination> expression)
{
var sourceType = typeof(TSource);
var destinationType = typeof(TDestination);
var existingMaps = Mapper.GetAllTypeMaps().First(x => x.SourceType.Equals(sourceType) && x.DestinationType.Equals(destinationType));
foreach (var property in existingMaps.GetUnmappedPropertyNames())
{
expression.ForMember(property, opt => opt.Ignore());
}
return expression;
}
Run Code Online (Sandbox Code Playgroud)
然后:
Mapper.CreateMap<UpdateProfileViewModel, ApplicationUser>()
.IgnoreAllNonExisting();
Run Code Online (Sandbox Code Playgroud) asp.net automapper asp.net-mvc-5 asp.net-identity asp.net-identity-2
我正在使用 Asp.net Identity 框架进行身份验证。现在我需要来自 connectionId 或已连接用户角色的已连接客户端的用户 ID。
我在登录时使用Claim。但它告诉我这个错误
http://schemas.xmlsoap.org/ws/2005/05/identity/claims/nameidentifier提供的ClaimsIdentity中没有类型的声明。
如何解决呢?
public class MvcApplication : System.Web.HttpApplication
{
protected void Application_Start()
{
AreaRegistration.RegisterAllAreas();
FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
RouteConfig.RegisterRoutes(RouteTable.Routes);
BundleConfig.RegisterBundles(BundleTable.Bundles);
//AntiForgeryConfig.UniqueClaimTypeIdentifier = ClaimTypes.Email;
AntiForgeryConfig.UniqueClaimTypeIdentifier = ClaimTypes.NameIdentifier;
}
}
Run Code Online (Sandbox Code Playgroud)
。
public async Task<ActionResult> Login(LoginViewModel model, string returnUrl)
{
if (!ModelState.IsValid)
{
return View(model);
}
var identity =new ClaimsIdentity(new[] { new Claim(ClaimTypes.Name, model.Email) }, DefaultAuthenticationTypes.ApplicationCookie,
ClaimTypes.Name, ClaimTypes.Role);
identity.AddClaim(new Claim(ClaimTypes.Name, model.Email));
identity.AddClaim(new Claim(ClaimTypes.Role, "Admin"));
identity.AddClaim(new Claim(ClaimTypes.Sid, "123"));
AuthenticationManager.SignIn(new AuthenticationProperties
{
IsPersistent = model.RememberMe
}, identity);
return RedirectToLocal(returnUrl);
}
Run Code Online (Sandbox Code Playgroud)
更新资料
我正在使用此代码进行登录.用户登录时如何找到用户角色?
[HttpPost]
[AllowAnonymous]
[ValidateAntiForgeryToken]
public async Task<ActionResult> Login(LoginViewModel model, string returnUrl)
{
if (!ModelState.IsValid)
{
return View(model);
}
var user = await UserManager.FindByNameAsync(model.Username);
if (user != null)
{
if (!await UserManager.IsEmailConfirmedAsync(user.Id))
{
ViewBag.errorMessage = "You must have a confirmed email to log on.";
return View("Error");
}
}
var result = await SignInManager.PasswordSignInAsync(model.Username, model.Password, model.RememberMe, shouldLockout: false);
switch (result)
{
case SignInStatus.Success:
return RedirectToLocal(returnUrl);
case SignInStatus.LockedOut:
return View("Lockout");
case SignInStatus.RequiresVerification:
return RedirectToAction("SendCode", new { ReturnUrl = returnUrl, RememberMe = model.RememberMe }); …Run Code Online (Sandbox Code Playgroud) asp.net asp.net-mvc identity asp.net-identity asp.net-identity-2