标签: asp.net-identity-2

在Db Initializer的Seed方法中创建Asp.net Identity用户

我先用EF 6代码创建了我的数据层,然后通过继承SeedEvInitializer类方法填充db DropCreateDatabaseIfModelChanges.Seed方法的实现是

protected override void Seed(EvContext context)
{
   //Add other entities using context methods
   ApplicationUserManager manager = new ApplicationUserManager(new UserStore<ApplicationUser>(context));
   var user = new ApplicationUser { Email = "admin@myemail.com" ,UserName = "admin@myemail.com"};
   var result = await manager.CreateAsync(user, "Temp_123");//this line gives error. obviously await cannot be used in non- async method and I cannot make Seed async
}
Run Code Online (Sandbox Code Playgroud)

我的问题是我如何Seed使用UserManager类在方法中添加用户.当我更改 var result = awit manager.CreateAsync(user, "Temp_123");

var result = …

entity-framework entity-framework-6 asp.net-identity asp.net-identity-2

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

身份2的种子数据库

我遇到了使用Identity v2为数据库播种的问题.我将IdentityModel从MVC5项目分离到我的数据访问层,我也设置了EF迁移.所以我注释掉了在"IdentityConfig.cs"中使用的代码来创建初始用户并将代码放在我的种子数据库中,看起来像这样

  protected override void Seed(Repository.DataContext.IdentityDb context)
        {

            //    var userManager = HttpContext.Current.GetOwinContext().GetUserManager<ApplicationUserManager>();
            //    var roleManager = HttpContext.Current.GetOwinContext().Get<ApplicationRoleManager>();
            var owinContext = new OwinContext();
            var userManager = owinContext.GetUserManager<ApplicationUserManager>();
            var roleManager = owinContext.Get<ApplicationRoleManager>();
            const string name = "admin@admin.com";
            const string password = "Admin@123456";
            const string roleName = "Admin";

            //    //Create Role Admin if it does not exist
            var role = roleManager.FindByName(roleName);
            if (role == null)
            {
                role = new IdentityRole(roleName);
                var roleresult = roleManager.Create(role);
            }

            var user = userManager.FindByName(name);
            if (user == …
Run Code Online (Sandbox Code Playgroud)

c# asp.net-identity-2

15
推荐指数
1
解决办法
6369
查看次数

没有实体框架的ASP.NET Identity 2.0实现

是否存在不使用Entity Framework的ASP.NET Identity 2.0的自定义实现?我希望有些东西不会使用完整的ORM,但是就像Dapper那样.我问的原因是因为我没有在项目的其他任何地方使用Entity Framework,所以如果可能的话我想远离它.

我知道我可以自己实施,但我没有多余的时间花在这上面.

asp.net-identity-2

15
推荐指数
1
解决办法
8338
查看次数

确认电子邮件中的aspnet身份无效令牌

我正在尝试确认帐户,但我收到"无效令牌".错误.

这是我正在尝试的:

var code = await UserManager.GenerateEmailConfirmationTokenAsync(user.Id);
var callbackUrl = Url.Action("ConfirmacaoEmail", "Usuario", new { userId = user.Id, code = code }, protocol: Request.Url.Scheme);

await UserManager.SendEmailAsync(user.Id, "Ativação de Conta", user.GetEmailAtivacao(model.Nome, callbackUrl));
Run Code Online (Sandbox Code Playgroud)

如果我UserManager.ConfirmEmailAsync在此代码后拨打电话,我可以确认该帐户.但是,如果我打开它在变量callbackUrl中的链接并尝试通过该操作确认,我收到错误.

我认为它可能是OwinContext的东西,所以我决定打电话HttpContext.GetOwinContext().GetUserManager<MyCustomUserService>但是我得到了同样的错误.

有线索吗?

asp.net-mvc-5 asp.net-identity asp.net-identity-2

15
推荐指数
2
解决办法
8399
查看次数

通过ASP.NET身份2中的UserManager.Update()更新用户

ASP.NET Identity 2在一个MVC 5项目中使用,我想Student通过使用UserManager.Update()方法更新数据.但是,当我从ApplicationUser类继承时,我需要在调用update方法之前映射StudentApplicationUser.另一方面,当使用我也用于创建新Student的方法时,由于并发性而导致错误,因为我创建了一个新实例而不是更新.由于我无聊使用解决问题AutoMapper,我需要一个稳定的解决方案来解决问题AutoMapper.能否请您澄清如何解决这个问题?我将StudentViewModel控制器中的Update方法传递给我,然后我需要将它映射到Student,然后将它们传递给UserManager.Update()方法ApplicationUser.另一方面,我想知道我是否应该在Controller阶段检索并发送密码,而不是为安全问题转到View?你能否告诉我这个问题(在用户更新期间我不更新密码,我必须在数据库中保留用户的密码).任何帮助,将不胜感激.

实体类:

public class ApplicationUser : IdentityUser<int, ApplicationUserLogin,
                                     ApplicationUserRole, ApplicationUserClaim>, IUser<int>
{
    public string Name { get; set; }
    public string Surname { get; set; } 
    //code omitted for brevity
}

public class Student: ApplicationUser
{     
    public int? Number { get; set; }
}
Run Code Online (Sandbox Code Playgroud)


控制器:

[HttpPost]
[ValidateAntiForgeryToken]
public JsonResult Update([Bind(Exclude = null)] StudentViewModel …
Run Code Online (Sandbox Code Playgroud)

c# asp.net-mvc automapper asp.net-identity asp.net-identity-2

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

使用MVC和ASP.NET身份进行URL授权

我想保护我的应用程序中的特定文件夹和资源,这些文件夹和资源位于我的mvc应用程序的路由之外.我希望这些资源仅供经过身份验证的用户使用(只要经过身份验证,该角色就不具备这些角色).

最初似乎UrlAuthorizationModule就是答案.我按照本文,了解IIS 7.0 URL授权,我可以让模块工作,因为它响应了中的配置元素web.config.

我目前的问题是,我认为它是基于IIS中的匿名用户而不是asp.net身份中经过身份验证的用户制定的规则.

测试环境

我使用标准html文件进行测试,而不是尝试加载脚本,因为这也会在MVC管道之外加载.

  • Visual Studio 2015.
    • 新的默认.net 4.6.2Web项目
    • MVC模板
    • 验证= Individual User Accounts
  • IIS 8(用于在Visual Studio外部进行测试)
    • 身份验证 - >匿名身份验证(已启用)

添加 web.config

<configuration>
...
<location path="Data">
  <system.webServer>
    <security>
      <authorization>
        <clear/>
        <add accessType="Deny" users="*"/>
        <add accessType="Allow" users="?"/>
      </authorization>
    </security>
  </system.webServer>
</location>
...
</configuration>
Run Code Online (Sandbox Code Playgroud)

添加到文件夹结构

/Data/Protected.html // this file just has some basic Hello World content to display so …
Run Code Online (Sandbox Code Playgroud)

asp.net asp.net-mvc asp.net-authorization asp.net-identity-2

15
推荐指数
1
解决办法
3682
查看次数

将用户名和姓名添加到ASP.NET标识2?

我转而使用新的ASP.NET Identity 2.我实际上使用的是Microsoft ASP.NET Identity Samples 2.0.0-beta2.

任何人都可以告诉我在哪里以及如何修改代码,以便它存储用户的名字和姓氏以及用户详细信息.这现在是否是索赔的一部分,如果是,我怎么能添加它?

我假设我需要在这里添加这个帐户控制器中的寄存器方法:

        if (ModelState.IsValid)
        {
            var user = new ApplicationUser { UserName = model.Email, Email = model.Email };
            var result = await UserManager.CreateAsync(user, model.Password);
            if (result.Succeeded)
            {
                var code = await UserManager.GenerateEmailConfirmationTokenAsync(user.Id);
                var callbackUrl = Url.Action("ConfirmEmail", "Account", new { userId = user.Id, code = code }, protocol: Request.Url.Scheme);
                await UserManager.SendEmailAsync(user.Id, "Confirm your account", "Please confirm your account by clicking this link: <a href=\"" + callbackUrl + "\">link</a>");
                ViewBag.Link = callbackUrl;
                return View("DisplayEmail");
            } …
Run Code Online (Sandbox Code Playgroud)

c# asp.net-identity asp.net-identity-2

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

web.config httpErrors部分和WebAPI区域可以共存吗?

我有一个ASP.net MVC 5项目,其中包含特定"API"区域中的WebAPI.我在我的web.config中启用了IIS7错误处理,如下所示:

<system.webServer>
    <httpErrors errorMode="Custom" existingResponse="Replace">
        <remove statusCode="400" subStatusCode="-1" />
        <remove statusCode="404" subStatusCode="-1" />
        <remove statusCode="500" subStatusCode="-1" />
        <error statusCode="400" path="400.html" responseMode="File" />
        <error statusCode="404" path="404.html" responseMode="File" />
        <error statusCode="500" path="500.html" responseMode="File" />
    </httpErrors>
</system.webServer>
Run Code Online (Sandbox Code Playgroud)

当发生404/500等时,这向MVC网站的用户显示友好消息.当从WebAPI返回特定(合法)状态代码时(例如,调用`/ api/token'时为400),我的问题就出现了.在这些情况下,响应的JSON内容被IIS截获,我的友好消息HTML作为响应返回,而不是来自WebAPI的原始JSON.是否可以从IIS错误处理中排除'API'区域?如果无法做到这一点,那么允许ASP.net MVC网站友好消息和WebAPI JSON响应共存的正确解决方案是什么?

asp.net-mvc iis-7 json asp.net-web-api asp.net-identity-2

14
推荐指数
1
解决办法
5433
查看次数

OWIN承载令牌认证

我有一些与Bearer Token有关的问题.在Owin你可以保护这样的票Protect(ticket):

ClaimsIdentity identity = new ClaimsIdentity(Startup.OAuthServerOptions.AuthenticationType);

identity.AddClaim(new Claim(ClaimTypes.Name, user.UserName));

 Dictionary<string, string> properties = new Dictionary<string, string>();
 properties.Add("UserId", user.Id);
 properties.Add("UserName", user.UserName);
 properties.Add("Role", "user");

 AuthenticationProperties properties = new AuthenticationProperties(properties);

 AuthenticationTicket ticket = new AuthenticationTicket(identity, properties);


 DateTime currentUtc = DateTime.UtcNow;

 DateTime expireUtc = currentUtc.Add(TimeSpan.FromHours(24));

 ticket.Properties.IssuedUtc = currentUtc;
 ticket.Properties.ExpiresUtc = expireUtc;


 string token = OAuthAuthorizationServerOptions.AccessTokenFormat.Protect(ticket)
Run Code Online (Sandbox Code Playgroud)

现在令牌将是这样的:

nqak-9R6U64Owsm_lqn_mJzKc_Djd8iVnIw0EX77v5x2rybhf4m_zg_UnrsoO5BxDZQl0HWrSvvd4efa4ChNSf5rAGhd13aOXZlvwOJOZ5v_9bhRCq8A7tqHyiM6DqVVOyYs3lh2SU-wU1m85HH2IcYDtdTY3ijaKZ_QnP1nsqO5LRnnEL4upbETPW9zqWIZzZBX7_Y2cXi2v0K7WnlRor3gFKIZlU9J-NfidRpWXqq5744NfWWHalYADGS7eUWyuxPJCj9ykHYzaXFksJEXBw

我的问题:

  • 如何生成/加密此令牌?

  • 是否有人可以尝试使用令牌进行混乱并添加一些自定义声明?

例:

如果您有令牌字符串,则可以执行以下操作:

AuthenticationTicket ticket = OAuthAuthorizationServerOptions.AccessTokenFormat.Unprotect(token);
Run Code Online (Sandbox Code Playgroud)

现在,您可以向其添加自定义声明.例如,如果存在role具有值的声明,user则可以修改该声明并添加admin然后重新编码故障单,并获得具有管理员角色的令牌.

我实际上做了一些测试,在服务器上编码一个令牌然后尝试在另一个系统上修改它,但我不能Unprotect.因此,我想也许使用最初创建的机器密钥对票证进行加密/解密.但是,如果我尝试Unprotect从同一台机器上运行它.我可以解密并修改它.

有人可以解释一下这个过程吗?

c# oauth-2.0 owin bearer-token asp.net-identity-2

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

每次请求都调用ApplicationUserManager.Create

我正在使用asp.net mvc 5与外部提供商owin提供(facebook,twitter)

每次请求都会调用ApplicationUserManager.Create.登录用户有很多不必要的东西(密码验证器配置或短信和电子邮件服务配置....)

var manager = new ApplicationUserManager(new UserStore<ApplicationUser>(context.Get<ApplicationDbContext>()));
            // Configure validation logic for usernames
            manager.UserValidator = new UserValidator<ApplicationUser>(manager)
            {
                AllowOnlyAlphanumericUserNames = true,
                RequireUniqueEmail = true
            };

            // Configure validation logic for passwords
            manager.PasswordValidator = new PasswordValidator
            {
                RequiredLength = 7,
                RequireNonLetterOrDigit = false,
                RequireDigit = true,
                RequireLowercase = true,
                RequireUppercase = true,
            };
...
Run Code Online (Sandbox Code Playgroud)

此外,我认为这与此有关

public partial class Startup
    {    
        public void ConfigureAuth(IAppBuilder app)
      // Configure the db context, user manager and signin manager to use a  single …
Run Code Online (Sandbox Code Playgroud)

c# asp.net asp.net-mvc asp.net-identity-2

14
推荐指数
1
解决办法
891
查看次数