Commit 95408542 authored by alan.f's avatar alan.f

authorization-with-email

parent bf7243fa
......@@ -3,7 +3,9 @@ Microsoft Visual Studio Solution File, Format Version 12.00
# Visual Studio Version 16
VisualStudioVersion = 16.0.29911.84
MinimumVisualStudioVersion = 10.0.40219.1
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Basics", "Basics\Basics.csproj", "{E2F91297-82C6-4735-B44E-1EAE43684D33}"
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Basics", "Basics\Basics.csproj", "{E2F91297-82C6-4735-B44E-1EAE43684D33}"
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "IdentityExample", "IdentityExample\IdentityExample.csproj", "{7CDAF7C0-2118-4FE9-9648-CB7E7D2A0323}"
EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
......@@ -15,6 +17,10 @@ Global
{E2F91297-82C6-4735-B44E-1EAE43684D33}.Debug|Any CPU.Build.0 = Debug|Any CPU
{E2F91297-82C6-4735-B44E-1EAE43684D33}.Release|Any CPU.ActiveCfg = Release|Any CPU
{E2F91297-82C6-4735-B44E-1EAE43684D33}.Release|Any CPU.Build.0 = Release|Any CPU
{7CDAF7C0-2118-4FE9-9648-CB7E7D2A0323}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{7CDAF7C0-2118-4FE9-9648-CB7E7D2A0323}.Debug|Any CPU.Build.0 = Debug|Any CPU
{7CDAF7C0-2118-4FE9-9648-CB7E7D2A0323}.Release|Any CPU.ActiveCfg = Release|Any CPU
{7CDAF7C0-2118-4FE9-9648-CB7E7D2A0323}.Release|Any CPU.Build.0 = Release|Any CPU
EndGlobalSection
GlobalSection(SolutionProperties) = preSolution
HideSolutionNode = FALSE
......
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Identity;
using Microsoft.AspNetCore.Mvc;
using NETCore.MailKit.Core;
using System.Threading.Tasks;
namespace IdentityExample.Controllers
{
public class HomeController : Controller
{
private readonly UserManager<IdentityUser> _userManager;
private readonly SignInManager<IdentityUser> _signInManager;
private readonly IEmailService _emailService;
public HomeController(
UserManager<IdentityUser> userManager,
SignInManager<IdentityUser> signInManager,
IEmailService emailService)
{
_userManager = userManager;
_signInManager = signInManager;
_emailService = emailService;
}
public IActionResult Index()
{
return View();
}
[Authorize]
public IActionResult Secret()
{
return View();
}
public IActionResult Login()
{
return View();
}
[HttpPost]
public async Task<IActionResult> Login(string username, string password)
{
//login functionality
var user = await _userManager.FindByNameAsync(username);
if (user != null)
{
//sign in
var signInResult = await _signInManager.PasswordSignInAsync(user, password, false, false);
if (signInResult.Succeeded)
{
return RedirectToAction("Index");
}
}
return RedirectToAction("Index");
}
public IActionResult Register()
{
return View();
}
[HttpPost]
public async Task<IActionResult> Register(string username, string password)
{
//register functionality
var user = new IdentityUser
{
UserName = username,
Email = "",
};
var result = await _userManager.CreateAsync(user, password);
if (result.Succeeded)
{
//generation of the email token
var code = await _userManager.GenerateEmailConfirmationTokenAsync(user);
var link = Url.Action(nameof(VerifyEmail), "Home", new { userId = user.Id, code }, Request.Scheme, Request.Host.ToString());
await _emailService.SendAsync("meh.far.hdi@gmail.com", "email verify", $"<a href=\"{link}\">Verify Email</a>", true);
return RedirectToAction("EmailVerification");
}
return RedirectToAction("Index");
}
public async Task<IActionResult> VerifyEmail(string userId, string code)
{
var user = await _userManager.FindByIdAsync(userId);
if (user == null) return BadRequest();
var result = await _userManager.ConfirmEmailAsync(user, code);
if (result.Succeeded)
{
return View();
}
return BadRequest();
}
public IActionResult EmailVerification() => View();
public async Task<IActionResult> LogOut()
{
await _signInManager.SignOutAsync();
return RedirectToAction("Index");
}
}
}
using Microsoft.AspNetCore.Identity.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore;
namespace IdentityExample.Data
{
// IdentityDbContext contains all the user tables
public class AppDbContext : IdentityDbContext
{
public AppDbContext(DbContextOptions<AppDbContext> options)
: base(options)
{
}
}
}
<Project Sdk="Microsoft.NET.Sdk.Web">
<PropertyGroup>
<TargetFramework>netcoreapp3.1</TargetFramework>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="Microsoft.AspNetCore.Identity.EntityFrameworkCore" Version="3.1.4" />
<PackageReference Include="Microsoft.EntityFrameworkCore.InMemory" Version="3.1.4" />
<PackageReference Include="NETCore.MailKit" Version="2.0.2" />
</ItemGroup>
</Project>
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
namespace IdentityExample
{
public class Program
{
public static void Main(string[] args)
{
CreateHostBuilder(args).Build().Run();
}
public static IHostBuilder CreateHostBuilder(string[] args) =>
Host.CreateDefaultBuilder(args)
.ConfigureWebHostDefaults(webBuilder =>
{
webBuilder.UseStartup<Startup>();
});
}
}
{
"iisSettings": {
"windowsAuthentication": false,
"anonymousAuthentication": true,
"iisExpress": {
"applicationUrl": "http://localhost:57417",
"sslPort": 44304
}
},
"profiles": {
"IIS Express": {
"commandName": "IISExpress",
"launchBrowser": true,
"environmentVariables": {
"ASPNETCORE_ENVIRONMENT": "Development"
}
},
"IdentityExample": {
"commandName": "Project",
"launchBrowser": true,
"applicationUrl": "https://localhost:5001;http://localhost:5000",
"environmentVariables": {
"ASPNETCORE_ENVIRONMENT": "Development"
}
}
}
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using IdentityExample.Data;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Identity;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using NETCore.MailKit.Extensions;
using NETCore.MailKit.Infrastructure.Internal;
namespace IdentityExample
{
public class Startup
{
private IConfiguration _config;
public Startup(IConfiguration config)
{
_config = config;
}
public void ConfigureServices(IServiceCollection services)
{
services.AddDbContext<AppDbContext>(config =>
{
config.UseInMemoryDatabase("Memory");
});
// AddIdentity registers the services
services.AddIdentity<IdentityUser, IdentityRole>(config =>
{
config.Password.RequiredLength = 4;
config.Password.RequireDigit = false;
config.Password.RequireNonAlphanumeric = false;
config.Password.RequireUppercase = false;
config.SignIn.RequireConfirmedEmail = true;
})
.AddEntityFrameworkStores<AppDbContext>()
.AddDefaultTokenProviders();
services.ConfigureApplicationCookie(config =>
{
config.Cookie.Name = "Identity.Cookie";
config.LoginPath = "/Home/Login";
});
services.AddMailKit(config => config.UseMailKit(_config.GetSection("Email").Get<MailKitOptions>()));
services.AddControllersWithViews();
}
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
app.UseRouting();
app.UseAuthentication();
app.UseAuthorization();
app.UseEndpoints(endpoints =>
{
endpoints.MapDefaultControllerRoute();
});
}
}
}

<h2>Email has been sent</h2>
<h3>Please verify it.</h3>
\ No newline at end of file
<h1>Home Page</h1>
\ No newline at end of file
<h1>Login Page</h1>
<form action="/Home/Login" method="post">
<input type="text" name="username" value="" />
<input type="text" name="password" value="" />
<button type="submit">Login</button>
</form>
<h1>Register Page</h1>
<form action="/Home/Register" method="post">
<input type="text" name="username" value="" />
<input type="text" name="password" value="" />
<button type="submit">Register</button>
</form>
<h1>Secret Page</h1>
\ No newline at end of file

<h2>Thank you for verifying your email please login here</h2>
<a href="/Home/Login">Go to Login </a>
\ No newline at end of file
{
"Logging": {
"LogLevel": {
"Default": "Information",
"Microsoft": "Warning",
"Microsoft.Hosting.Lifetime": "Information"
}
}
}
{
"Email": {
"Server": "127.0.0.1",
"Port": 25,
"SenderName": "Anton",
"SenderEmail": "meh.far.hdi@gmail.com"
},
"Logging": {
"LogLevel": {
"Default": "Information",
"Microsoft": "Warning",
"Microsoft.Hosting.Lifetime": "Information"
}
},
"AllowedHosts": "*"
}
{
"version": "1.0",
"defaultProvider": "cdnjs",
"libraries": []
}
\ No newline at end of file
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment