这是我的注册方法.我将注册方法更改为管理工具.管理工具在没有if语句的情况下正常工作.但是,它不喜欢我寻找现有用户的方式.
// POST: /Account/Register
[HttpPost]
[AllowAnonymous]
[ValidateAntiForgeryToken]
public async Task<ActionResult> Register(RegisterViewModel model)
{
if (ModelState.IsValid)
{
if(_context.Users.Contains(model.UserName))//Errors out here
{
var user = new ApplicationUser { UserName = model.UserName};
user.UserName = model.UserName;
var result = await UserManager.CreateAsync(user, model.Password);
if (result.Succeeded)
{
await this.UserManager.AddToRoleAsync(user.Id, model.Name);
return RedirectToAction("Index","User");
}
AddErrors(result);
}
}
return View(model);
}
Run Code Online (Sandbox Code Playgroud) 我找不到任何可行的解决方案......我尝试了每个谷歌搜索结果.我好几个小时都喜欢这个.
所以我只是将我的新角色插入到SQL表中:
insert into [dbo].[AspNetRoles] ( [Id]
,[ConcurrencyStamp]
,[Name]
,[NormalizedName] )
values(1,NULL,'Admin','Admin') ;
Insert into [dbo].[AspNetUserRoles] ( [UserId]
,[RoleId] )
VALUES('user_id_from_[dbo].[AspNetUsers]' , 1 )
Run Code Online (Sandbox Code Playgroud)
我认为它是如此丑陋而且我能做的最糟糕,但它正在发挥作用.
在SO上是一个标记为解决方案的答案: Asp.Net核心MVC6如何最初在Identity 3中添加角色
但我真的不知道在google中寻找答案如何在Startup.cs中正确初始化roleManager.
我甚至不相信它真的那么难.我想我只是错过了一些线索.
我有一个现有的ASP.net MVC和WebAPI组合网站,该网站使用标准UserManager类使用实体框架执行身份验证。现在,我需要“交换”该身份验证,并使用外部的第三方REST Web服务进行身份验证以及存储和更新用户详细信息。
第三方Web服务具有一个简单的login终结点,该终结点使用用户名和密码,如果登录成功,它将返回令牌。
如果可能的话,我希望AspNetRoles在用户登录后继续使用ASP.net Identity 表来管理用户的角色。
实施此方案的最佳方法是什么?我最初考虑编写一个自定义,UserStore但是假设我可以访问密码哈希,而我没有。我只能使用第三方API端点登录并更新密码,我无法直接访问数据库用户表。
asp.net authentication asp.net-mvc entity-framework asp.net-identity
参考:
使用ASP.NET Core MVC和Visual Studio构建您的第一个Web API
场景:
(a)使用上述链接构建.NET Core 1.0 Web API解决方案.
(b)该解决方案在调试模式下运行.
(c)用户注册
(d)该用户登录后
(e)许多小时后该用户仍然登录
仍然在同一个Debug会话中,执行此代码:
@using Microsoft.AspNetCore.Identity
@inject SignInManager<ApplicationUser> SignInManager
@inject UserManager<ApplicationUser> UserManager
@if (SignInManager.IsSignedIn(User))
{
<form asp-area="" asp-controller="Account" asp-action="LogOff" method="post" id="logoutForm" class="navbar-right">
<ul class="nav navbar-nav navbar-right">
<li>
<a asp-area="" asp-controller="Manage" asp-action="Index" title="Manage">Hello @UserManager.GetUserName(User)!</a>
</li>
<li>
<button type="submit" class="btn btn-link navbar-btn navbar-link">Log off</button>
</li>
</ul>
</form>
}
Run Code Online (Sandbox Code Playgroud)
我未满足的期望是上述用户的登录会超时; 然而,Hello *example user*!又Log off被渲染到导航栏 ; 单击Log off会注销示例用户.
那么如何设置ASP.NET核心标识中的到期时间,以便
(a)登录用户可以在固定时间段(如8小时 …
security login expired-sessions asp.net-identity asp.net-core
我创建了一个名为的表PasswordHistory。每次用户更改密码时,都应将当前密码复制到PasswordHistory表中。该策略是以下2种中最严格的:
我想知道如何将新输入的密码与现有的密码进行比较,但这是散列的?
这是我的代码:
var _limitDate = DateTime.Now.AddYears(-2);
int n = db.PasswordsHistory.Where(pwd => pwd.UserId == userId && pwd.ChangeDate > _limitDate).Count();
var pwdList = new List<PasswordHistory>();
if(n >= 8)
{
pwdList = db.PasswordsHistory
.Where(pwd => pwd.ChangeDate > _limitDate)
.ToList();
}
else
{
pwdList = db.PasswordsHistory
.OrderByDescending(pwd => pwd.ChangeDate)
.Take(8)
.ToList();
}
if (pwdList.Count == 0)
{
return false;
}
else
{
foreach (var pwd in pwdList)
{
//compare the password entered by the user with the password stored …Run Code Online (Sandbox Code Playgroud) 说,我有一个包含用户名/密码的SQL Server数据库.在我的"登录"视图中,我希望在用户名/密码文本字段中输入数据,当我单击"登录"时,我想使用我的登录控制器将这些值与数据库中的值进行比较.所有这些都是相当直接的:

但是,我想[Authorize]在我网站的其余控制器上使用属性.在通过登录页面授予访问权限后,我似乎无法找到任何解释如何"授权"用户的示例,以便["Authorize"]属性识别此用户并允许他们访问其他控制器/操作.以下是我已经开始设置的方法,但我找不到任何方向从这里开始.
public class LoginController : Controller
{
// GET: /<controller>/
//[Route("/Login")]
public ActionResult Index()
{
return View();
}
public bool Login(Workflow.Models.WorkflowContext wfc, string username, string password)
{
var user = wfc.User.Where(u => u.Active && u.Username == username && u.Password == password).ToList();
if (user.Count > 0)
{
//User may log in
return true;
}
else
//Access Denied
return false;
}
}
Run Code Online (Sandbox Code Playgroud)
例如,如果没有用户授权,我不希望他们能够访问我的"家庭控制器":
[Authorize]
public class HomeController : Controller
{
[Route("/Home")]
public ActionResult Index()
{
return …Run Code Online (Sandbox Code Playgroud) 在我的项目中,Admin添加了教师,然后每个教师都会添加他的学生.添加后,他们会收到一封电子邮件,要求他们完成注册.
我的项目中有以下类:
1学生班
Student: int id, int Registry number, int grade, string password, string email, string name
Run Code Online (Sandbox Code Playgroud)
2-Instructor类:
Instructor: int id, string name , string email , string password
Run Code Online (Sandbox Code Playgroud)
3-My database context:
public class InstructorContext:DbContext
{
public InstructorContext() : base("InstructorContext")
{
}
public DbSet<Instructor> Instructors { get; set; }
public DbSet<Student> Students { get; set; }}
Run Code Online (Sandbox Code Playgroud)
当用户进入时,我必须确定他是管理员,讲师还是学生.我是否必须使用基于角色的身份验证?我已经有两个不同角色的单独课程.它们都可以从IdentityUser继承吗?
我试图更好地了解.NET的Identity OnValidateIdentity方法的工作原理。我已经在我的应用程序中设置了这段代码,如下所示:
app.UseCookieAuthentication(new CookieAuthenticationOptions
{
AuthenticationType = DefaultAuthenticationTypes.ApplicationCookie,
LoginPath = new PathString("/Account/Login"),
CookieName = "LoginCookie",
ExpireTimeSpan = TimeSpan.FromHours(1),
Provider = new CookieAuthenticationProvider
{
// Enables the application to validate the security stamp when the user logs in.
// This is a security feature which is used when you change a password or add an external login to your account.
OnValidateIdentity = SecurityStampValidator.OnValidateIdentity<ApplicationUserManager, ApplicationUser>(
validateInterval: TimeSpan.FromHours(1),
regenerateIdentity: (manager, user) => user.GenerateUserIdentityAsync(manager))
}
});
Run Code Online (Sandbox Code Playgroud)
OnValidateIdentity是否在这里起到检查用户何时访问我的网站的作用,以查看其Cookie的年龄以及是否比我在此处设置的Cookie的年龄(1小时)大-用户将被迫重新登录。应用程序。
这到底是怎么运作的?
我有一个使用OpenIddict进行令牌授权(访问和刷新令牌)的应用程序,总体而言,它运行良好.问题是我的用例有多个使用相同授权服务器的应用程序类型(Web和移动).我想为不同类型(可能使用不同的令牌端点)设置不同的到期时间,但我无法找到一种方法来覆盖使用SetAccessTokenLifetime和SetRefreshTokenLifetime设置的值.有没有办法做到这一点?
目标是为Web应用程序设置更长的访问令牌长度,并让用户在到期时重定向到登录(合理的长期到期,例如小时).在移动端,我想使用刷新令牌来保持用户登录.最佳做法似乎表明,在移动设备上我应该有一个非常短的令牌到期(例如分钟),并且刷新令牌到期时间很长.
谢谢你,杰森
尝试使用UserManager CreateAsync方法创建新用户时出现以下错误.我使用的是未经修改的IdentityUser和IdentityRole.我有几个DBSets填充了数据库中的数据,所以阅读不是问题,只是写它似乎.
{System.InvalidOperationException: Connection must be valid and open to commit transaction at MySql.Data.MySqlClient.MySqlTransaction.Commit()
at Microsoft.EntityFrameworkCore.Storage.RelationalTransaction.Commit()
at Microsoft.EntityFrameworkCore.Update.Internal.BatchExecutor.<ExecuteAsync>d__10.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
at Microsoft.EntityFrameworkCore.ChangeTracking.Internal.StateManager.<SaveChangesAsync>d__54.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
at Microsoft.EntityFrameworkCore.ChangeTracking.Internal.StateManager.<SaveChangesAsync>d__52.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
at Microsoft.EntityFrameworkCore.DbContext.<SaveChangesAsync>d__35.MoveNext()
--- End …Run Code Online (Sandbox Code Playgroud) asp.net-identity ×10
asp.net ×4
asp.net-core ×4
asp.net-mvc ×4
c# ×2
security ×2
cookies ×1
login ×1
mysql ×1
openiddict ×1