Advertisement

Advertisement

Otp base login in .net core mvc app

How to send otp on any mobile number using Twilio


Twilio otp provider k thru .net core mvc app banaya jis me user apna mobile number dalega aur otp send btn pe click karega to mobile pe otp aayega phir user otp aur password dal k submit karega to home index pe redirect kra rhe h 


 <ItemGroup>

  <PackageReference Include="Microsoft.AspNetCore.Identity.EntityFrameworkCore" Version="8.0.0" />

  <PackageReference Include="Microsoft.EntityFrameworkCore" Version="8.0.0" />

  <PackageReference Include="Microsoft.EntityFrameworkCore.SqlServer" Version="8.0.0" />

  <PackageReference Include="Microsoft.EntityFrameworkCore.Tools" Version="8.0.0">

  <PrivateAssets>all</PrivateAssets>

  <IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>

  </PackageReference>

  <PackageReference Include="Twilio" Version="7.8.0" />

 </ItemGroup>


appsettings.json


"ConnectionStrings": {

    "DefaultConnection": "Server = DESKTOP-9M9EDAA\\SQLEXPRESS; Database = TwilioOtpDb; Trusted_Connection = True; MultipleActiveResultSets = True; TrustServerCertificate = True;"


},

"Twilio": {

    "AccountSid": "AC55d242a0054a1aa9818dac9c49637...",

    "AuthToken": "4f21c3dbe6321f1201c39ed9e67e5...",

    "FromPhoneNumber": "+1 570 539 7..."

},

Program.cs


// Add services to the container.

builder.Services.AddControllersWithViews();


builder.Services.AddDbContext<ApplicationDbContext>(options =>

       options.UseSqlServer((builder.Configuration.GetConnectionString("DefaultConnection"))));


builder.Services.AddIdentity<IdentityUser, IdentityRole>()

    .AddEntityFrameworkStores<ApplicationDbContext>()

    .AddDefaultTokenProviders();



builder.Services.AddTransient<TwilioService>();

// Add session services

builder.Services.AddSession(options =>

{

    options.IdleTimeout = TimeSpan.FromMinutes(30); // Session timeout duration

    options.Cookie.HttpOnly = true;

    options.Cookie.IsEssential = true;

});


app.UseAuthentication();

app.UseAuthorization();

// Use session middleware

app.UseSession();


Service folder k ander 


 using Twilio;

 using Twilio.Rest.Api.V2010.Account;

 using Microsoft.Extensions.Configuration;


 public class TwilioService

 {

     private readonly IConfiguration _configuration;


     public TwilioService(IConfiguration configuration)

     {

         _configuration = configuration;

     }


     public void SendOtp(string toPhoneNumber, string otp)

     {

         var accountSid = _configuration["Twilio:AccountSid"];

         var authToken = _configuration["Twilio:AuthToken"];

         var fromPhoneNumber = _configuration["Twilio:FromPhoneNumber"];


         TwilioClient.Init(accountSid, authToken);


         MessageResource.Create(

             body: $"Your OTP is {otp}",

             from: new Twilio.Types.PhoneNumber(fromPhoneNumber),

             to: new Twilio.Types.PhoneNumber(toPhoneNumber)

         );

     }

 }


 Data folder k ander


 public class ApplicationDbContext : IdentityDbContext

 {

     public ApplicationDbContext(DbContextOptions<ApplicationDbContext> options)

         : base(options)

     {

     }

 }


Model folder k ander


 public class OtpViewModel

 {

     public string PhoneNumber { get; set; }

     public string Otp { get; set; }

     public string Password { get; set; }

 }


Controller folder k ander


  public class AccountController : Controller

  {

      private readonly UserManager<IdentityUser> _userManager;

      private readonly TwilioService _twilioService;


      public AccountController(UserManager<IdentityUser> userManager, TwilioService twilioService)

      {

          _userManager = userManager;

          _twilioService = twilioService;

      }


      // Step 1: Render OTP Request Form

      [HttpGet]

      public IActionResult RequestOtp()

      {

          return View();

      }


      // Step 2: Handle OTP Request

      [HttpPost]

      public IActionResult RequestOtp(string phoneNumber)

      {

          if (string.IsNullOrEmpty(phoneNumber))

          {

              ModelState.AddModelError("", "Phone number is required");

              return View();

          }


          var otp = new Random().Next(100000, 999999).ToString();


          HttpContext.Session.SetString("PhoneNumber", phoneNumber);

          HttpContext.Session.SetString("Otp", otp);


          // Send OTP

          _twilioService.SendOtp(phoneNumber, otp);


          return RedirectToAction("VerifyOtp");

      }



      // Step 3: Render OTP Verification Form

      [HttpGet]

      public IActionResult VerifyOtp()

      {

          return View();

      }


      // Step 4: Handle OTP Verification


      // Step 3: Verify OTP

      [HttpPost]

      public async Task<IActionResult> VerifyOtp(OtpViewModel model)

      {

          var sessionOtp = HttpContext.Session.GetString("Otp");

          var sessionPhoneNumber = HttpContext.Session.GetString("PhoneNumber");


          if (sessionOtp == model.Otp && sessionPhoneNumber == model.PhoneNumber)

          {

              // Create a new user in Identity

              var user = new IdentityUser

              {

                  UserName = sessionPhoneNumber,

                  PhoneNumber = sessionPhoneNumber

              };


              var result = await _userManager.CreateAsync(user, model.Password);


              if (result.Succeeded)

              {

                  return RedirectToAction("Index", "Home");

              }

              else

              {

                  foreach (var error in result.Errors)

                  {

                      ModelState.AddModelError("", error.Description);

                  }

              }

          }

          else

          {

              ModelState.AddModelError("", "Invalid OTP or phone number");

          }


          return View(model);

      }



      public IActionResult Success()

      {

          return View();

      }

  }


RequestOtp.cshtml


 <form method="post" action="/Account/RequestOtp">

    <label>Phone Number</label>

    <input type="text" name="phoneNumber" required />

    <button type="submit">Send OTP</button>

</form> 


VerifyOtp.cshtml


<form method="post" action="/Account/VerifyOtp">

    <label for="phoneNumber">Phone Number:</label>

    <input type="text" id="phoneNumber" name="PhoneNumber" required />


    <label for="otp">OTP:</label>

    <input type="text" id="otp" name="Otp" required />


    <label for="password">Password:</label>

    <input type="password" id="password" name="Password" required />


    <button type="submit">Verify</button>

</form>



Run command in PMC


Add-Migration InitialCreate

Update-database


Otp base login in .net core mvc app Otp base login in .net core mvc app Reviewed by Rikesh on January 10, 2025 Rating: 5

No comments:

Powered by Blogger.