Để tích hợp Twilio vào ứng dụng ASP.NET Core MVC 8 và sử dụng SMS One-Time Password (OTP) cho hệ thống xác thực người dùng, bạn cần thực hiện các bước sau:
Cài đặt Twilio SDK
Cấu hình Twilio
Tạo một dịch vụ gửi OTP qua SMS
Tạo mã OTP
Xác thực mã OTP
Sử dụng OTP trong hệ thống xác thực người dùng
Đầu tiên, bạn cần cài đặt thư viện Twilio SDK vào dự án của mình. Để làm điều này, sử dụng NuGet Package Manager hoặc dotnet CLI hoặc cũng có thể search và bấm cài trực tiếp ở cửa sổ Manage Nuget Packages:
Qua NuGet Package Manager:
Mở NuGet Package Manager Console trong Visual Studio.
Chạy lệnh sau:
Install-Package Twilio
Qua .NET CLI:
Mở terminal và chạy:
dotnet add package Twilio
Sau khi cài đặt Twilio SDK, bạn cần cấu hình Twilio với các thông tin từ tài khoản Twilio của bạn. Bạn sẽ cần:
Account SID
Auth Token
Số điện thoại Twilio của bạn
Đăng ký Twilio: Nếu bạn chưa có tài khoản, bạn có thể tạo tài khoản miễn phí tại Twilio.
Lấy Account SID và Auth Token: Truy cập vào Twilio Console, bạn sẽ tìm thấy thông tin này trong phần Dashboard.
Lấy số điện thoại Twilio: Trong phần Phone Numbers trên Twilio Console, bạn có thể mua một số điện thoại và sử dụng để gửi SMS.
Tiếp theo, bạn thêm thông tin này vào tệp cấu hình của ASP.NET Core (thường là appsettings.json):
{
"Twilio": {
"AccountSid": "your_account_sid",
"AuthToken": "your_auth_token",
"PhoneNumber": "+1234567890" // số điện thoại Twilio đã đăng ký của bạn
}
}
Trong ứng dụng của bạn, bạn cần tạo một dịch vụ giúp gửi OTP qua Twilio. Tạo một lớp mới trong thư mục Services.
Tạo TwilioService
Tạo một dịch vụ có tên TwilioService.cs trong thư mục Services để gửi SMS:
using Twilio;
using Twilio.Rest.Api.V2010.Account;
using Twilio.Exceptions;
using Microsoft.Extensions.Configuration;
using System;
using System.Threading.Tasks;
public class TwilioService
{
private readonly string _accountSid;
private readonly string _authToken;
private readonly string _phoneNumber;
public TwilioService(IConfiguration configuration)
{
_accountSid = configuration["Twilio:AccountSid"];
_authToken = configuration["Twilio:AuthToken"];
_phoneNumber = configuration["Twilio:PhoneNumber"];
}
public async Task<bool> SendOtpAsync(string toPhoneNumber, string otp)
{
try
{
TwilioClient.Init(_accountSid, _authToken);
var message = await MessageResource.CreateAsync(
body: $"Your OTP code is: {otp}",
from: new Twilio.Types.PhoneNumber(_phoneNumber),
to: new Twilio.Types.PhoneNumber(toPhoneNumber)
);
return true;
}
catch (ApiException ex)
{
// Handle the error (log it, etc.)
Console.WriteLine($"Twilio API error: {ex.Message}");
return false;
}
}
}
Sau đó, đăng ký service ở file Program.cs:
services.AddSingleton<TwilioService>();
Để tạo mã OTP, bạn có thể sử dụng một phương thức đơn giản để tạo chuỗi số ngẫu nhiên. Ví dụ:
public class OtpHelper
{
private static Random _random = new Random();
public static string GenerateOtp(int length = 6)
{
string otp = "";
for (int i = 0; i < length; i++)
{
otp += _random.Next(0, 10).ToString();
}
return otp;
}
}
Bây giờ bạn cần lưu mã OTP tạm thời trong cơ sở dữ liệu hoặc bộ nhớ tạm thời (Session, Cache, v.v.) để xác thực người dùng sau khi họ nhận được OTP.
Ví dụ về Controller
Tạo một controller mới để xử lý việc gửi và xác thực OTP. Bạn có thể thêm các hành động như sau:
using Microsoft.AspNetCore.Mvc;
using System.Threading.Tasks;
using Microsoft.Extensions.Configuration;
public class AccountController : Controller
{
private readonly TwilioService _twilioService;
public AccountController(TwilioService twilioService)
{
_twilioService = twilioService;
}
[HttpGet]
public IActionResult SendOtp()
{
return View();
}
[HttpPost]
public async Task<IActionResult> SendOtp(string phoneNumber)
{
// Generate OTP
var otp = OtpHelper.GenerateOtp();
// Send OTP via Twilio
bool success = await _twilioService.SendOtpAsync(phoneNumber, otp);
if (success)
{
// Store OTP temporarily (e.g., in Session or a database)
HttpContext.Session.SetString("Otp", otp);
// Redirect to OTP verification page
return RedirectToAction("VerifyOtp");
}
ModelState.AddModelError("", "Failed to send OTP.");
return View();
}
[HttpGet]
public IActionResult VerifyOtp()
{
return View();
}
[HttpPost]
public IActionResult VerifyOtp(string otp)
{
// Retrieve the OTP stored in Session or database
var storedOtp = HttpContext.Session.GetString("Otp");
if (storedOtp == otp)
{
// OTP is valid, proceed with authentication (e.g., login)
return RedirectToAction("Dashboard", "Home");
}
ModelState.AddModelError("", "Invalid OTP.");
return View();
}
}
View để gửi OTP (SendOtp.cshtml)
@{
ViewData["Title"] = "Send OTP";
}
<h2>@ViewData["Title"]</h2>
<form method="post">
<label for="phoneNumber">Phone Number</label>
<input type="text" id="phoneNumber" name="phoneNumber" required />
<button type="submit">Send OTP</button>
</form>
View để xác thực OTP (VerifyOtp.cshtml)
@{
ViewData["Title"] = "Verify OTP";
}
<h2>@ViewData["Title"]</h2>
<form method="post">
<label for="otp">OTP</label>
<input type="text" id="otp" name="otp" required />
<button type="submit">Verify OTP</button>
</form>
Sau khi hoàn tất các bước trên, bạn đã hoàn thiện việc tích hợp Twilio để gửi mã OTP qua SMS trong ứng dụng ASP.NET Core MVC 8. Khi người dùng nhập số điện thoại, hệ thống sẽ gửi mã OTP qua SMS và yêu cầu người dùng xác thực mã đó.
Lưu ý:
Bạn có thể lưu mã OTP vào cơ sở dữ liệu thay vì sử dụng Session nếu muốn xử lý lâu dài hơn.
Đảm bảo kiểm tra và xử lý lỗi khi gửi SMS, ví dụ như số điện thoại không hợp lệ hoặc mạng lưới của Twilio gặp vấn đề.
Tham khảo thêm
Giả sử bạn sẽ tạo 2 trang: một trang để nhập số điện thoại và một trang để xác minh mã OTP.
1. Thêm Controller (PhoneController)
Tạo một controller PhoneController để xử lý logic cho việc thêm số điện thoại và xác minh mã OTP.
using Microsoft.AspNetCore.Mvc;
using Twilio;
using Twilio.Rest.Verify.V2.Service;
using Twilio.Exceptions;
namespace YourProject.Controllers
{
public class PhoneController : Controller
{
private const string AccountSid = "your_account_sid";
private const string AuthToken = "your_auth_token";
private const string ServiceSid = "your_verify_service_sid"; // ID dịch vụ verify Twilio
public PhoneController()
{
// Khởi tạo Twilio client
TwilioClient.Init(AccountSid, AuthToken);
}
// Trang thêm số điện thoại
public IActionResult AddPhone()
{
return View();
}
// Xử lý gửi mã xác minh
[HttpPost]
public IActionResult AddPhone(string phoneNumber)
{
try
{
var verification = VerificationResource.Create(
to: phoneNumber,
channel: "sms", // Sử dụng SMS để gửi mã xác minh
pathServiceSid: ServiceSid
);
TempData["PhoneNumber"] = phoneNumber; // Lưu lại số điện thoại để xác minh
TempData["Message"] = "Mã xác minh đã được gửi đến số điện thoại của bạn.";
return RedirectToAction("VerifyPhone");
}
catch (ApiException e)
{
ModelState.AddModelError("", $"Error: {e.Message}");
return View();
}
}
// Trang xác minh mã OTP
public IActionResult VerifyPhone()
{
return View();
}
// Xử lý xác minh mã OTP
[HttpPost]
public IActionResult VerifyPhone(string verificationCode)
{
var phoneNumber = TempData["PhoneNumber"]?.ToString();
if (string.IsNullOrEmpty(phoneNumber))
{
ModelState.AddModelError("", "Số điện thoại không hợp lệ.");
return View();
}
try
{
var verificationCheck = VerificationCheckResource.Create(
to: phoneNumber,
code: verificationCode,
pathServiceSid: ServiceSid
);
if (verificationCheck.Status == "approved")
{
TempData["Message"] = "Xác minh số điện thoại thành công!";
return RedirectToAction("Success");
}
else
{
ModelState.AddModelError("", "Mã xác minh không chính xác. Vui lòng thử lại.");
return View();
}
}
catch (ApiException e)
{
ModelState.AddModelError("", $"Error: {e.Message}");
return View();
}
}
public IActionResult Success()
{
return View();
}
}
}
2. Thêm View cho AddPhone và VerifyPhone
Tạo các View tương ứng trong thư mục Views/Phone:
AddPhone.cshtml: Đây là trang cho phép người dùng nhập số điện thoại.
@{
ViewData["Title"] = "Add Phone";
}
<h2>Add Phone Number</h2>
<form asp-action="AddPhone" method="post">
<div class="form-group">
<label for="phoneNumber">Phone Number</label>
<input type="text" class="form-control" id="phoneNumber" name="phoneNumber" placeholder="Enter phone number" required />
</div>
<button type="submit" class="btn btn-primary">Send Verification Code</button>
</form>
@if (TempData["Message"] != null)
{
<div class="alert alert-info mt-3">@TempData["Message"]</div>
}
VerifyPhone.cshtml: Trang xác minh mã OTP gửi tới số điện thoại.
@{
ViewData["Title"] = "Verify Phone Number";
}
<h2>Verify Phone Number</h2>
<form asp-action="VerifyPhone" method="post">
<div class="form-group">
<label for="verificationCode">Verification Code</label>
<input type="text" class="form-control" id="verificationCode" name="verificationCode" placeholder="Enter verification code" required />
</div>
<button type="submit" class="btn btn-primary">Verify</button>
</form>
<div class="alert alert-danger mt-3" asp-validation-summary="All"></div>
@if (TempData["Message"] != null)
{
<div class="alert alert-info mt-3">@TempData["Message"]</div>
}
Success.cshtml: Trang thông báo khi xác minh thành công.
@{
ViewData["Title"] = "Success";
}
<h2>Phone Verification Successful!</h2>
<p>Your phone number has been successfully verified.</p>
Nếu bạn sử dụng mặc định Route của MVC, thì các URL sẽ là:
GET /Phone/AddPhone để nhập số điện thoại.
POST /Phone/AddPhone để gửi mã xác minh.
GET /Phone/VerifyPhone để nhập mã OTP.
POST /Phone/VerifyPhone để xác minh mã OTP.
GET /Phone/Success để hiển thị kết quả xác minh thành công.
Khởi động ứng dụng ASP.NET Core của bạn.
Truy cập trang Add Phone để nhập số điện thoại và nhận mã xác minh qua SMS.
Nhập mã OTP vào trang Verify Phone để hoàn tất quá trình xác minh.
Mã Verify service lấy ở đâu?
Login vào Twilio Console.
Vào Service Dashboard
Chọn Service SID, mã có dạng VAXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX