Integrating MSG91 for OTP and SMS in ASP.NET Core Applications
Overview
In the digital age, securing user accounts is paramount. One of the most effective methods for achieving this is through the use of One-Time Passwords (OTPs). An OTP is a unique code that is valid for a single transaction or login session, providing an additional layer of security beyond traditional passwords. MSG91 is a widely used service in India that facilitates SMS sending, including OTPs, to users' mobile devices. By integrating MSG91 into your ASP.NET Core application, you can streamline the process of user verification and enhance security.
MSG91 exists to solve the problem of user authentication and communication in a reliable and scalable manner. The service offers a robust API that allows developers to send OTPs and SMS messages efficiently. Real-world use cases include banking applications, e-commerce platforms, and any service requiring secure user verification. This integration not only improves security but also enhances user experience by providing instant communication.
Prerequisites
- ASP.NET Core: Familiarity with ASP.NET Core framework and creating web applications.
- REST API Knowledge: Understanding of how to make HTTP requests and handle responses.
- MSG91 Account: You need an MSG91 account to access the API key and other configurations.
- NuGet Package Manager: Ability to install required NuGet packages in your ASP.NET Core project.
Setting Up MSG91 Account
Before integrating MSG91 into your ASP.NET Core application, you must set up your MSG91 account. This involves registering on the MSG91 website, verifying your phone number, and obtaining your API key. The API key is essential as it authenticates your requests to the MSG91 service.
Once registered, navigate to the dashboard where you can find your API key. Be sure to save this in a secure location, as it will be required in your application to authenticate API calls. Additionally, you may need to configure your sender ID, which is the name that will appear on users' mobile devices when they receive an SMS.
Integrating MSG91 API in ASP.NET Core
To integrate MSG91 into your ASP.NET Core application, you will primarily use the HttpClient class to send HTTP requests to the MSG91 API. This involves creating a service that encapsulates the logic for sending OTPs and SMS messages. Below is an example of how to set up this integration:
using System.Net.Http;
using System.Net.Http.Headers;
using System.Text;
using System.Threading.Tasks;
public class Msg91Service
{
private readonly HttpClient _httpClient;
private readonly string _apiKey;
private readonly string _senderId;
public Msg91Service(string apiKey, string senderId)
{
_httpClient = new HttpClient();
_apiKey = apiKey;
_senderId = senderId;
}
public async Task SendOtpAsync(string mobileNumber, string otp)
{
var url = $"https://api.msg91.com/api/sendotp?mobile={mobileNumber}&otp={otp}&authkey={_apiKey}&sender={_senderId}&message=Your OTP is {otp}"
var response = await _httpClient.GetAsync(url);
if (response.IsSuccessStatusCode)
{
return "OTP sent successfully";
}
else
{
return "Failed to send OTP";
}
}
}
This code defines a Msg91Service class that encapsulates the logic for sending OTPs. The constructor accepts the API key and sender ID, which are stored for use in the SendOtpAsync method. This method constructs the URL for the API request, including the mobile number, OTP, API key, and sender ID. An HTTP GET request is made to the MSG91 API, and the response is checked for success.
The expected output of the SendOtpAsync method is a success message if the OTP is sent successfully. In a production application, you would likely want to handle errors and exceptions more gracefully.
Sending SMS Messages
In addition to sending OTPs, you may also want to send regular SMS messages. The process is similar to sending OTPs, but the API endpoint and parameters differ slightly. Here’s how you can extend the Msg91Service to include a method for sending SMS:
public async Task SendSmsAsync(string mobileNumber, string message)
{
var url = $"https://api.msg91.com/api/sendhttp.php?authkey={_apiKey}&mobiles={mobileNumber}&message={message}&sender={_senderId}&route=4";
var response = await _httpClient.GetAsync(url);
if (response.IsSuccessStatusCode)
{
return "SMS sent successfully";
}
else
{
return "Failed to send SMS";
}
}
This method constructs a URL for sending an SMS and makes an HTTP GET request. Similar to the OTP method, it checks the response and returns an appropriate message.
Testing the MSG91 Integration
To ensure that your integration works correctly, you should write unit tests for the Msg91Service. Using a mocking framework like Moq can help you simulate HTTP responses without actually calling the MSG91 API. Here’s how you can write a test for the SendOtpAsync method:
using Moq;
using System.Net;
using System.Net.Http;
using System.Threading.Tasks;
using Xunit;
public class Msg91ServiceTests
{
[Fact]
public async Task SendOtpAsync_ShouldReturnSuccess_WhenResponseIsSuccessful()
{
// Arrange
var mockHttp = new Mock();
mockHttp.Protected()
.Setup>("SendAsync",
It.IsAny(), It.IsAny())
.ReturnsAsync(new HttpResponseMessage
{
StatusCode = HttpStatusCode.OK,
});
var httpClient = new HttpClient(mockHttp.Object);
var msg91Service = new Msg91Service("your_api_key", "your_sender_id");
// Act
var result = await msg91Service.SendOtpAsync("1234567890", "123456");
// Assert
Assert.Equal("OTP sent successfully", result);
}
}
This test checks that when the SendOtpAsync method is called, it returns a success message if the response from the mocked HTTP client is successful. You can extend this test suite to cover edge cases and error scenarios as well.
Edge Cases & Gotchas
While integrating with external APIs like MSG91, there are several edge cases and pitfalls to be aware of. One common issue is rate limiting. MSG91 has limits on how many messages can be sent within a certain time frame. If you exceed this limit, you may receive an error response. Always check the documentation for the latest rate limits.
Another potential issue is the formatting of the mobile number. Ensure that the mobile numbers you send are correctly formatted, including country codes, to avoid failures in sending messages. Additionally, be cautious with the handling of sensitive data such as API keys. Never hard-code them in your source code; use environment variables or configuration files instead.
Performance & Best Practices
When integrating with external services, performance is crucial. One best practice is to implement asynchronous calls, as demonstrated in the examples above. This prevents blocking the main thread and ensures that your application remains responsive, especially when sending multiple messages.
Another important aspect is error handling. Implement retry logic for transient errors, such as network issues. Consider using libraries like Polly for resilient HTTP calls. Monitor your application for performance metrics and error rates to identify any bottlenecks in the integration.
Real-World Scenario: User Registration with OTP Verification
Let’s tie everything together in a realistic mini-project. Imagine you are developing a user registration feature that requires OTP verification. Here’s how you can implement this:
public class UserRegistrationController : Controller
{
private readonly Msg91Service _msg91Service;
public UserRegistrationController(Msg91Service msg91Service)
{
_msg91Service = msg91Service;
}
[HttpPost]
public async Task Register(UserRegistrationModel model)
{
if (ModelState.IsValid)
{
var otp = GenerateOtp();
await _msg91Service.SendOtpAsync(model.MobileNumber, otp);
return Ok("OTP sent to your mobile number.");
}
return BadRequest(ModelState);
}
private string GenerateOtp()
{
var random = new Random();
return random.Next(100000, 999999).ToString();
}
}
This UserRegistrationController handles user registration. When a user submits their registration, a random OTP is generated and sent to their mobile number using the Msg91Service. This provides a seamless registration experience with added security.
Conclusion
- MSG91 provides a robust solution for sending OTPs and SMS in ASP.NET Core applications.
- Proper setup of the MSG91 account and understanding of the API is essential for successful integration.
- Testing and handling edge cases are critical for a reliable application.
- Implementing performance best practices ensures a responsive user experience.
- Real-world scenarios demonstrate the practical application of OTP in user registration.