Microsoft.AspNet.Identity 2.0 用账号或者邮件作为登陆方式

创建一个默认的MVC4.0的项目工程,默认的登陆方式是邮件登陆,那么有没办法改为用账号登陆?

我们来看下默认的登陆Action

        [AllowAnonymous]
        [ValidateAntiForgeryToken]
        public async Task<ActionResult> Login(LoginViewModel model, string returnUrl)
        {
            if (!ModelState.IsValid)
            {
                return View(model);
            }// This doesn‘t count login failures towards account lockout
            // To enable password failures to trigger account lockout, change to shouldLockout: true
            var result = await SignInManager.PasswordSignInAsync(model.Email, 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 });
                case SignInStatus.Failure:
                default:
                    ModelState.AddModelError("", "Invalid login attempt.");
                    return View(model);
            }
        }

其中最重要的一个函数

var result = await SignInManager.PasswordSignInAsync(model.Email, model.Password, model.RememberMe, shouldLockout: false);

反编译后,查看源码中标志的红色代码,FindByNameAsync(userName)

// Microsoft.AspNet.Identity.Owin.SignInManager<TUser, TKey>
// Token: 0x06000069 RID: 105 RVA: 0x00005858 File Offset: 0x00003A58
public virtual async Task<SignInStatus> PasswordSignInAsync(string userName, string password, bool isPersistent, bool shouldLockout)
{
    SignInStatus result;
    if (this.UserManager == null)
    {
        result = SignInStatus.Failure;
    }
    else
    {
        TUser tUser = await this.UserManager.FindByNameAsync(userName).WithCurrentCulture<TUser>();
        if (tUser == null)
        {
            result = SignInStatus.Failure;
        }
        else if (await this.UserManager.IsLockedOutAsync(tUser.Id).WithCurrentCulture<bool>())
        {
            result = SignInStatus.LockedOut;
        }
        else if (await this.UserManager.CheckPasswordAsync(tUser, password).WithCurrentCulture<bool>())
        {
            await this.UserManager.ResetAccessFailedCountAsync(tUser.Id).WithCurrentCulture<IdentityResult>();
            result = await this.SignInOrTwoFactor(tUser, isPersistent).WithCurrentCulture<SignInStatus>();
        }
        else
        {
            if (shouldLockout)
            {
                await this.UserManager.AccessFailedAsync(tUser.Id).WithCurrentCulture<IdentityResult>();
                if (await this.UserManager.IsLockedOutAsync(tUser.Id).WithCurrentCulture<bool>())
                {
                    result = SignInStatus.LockedOut;
                    return result;
                }
            }
            result = SignInStatus.Failure;
        }
    }
    return result;
}

=。=! 聪明如你,应该想到了,默认的方式只是查询Email

按照我们的需求是 用户输入账号或者邮箱就能登陆了,我的解决方式是

public static class IdentityExtension
    {
        public static async Task<ApplicationUser> FindByNameOrEmailAsync
            (this UserManager<ApplicationUser> userManager, string usernameOrEmail, string password)
        {
            var username = usernameOrEmail;
            if (usernameOrEmail.Contains("@"))
            {
                var userForEmail = await userManager.FindByEmailAsync(usernameOrEmail);
                if (userForEmail != null)
                {
                    username = userForEmail.UserName;
                }
            }
            return  await userManager.FindByNameAsync(username);
        }
    }

在Action中直接使用

[HttpPost]
        [AllowAnonymous]
        [ValidateAntiForgeryToken]
        public async Task<ActionResult> Login(LoginViewModel model, string returnUrl)
        {
            if (!ModelState.IsValid)
            {
                return View(model);
            }
            var user = await UserManager.FindByNameOrEmailAsync(model.PasspotOrEmail, model.Password);
            // This doesn‘t count login failures towards account lockout
            // To enable password failures to trigger account lockout, change to shouldLockout: true
            SignInStatus result = SignInStatus.Failure;
            if(user!=null)
                result = await SignInManager.PasswordSignInAsync(user.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 });
                case SignInStatus.Failure:
                default:
                    ModelState.AddModelError("", "Invalid login attempt.");
                    return View(model);
            }
        }

扩展一下,用手机号登陆也可以的哦!

时间: 2024-12-31 07:02:39

Microsoft.AspNet.Identity 2.0 用账号或者邮件作为登陆方式的相关文章

从Microsoft.AspNet.Identity看微软推荐的一种MVC的分层架构

Microsoft.AspNet.Identity简介 Microsoft.AspNet.Identity是微软在MVC 5.0中新引入的一种membership框架,和之前ASP.NET传统的membership以及WebPage所带来的SimpleMembership(在MVC 4中使用)都有所不同. Microsoft.AspNet.Identity是符合微软开放Owin标准里面Security标准的一种实现.且在MVC 5中默认使用EntityFramework作为Microsoft.A

Asp.net Identity 系列之 怎样修改Microsoft.AspNet.Identity.EntityFramework.IdentityUser 的 Id 字段的数据类型

这篇博客我们来学习如何将AspNetUsers 表的Id 字段 的类型由nvarchar(128) 改为Int 并且子增长 1.为什么要修改 如果你运行过 Asp.net mvc 示例项目,你好会发现 AspNetUsers 表的Id是Nvarchar(128) 类型,值为GUID,不可否认使用GUID来做主键进行主外键关联会增加数据安全性(个人看法),但是非常不利于查询,可读性不够,因此我们尝试着去改为Int类型. 先看一下修改后的效果: 2.修改前分析 查看数据库结构我们知道要修改的表有这样

Microsoft.AspNet.Identity.EntityFramework/IdentityDbContext.cs

using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations.Schema; using System.Data.Common; using System.Data.Entity; using System.Data.Entity.Infrastructure; using System.Data.Entity.Infrastructure.Annotations; usin

Microsoft.AspNet.Identity 自定义使用现有的表—登录实现

Microsoft.AspNet.Identity是微软新引入的一种membership框架,也是微软Owin标准的一个实现.Microsoft.AspNet.Identity.EntityFramework则是Microsoft.AspNet.Identity的数据提供实现.但是在使用此框架的时候存在一些问题,如果是全新的项目还可以使用它默认提供的表名,字段名等.但是如果是在一些老的数据库上应用这个框架就比较麻烦了.所以我们实现一个自己的Microsoft.AspNet.Identity.En

Microsoft.AspNet.Identity 重置密码

原文:Microsoft.AspNet.Identity 重置密码 重置密码:先生成重置密码的Token,然后调用ResetPassword方法重置密码,密码要符合规则.. ApplicationUserManager UserManager => _userManager ?? HttpContext.GetOwinContext().GetUserManager<ApplicationUserManager>(); string token = UserManager.Generat

在现有项目中使用AspNet Identity 2.0 实战

感谢@LAgess 的解答:http://q.cnblogs.com/q/68698/ 办法一: 1.用 NuGet 安装 Identity. 2.添加链接字符串: <add name="DefaultConnection" connectionString="Data Source=.\SQLExpress;Initial Catalog=SJK;User ID=**;password=********;" providerName="System

Microsoft.AspNet.Identity: UserID用整型数据表示, 而不是GUID

http://stackoverflow.com/questions/19553424/how-to-change-type-of-id-in-microsoft-aspnet-identity-entityframework-identityus

AspNet Identity and IoC Container Registration

https://github.com/trailmax/IoCIdentitySample TL;DR: Registration code for Autofac, for SimpleInjector, for Unity. Tony Mackay has an alternative walk-through of a very similar process but with Autofac Part 2: Sending Emails in Asp.Net Identity using

[ASP.NET MVC] 使用CLK.AspNet.Identity提供以角色为基础的访问控制(RBAC)

[ASP.NET MVC] 使用CLK.AspNet.Identity提供以角色为基础的访问控制(RBAC) 程序代码下载 程序代码下载:点此下载 前言 ASP.NET Identity是微软所贡献的开源项目,用来提供ASP.NET的验证.授权机制.而在ASP.NET Identity的功能模块中:是采用Claims-Based验证来提供验证机制.并且实作Role-Based授权来提供授权机制.开发人员在系统内套用ASP.NET Identity后,就可以像下列范例一样定义用户属于哪个角色.哪个