初始化项目
This commit is contained in:
72
AUTS_Server/Service/IEncryptionService.cs
Normal file
72
AUTS_Server/Service/IEncryptionService.cs
Normal file
@@ -0,0 +1,72 @@
|
||||
using Microsoft.AspNetCore.Mvc;
|
||||
using OtpNet;
|
||||
using static AUTS_Server.Service.MultiFactorAuthController;
|
||||
|
||||
namespace AUTS_Server.Service
|
||||
{
|
||||
public interface IEncryptionService
|
||||
{
|
||||
//md5加密
|
||||
string Encrypt(string str);
|
||||
// 手动构建TOTP URI
|
||||
string BuildTotpUri(string secret, string user, string issuer);
|
||||
// 验证TOTP
|
||||
bool VerifyTOTP(VerifyTOTPRequest request);
|
||||
// 生成并返回密钥和二维码URL
|
||||
GenerateKeyinfo GenerateKey();
|
||||
}
|
||||
[ApiController]
|
||||
[Route("[controller]")]
|
||||
public class MultiFactorAuthController : ControllerBase
|
||||
{
|
||||
// 生成并返回密钥和二维码URL
|
||||
[HttpGet("GenerateKey")]
|
||||
public IActionResult GenerateKey()
|
||||
{
|
||||
var key = KeyGeneration.GenerateRandomKey(20);
|
||||
var base32Secret = Base32Encoding.ToString(key);
|
||||
var issuer = "AUTS";
|
||||
var userAccount = "new.uts-data.com";
|
||||
var totpSetupUrl = BuildTotpUri(base32Secret, userAccount, issuer);
|
||||
|
||||
// 返回密钥和二维码URL
|
||||
return Ok(new { SecretKey = base32Secret, QrCodeSetupUrl = totpSetupUrl });
|
||||
}
|
||||
|
||||
// 验证TOTP
|
||||
[HttpPost("VerifyTOTP")]
|
||||
public IActionResult VerifyTOTP([FromBody] VerifyTOTPRequest request)
|
||||
{
|
||||
var key = Base32Encoding.ToBytes(request.SecretKey);
|
||||
long timeStepMatched;
|
||||
var totp = new Totp(key);
|
||||
var TotpCode = "";
|
||||
bool isValid = totp.VerifyTotp(TotpCode, out timeStepMatched, new VerificationWindow(2, 2));
|
||||
|
||||
if (isValid)
|
||||
{
|
||||
// 验证成功
|
||||
return Ok(new { Success = true });
|
||||
}
|
||||
else
|
||||
{
|
||||
// 验证失败
|
||||
return BadRequest(new { Success = false });
|
||||
}
|
||||
}
|
||||
|
||||
// 手动构建TOTP URI
|
||||
private string BuildTotpUri(string secret, string user, string issuer)
|
||||
{
|
||||
var issuerParameter = string.IsNullOrEmpty(issuer) ? "" : $"&issuer={Uri.EscapeDataString(issuer)}";
|
||||
return $"otpauth://totp/{Uri.EscapeDataString(user)}?secret={secret}{issuerParameter}&algorithm=SHA1&digits=6&period=30";
|
||||
}
|
||||
|
||||
|
||||
}
|
||||
public class VerifyTOTPRequest
|
||||
{
|
||||
public string SecretKey { get; set; }
|
||||
public string UserId { get; set; }
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user