首页 > 其他分享 >用Abp实现两步验证(Two-Factor Authentication,2FA)登录(三):免登录验证

用Abp实现两步验证(Two-Factor Authentication,2FA)登录(三):免登录验证

时间:2023-04-12 21:36:20浏览次数:43  
标签:return string 登录 验证 await Two var new validationParameters

@目录

免登录验证是用户在首次两步验证通过后,在常用的设备(浏览器)中,在一定时间内不需要再次输入验证码直接登录。

常见的网页上提示“7天免登录验证”或“信任此设备,7天内无需两步验证”等内容。
这样可以提高用户的体验。但同时也会带来一定的安全风险,因此需要用户自己决定是否开启。
在这里插入图片描述

原理

常用的实现方式是在用户登录成功后,生成一个随机的字符串Token,将此Token保存在用户浏览器的 cookie 中,同时将这个字符串保存在用户的数据库中。当用户再次访问时,如果 cookie 中的字符串和数据库中的字符串相同,则免登录验证通过。流程图如下:

在这里插入图片描述

为了安全,Token采用对称加密传输存储,同时参与校验的还有用户Id,以进一步验证数据一致性。Token存储于数据库中并设置过期时间(ExpireDate)
认证机制由JSON Web Token(JWT)实现,通过自定义Payload声明中添加Token和用户Id字段,实现校验。

下面来看代码实现:

修改请求报文

项目添加对Microsoft.AspNetCore.Authentication.JwtBearer包的引用

<packagereference include="Microsoft.AspNetCore.Authentication.JwtBearer" version="7.0.4">

在Authenticate方法参数AuthenticateModel中添加RememberClient和RememberClientToken属性,

当首次登录时,若用户选择免登录,RememberClient为true,
非首次登录时,系统校验RememberClientToken合法性,是否允许跳过两步验证。

public class AuthenticateModel
{
  ..

    public bool RememberClient { get; set; }

    public string RememberClientToken { get; set; }
}

同时返回值中添加RememberClientToken,用于首次登录生成的Token

public class AuthenticateResultModel
{
    ...

    public string RememberClientToken { get; set; }
}

配置JwtBearerOptions

在TokenAuthController的Authenticate方法中,添加validation参数:

var validationParameters = new TokenValidationParameters
{
    ValidAudience = _configuration.Audience,
    ValidIssuer = _configuration.Issuer,
    IssuerSigningKey = _configuration.SecurityKey
};

在默认的AbpBoilerplate模板项目中已经为我们生成了默认配置

 "Authentication": {
    "JwtBearer": {
      "IsEnabled": "true",
      "SecurityKey": "MatoAppSample_C421AAEE0D114E9C",
      "Issuer": "MatoAppSample",
      "Audience": "MatoAppSample"
    }
  },

生成Token

在TokenAuthController类中

添加自定义Payload声明类型

public const string USER_IDENTIFIER_CLAIM = "USER_IDENTIFIER_CLAIM";
public const string REMEMBER_CLIENT_TOKEN = "REMEMBER_CLIENT_TOKEN";

添加生成Token的方法CreateAccessToken,它将根据自定义Payload声明,validationParameters生成经过SHA256加密的Token,过期时间即有效期为7天:

private string CreateAccessToken(IEnumerable<claim> claims, TokenValidationParameters validationParameters)
{
    var now = DateTime.UtcNow;
    var expiration = TimeSpan.FromDays(7);
    var signingCredentials = new SigningCredentials(validationParameters.IssuerSigningKey, SecurityAlgorithms.HmacSha256);


    var jwtSecurityToken = new JwtSecurityToken(
        issuer: validationParameters.ValidIssuer,
        audience: validationParameters.ValidAudience,
        claims: claims,
        notBefore: now,
        expires: now.Add(expiration),
        signingCredentials: signingCredentials
    );

    return new JwtSecurityTokenHandler().WriteToken(jwtSecurityToken);
}

更改方法TwoFactorAuthenticateAsync的签名,添加rememberClient和validationParameters形参

在该方法中添加生成Token的代码

if (rememberClient)
{
    if (await settingManager.GetSettingValueAsync<bool>(AbpZeroSettingNames.UserManagement.TwoFactorLogin.IsRememberBrowserEnabled))
    {
        var expiration = TimeSpan.FromDays(7);

        var tokenValidityKey = Guid.NewGuid().ToString("N");
        var accessToken = CreateAccessToken(new[]
            {
                new Claim(USER_IDENTIFIER_CLAIM, user.ToUserIdentifier().ToString()),
                new Claim(REMEMBER_CLIENT_TOKEN, tokenValidityKey)
            }, validationParameters
        );
        await _userManager.AddTokenValidityKeyAsync(user, tokenValidityKey,
        DateTime.Now.Add(expiration));
        return accessToken;
    }
}

校验Token

添加校验方法TwoFactorClientRememberedAsync,它表示校验结果是否允许跳过两步验证

public async Task<bool> TwoFactorClientRememberedAsync(UserIdentifier userIdentifier, string TwoFactorRememberClientToken, TokenValidationParameters validationParameters)
{
    if (!await settingManager.GetSettingValueAsync<bool>(AbpZeroSettingNames.UserManagement.TwoFactorLogin.IsRememberBrowserEnabled))
    {
        return false;
    }

    if (string.IsNullOrWhiteSpace(TwoFactorRememberClientToken))
    {
        return false;
    }

    try
    {
        var tokenHandler = new JwtSecurityTokenHandler();


        if (tokenHandler.CanReadToken(TwoFactorRememberClientToken))
        {
            try
            {
                SecurityToken validatedToken;
                var principal = tokenHandler.ValidateToken(TwoFactorRememberClientToken, validationParameters, out validatedToken);
                var userIdentifierString = principal.Claims.First(c =&gt; c.Type == TwoFactorAuthorizationManager.USER_IDENTIFIER_CLAIM);
                if (userIdentifierString == null)
                {
                    throw new SecurityTokenException(TwoFactorAuthorizationManager.USER_IDENTIFIER_CLAIM + " invalid");
                }

                var tokenValidityKeyInClaims = principal.Claims.First(c =&gt; c.Type == TwoFactorAuthorizationManager.REMEMBER_CLIENT_TOKEN);


                var currentUserIdentifier = UserIdentifier.Parse(userIdentifierString.Value);

                var user = _userManager.GetUserById(currentUserIdentifier.UserId);
                var isValidityKetValid = AsyncHelper.RunSync(() =&gt; _userManager.IsTokenValidityKeyValidAsync(user, tokenValidityKeyInClaims.Value));

                if (!isValidityKetValid)
                {
                    throw new SecurityTokenException(REMEMBER_CLIENT_TOKEN + " invalid");

                }

                return userIdentifierString.Value == userIdentifier.ToString();
            }
            catch (Exception ex)
            {
                LogHelper.LogException(ex);
            }
        }

    }
    catch (Exception ex)
    {
        LogHelper.LogException(ex);
    }

    return false;
}

更改方法IsTwoFactorAuthRequiredAsync添加twoFactorRememberClientToken和validationParameters形参

添加对TwoFactorClientRememberedAsync的调用

public async Task<bool> IsTwoFactorAuthRequiredAsync(AbpLoginResult<tenant, user=""> loginResult, string TwoFactorRememberClientToken, TokenValidationParameters validationParameters)
{
    if (!await settingManager.GetSettingValueAsync<bool>(AbpZeroSettingNames.UserManagement.TwoFactorLogin.IsEnabled))
    {
        return false;
    }

    if (!loginResult.User.IsTwoFactorEnabled)
    {
        return false;
    }
    if ((await _userManager.GetValidTwoFactorProvidersAsync(loginResult.User)).Count &lt;= 0)
    {
        return false;
    }

    if (await TwoFactorClientRememberedAsync(loginResult.User.ToUserIdentifier(), TwoFactorRememberClientToken, validationParameters))
    {
        return false;
    }

    return true;
}

修改认证EndPoint

在TokenAuthController的Authenticate方法中,找到校验代码片段,对以上两个方法的调用传入实参

...
await userManager.InitializeOptionsAsync(loginResult.Tenant?.Id);
string twoFactorRememberClientToken = null;
if (await twoFactorAuthorizationManager.IsTwoFactorAuthRequiredAsync(loginResult, model.RememberClientToken, validationParameters))
{
    if (string.IsNullOrEmpty(model.TwoFactorAuthenticationToken))
    {
        return new AuthenticateResultModel
        {
            RequiresTwoFactorAuthenticate = true,
            UserId = loginResult.User.Id,
            TwoFactorAuthenticationProviders = await userManager.GetValidTwoFactorProvidersAsync(loginResult.User),

        };
    }
    else
    {
        twoFactorRememberClientToken = await twoFactorAuthorizationManager.TwoFactorAuthenticateAsync(loginResult.User, model.TwoFactorAuthenticationToken, model.TwoFactorAuthenticationProvider, model.RememberClient, validationParameters);
    }
}

完整的TwoFactorAuthorizationManager代码如下:

public class TwoFactorAuthorizationManager : ITransientDependency
{
    public const string USER_IDENTIFIER_CLAIM = "USER_IDENTIFIER_CLAIM";
    public const string REMEMBER_CLIENT_TOKEN = "REMEMBER_CLIENT_TOKEN";

    private readonly UserManager _userManager;
    private readonly ISettingManager settingManager;
    private readonly SmsCaptchaManager smsCaptchaManager;
    private readonly EmailCaptchaManager emailCaptchaManager;

    public TwoFactorAuthorizationManager(
        UserManager userManager,
        ISettingManager settingManager,
        SmsCaptchaManager smsCaptchaManager,
        EmailCaptchaManager emailCaptchaManager)
    {
        this._userManager = userManager;
        this.settingManager = settingManager;
        this.smsCaptchaManager = smsCaptchaManager;
        this.emailCaptchaManager = emailCaptchaManager;
    }



    public async Task<bool> IsTwoFactorAuthRequiredAsync(AbpLoginResult<tenant, user=""> loginResult, string TwoFactorRememberClientToken, TokenValidationParameters validationParameters)
    {
        if (!await settingManager.GetSettingValueAsync<bool>(AbpZeroSettingNames.UserManagement.TwoFactorLogin.IsEnabled))
        {
            return false;
        }

        if (!loginResult.User.IsTwoFactorEnabled)
        {
            return false;
        }
        if ((await _userManager.GetValidTwoFactorProvidersAsync(loginResult.User)).Count &lt;= 0)
        {
            return false;
        }

        if (await TwoFactorClientRememberedAsync(loginResult.User.ToUserIdentifier(), TwoFactorRememberClientToken, validationParameters))
        {
            return false;
        }

        return true;
    }

    public async Task<bool> TwoFactorClientRememberedAsync(UserIdentifier userIdentifier, string TwoFactorRememberClientToken, TokenValidationParameters validationParameters)
    {
        if (!await settingManager.GetSettingValueAsync<bool>(AbpZeroSettingNames.UserManagement.TwoFactorLogin.IsRememberBrowserEnabled))
        {
            return false;
        }

        if (string.IsNullOrWhiteSpace(TwoFactorRememberClientToken))
        {
            return false;
        }

        try
        {
            var tokenHandler = new JwtSecurityTokenHandler();


            if (tokenHandler.CanReadToken(TwoFactorRememberClientToken))
            {
                try
                {
                    SecurityToken validatedToken;
                    var principal = tokenHandler.ValidateToken(TwoFactorRememberClientToken, validationParameters, out validatedToken);
                    var userIdentifierString = principal.Claims.First(c =&gt; c.Type == TwoFactorAuthorizationManager.USER_IDENTIFIER_CLAIM);
                    if (userIdentifierString == null)
                    {
                        throw new SecurityTokenException(TwoFactorAuthorizationManager.USER_IDENTIFIER_CLAIM + " invalid");
                    }

                    var tokenValidityKeyInClaims = principal.Claims.First(c =&gt; c.Type == TwoFactorAuthorizationManager.REMEMBER_CLIENT_TOKEN);


                    var currentUserIdentifier = UserIdentifier.Parse(userIdentifierString.Value);

                    var user = _userManager.GetUserById(currentUserIdentifier.UserId);
                    var isValidityKetValid = AsyncHelper.RunSync(() =&gt; _userManager.IsTokenValidityKeyValidAsync(user, tokenValidityKeyInClaims.Value));

                    if (!isValidityKetValid)
                    {
                        throw new SecurityTokenException(REMEMBER_CLIENT_TOKEN + " invalid");

                    }

                    return userIdentifierString.Value == userIdentifier.ToString();
                }
                catch (Exception ex)
                {
                    LogHelper.LogException(ex);
                }
            }

        }
        catch (Exception ex)
        {
            LogHelper.LogException(ex);
        }

        return false;
    }

    public async Task<string> TwoFactorAuthenticateAsync(User user, string token, string provider, bool rememberClient, TokenValidationParameters validationParameters)
    {
        if (provider == "Email")
        {
            var isValidate = await emailCaptchaManager.VerifyCaptchaAsync(token, CaptchaPurpose.TWO_FACTOR_AUTHORIZATION);
            if (!isValidate)
            {
                throw new UserFriendlyException("验证码错误");
            }
        }

        else if (provider == "Phone")
        {
            var isValidate = await smsCaptchaManager.VerifyCaptchaAsync(token, CaptchaPurpose.TWO_FACTOR_AUTHORIZATION);
            if (!isValidate)
            {
                throw new UserFriendlyException("验证码错误");
            }
        }
        else
        {
            throw new UserFriendlyException("验证码提供者错误");
        }


        if (rememberClient)
        {
            if (await settingManager.GetSettingValueAsync<bool>(AbpZeroSettingNames.UserManagement.TwoFactorLogin.IsRememberBrowserEnabled))
            {
                var expiration = TimeSpan.FromDays(7);

                var tokenValidityKey = Guid.NewGuid().ToString("N");
                var accessToken = CreateAccessToken(new[]
                    {
                        new Claim(USER_IDENTIFIER_CLAIM, user.ToUserIdentifier().ToString()),
                        new Claim(REMEMBER_CLIENT_TOKEN, tokenValidityKey)
                    }, validationParameters
                );

                await _userManager.AddTokenValidityKeyAsync(user, tokenValidityKey,
                DateTime.Now.Add(expiration));
                return accessToken;


            }
        }

        return null;
    }

    private string CreateAccessToken(IEnumerable<claim> claims, TokenValidationParameters validationParameters)
    {
        var now = DateTime.UtcNow;
        var expiration = TimeSpan.FromDays(7);
        var signingCredentials = new SigningCredentials(validationParameters.IssuerSigningKey, SecurityAlgorithms.HmacSha256);


        var jwtSecurityToken = new JwtSecurityToken(
            issuer: validationParameters.ValidIssuer,
            audience: validationParameters.ValidAudience,
            claims: claims,
            notBefore: now,
            expires: now.Add(expiration),
            signingCredentials: signingCredentials
        );

        return new JwtSecurityTokenHandler().WriteToken(jwtSecurityToken);
    }


    public async Task SendCaptchaAsync(long userId, string provider)
    {
        var user = await _userManager.FindByIdAsync(userId.ToString());
        if (user == null)
        {
            throw new UserFriendlyException("找不到用户");

        }

        if (provider == "Email")
        {
            if (!user.IsEmailConfirmed)
            {
                throw new UserFriendlyException("未绑定邮箱");
            }
            await emailCaptchaManager.SendCaptchaAsync(user.Id, user.EmailAddress, CaptchaPurpose.TWO_FACTOR_AUTHORIZATION);
        }
        else if (provider == "Phone")
        {
            if (!user.IsPhoneNumberConfirmed)
            {
                throw new UserFriendlyException("未绑定手机号");
            }
            await smsCaptchaManager.SendCaptchaAsync(user.Id, user.PhoneNumber, CaptchaPurpose.TWO_FACTOR_AUTHORIZATION);
        }
        else
        {
            throw new UserFriendlyException("验证码提供者错误");
        }
    }



}

至此我们就完成了后端部分的开发

修改前端

登录

在两步验证的页面中添加一个checkbox,用于选择是否记住客户端

<el-checkbox v-model="loginForm.rememberClient">
    7天内不再要求两步验证
</el-checkbox>

JavaScript部分添加对rememberClientToken的处理,存储于cookie中,即便在网页刷新后也能保持免两步验证的状态

const rememberClientTokenKey = "main_rememberClientToken";
const setRememberClientToken = (rememberClientToken: string) =&gt;
  Cookies.set(rememberClientTokenKey, rememberClientToken);
const cleanRememberClientToken = () =&gt; Cookies.remove(rememberClientTokenKey);
const getRememberClientToken = () =&gt; Cookies.get(rememberClientTokenKey);

在请求body中添加rememberClientToken, rememberClient的值

 var rememberClientToken = getRememberClientToken();
var rememberClient=this.loginForm.rememberClient;

userNameOrEmailAddress = userNameOrEmailAddress.trim();
await request(`${this.host}api/TokenAuth/Authenticate`, "post", {
    userNameOrEmailAddress,
    password,
    twoFactorAuthenticationToken,
    twoFactorAuthenticationProvider,
    rememberClientToken,
    rememberClient
})

请求成功后,返回报文中包含rememberClientToken,将其存储于cookie中

setRememberClientToken(data.rememberClientToken);

登出

登出的逻辑不用做其他的修改,只需要将页面的两步验证的token清空即可,

this.loginForm.twoFactorAuthenticationToken = "";
this.loginForm.password = "";

rememberClientToken是存储于cookie中的,当用户登出时不需要清空cookie中的rememberClientToken,以便下次登录跳过两步验证

除非在浏览器设置中清空cookie,下次登录时,rememberClientToken就会失效。

最终效果

在这里插入图片描述

项目地址

Github:matoapp-samples</tenant,></tenant,>

标签:return,string,登录,验证,await,Two,var,new,validationParameters
From: https://www.cnblogs.com/jevonsflash/p/17311342.html

相关文章

  • 配置路由表及登录态校验
    前几天我完成了一个哔哩哔哩的博主视频下的一个react项目,借此项目来巩固学习的知识,这篇文章主要记录我在该项目用到的路由知识配置路由表在src下新建一个router文件夹,在router文件夹下新建index.js和router.jsrouter.js是将将项目中的所有路由引入并制作成一张路由表,在该文件下......
  • python习题-验证6174猜想
    【题目描述】1955年,卡普耶卡(D.R.Kaprekar)对4位数字进行了研究,发现一个规律:对任意各位数字不相同的4位数,使用各位数字能组成的最大数减去能组成的最小数,对得到的差重复这个操作,最终会得到6174这个数字,并且这个操作最多不会超过7次。请编写程序验证这个猜想。【源代码程序】de......
  • SNMP(Simple Network Management Protocol)——简单网络管理协议
    SNMP(SimpleNetworkManagementProtocol)——简单网络管理协议 目录一、SNMP简介1.背景2.SNMP管理的网络架构二、SNMPMIB1.SNMPMIB简介2.MIB分类(1)公有MIB(2)私有MIB3.被管理设备的基本属性(1)对象表示符(2)对象的状态(3)对象的访问权限(4)对象的数据类型三、SNMPv1工作......
  • Linux系列---【验证端口网络策略是否通的几种方式】
    验证端口网络策略是否通的几种方式前提:先使用ping命令保证IP是通的,再去验证端口。方式一(telnetip端口)telnet172.17.4.128080方式二(curlip:端口)curl172.17.4.12:8080#验证通:curl:(52)Emptyreplyfromserver不通:curl:(7)Failedtoconnectto172.17.4.1......
  • jwt验证机制
    jwt数据结构为1.header头:{"type":"JWT"}2.payload:有效载荷3.signature签名防止篡改 服务器和客户端jwt交互过程服务器给出token的时候:1.前提:账号密码验证通过得到用户信息或者其他信息(过期时间等)往header或者payload里面塞2. base64urlEncode(header)+"."+base64......
  • Django自带的Admin后台中如何获取当前登录用户
    需求背景在使用Django快速开发一个IT电脑、显示器资产管理小系统的时候,遇到一个问题是,当变更资产设备(新增、修改、删除)的时候,能记录是谁在什么时间进行的变更。确认的是肯定是登录状态,但是在使用Django的signal中获取不到当前登录的用户问题演示1、定义资产设备模型和 自定义日志......
  • 用Abp实现两步验证(Two-Factor Authentication,2FA)登录(二):Vue网页端开发
    @目录发送验证码登录退出登录界面控件获取用户信息功能项目地址前端代码的框架采用vue.js+elementUI这套较为简单的方式实现,以及typescript语法更方便阅读。首先添加全局对象:loginForm:登录表单对象twoFactorData:两步验证数据,showTwoFactorSuccess:是否显示两步验证成......
  • 23.text--生成验证码
    生成验证码内容:可以是小写字母,也可以是大写字母,还可以是数字规则:长度为5,内容是四位字母,一位数字,其中数字只有1位,但是可以出现在任意位置publicstaticvoidmain(String[]args){//创建含有大小写字母的数组char[]letterArr=newchar[52];//小写字母在ASC......
  • Javaweb-登录界面-filter配合案例-2023-04-11
    1、新建login.jsp登录界面响应的路径<%@pagecontentType="text/html;charset=UTF-8"language="java"%><html><head><title>Login</title></head><body><h1>登录界面</h1><hr><form......
  • vmware esxi 用户名(账号)密码明明正确,网页却无法登录管理后台的解决办法大全
    相信使用过VmwareEsxi虚拟系统的网友们可能都偶尔遇到过,明明vmwareesxi用户名密码是正确的,管理网页却无法登录管理的现象。一、账号密码正常但无法登录现象:隔了一段时间没有登录,用服务器名或IP再登录Vmware的网页管理后台,输入正确的管理员用户名及密码,之前登录都非常正常......