Build a Instagram like clone called Chymin using ASP.net Core and Angular9 — part 2

namespace chymininstagramapp.Data.Models
{
using Microsoft.AspNetCore.Identity;
public class User: IdentityUser
{
}
}
User class inherits from identityUser class
chymininstagramDbContext.cs class
Startup.cs
  1. Under Controller folder create a new class called IdentityController.cs
    Add the following:
namespace chymin_app.Controllers
{
using System;
using System.IdentityModel.Tokens.Jwt;
using System.Security.Claims;
using System.Text;
using System.Threading.Tasks;
using chymin_app.Models;
using chymin_app.Models.Identity;
using Microsoft.AspNetCore.Identity;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Options;
using Microsoft.IdentityModel.Tokens;

public class IdentityController:ApiController
{
private readonly UserManager
<User> userManager;
private readonly AppSettings appSettings;
public IdentityController(
UserManager
<User> userManager,
IOptions
<AppSettings> appSettings)
{
this.userManager = userManager;
this.appSettings = appSettings.Value;
}
[Route(nameof(Register))]

public async Task
<ActionResult> Register(RegisterRequestModel model)
{
var user = new User
{
Email = model.Email,
UserName = model.Username
};

var results = await this.userManager.CreateAsync(user,model.Password);
if (results.Succeeded)
{
return Ok();
}
return BadRequest(results.Errors);

}
[Route(nameof(Login))]
public async Task
<ActionResult
<string>> Login(LoginRequestModel model)
{
var user = await this.userManager.FindByNameAsync(model.Username);
if (user == null)
{
return Unauthorized();
}
var passwordValid = await this.userManager.CheckPasswordAsync(user, model.Password);
if (!passwordValid)
{
return Unauthorized();
}
// generate token that is valid for 7 days
var tokenHandler = new JwtSecurityTokenHandler();
var key = Encoding.ASCII.GetBytes(this.appSettings.Secret);
var tokenDescriptor = new SecurityTokenDescriptor
{
Subject = new ClaimsIdentity(new[] { new Claim(“id”, user.Id.ToString()) }),
Expires = DateTime.UtcNow.AddDays(7),
SigningCredentials = new SigningCredentials(new SymmetricSecurityKey(key), SecurityAlgorithms.HmacSha256Signature)
};
var token = tokenHandler.CreateToken(tokenDescriptor);
var encryptedToken = tokenHandler.WriteToken(token);
return encryptedToken;
}
private string generateJwtToken(User user)
{
// generate token that is valid for 7 days
var tokenHandler = new JwtSecurityTokenHandler();
var key = Encoding.ASCII.GetBytes(appSettings.Secret);
var tokenDescriptor = new SecurityTokenDescriptor
{
Subject = new ClaimsIdentity(new[] { new Claim(“id”, user.Id.ToString()) }),
Expires = DateTime.UtcNow.AddDays(7),
SigningCredentials = new SigningCredentials(new SymmetricSecurityKey(key), SecurityAlgorithms.HmacSha256Signature)
};
var token = tokenHandler.CreateToken(tokenDescriptor);
return tokenHandler.WriteToken(token);
}
}
}
namespace chymin_app.Controllers
{
using Microsoft.AspNetCore.Mvc;
[ApiController]
[Route(“[controller]”)]
public abstract class ApiController:ControllerBase
{
}
}
using chymin_app.Data;using Microsoft.AspNetCore.Builder;using Microsoft.EntityFrameworkCore;using Microsoft.Extensions.DependencyInjection;namespace chymin_app.Infrastructure{public static class ApplicationBuilderExtentions{public static void ApplyMigration(this IApplicationBuilder app){  using var services = app.ApplicationServices.CreateScope();
var dbContext = services.ServiceProvider.GetService<chymin_app_DbContext>();
dbContext.Database.Migrate();
}}}
Register json example{“Username”: “kmangal3”,“email”: “jacop@jem.com”,“password”: “igman143”}
{"ApplicationSettings": {"Secret": "SOME MAGIC UNICORNS GENERATE THIS SECRET"},
Controller so far, this will be refactored but this is what we have so far in this tutorial
Api controller class
using System;
using System.IdentityModel.Tokens.Jwt;
using System.Security.Claims;
using System.Text;
using System.Threading.Tasks;
using Server_Chymin.Models;
using Microsoft.AspNetCore.Identity;
using Microsoft.AspNetCore.Mvc;
using Server_Chymin.Models.Identity;
using Microsoft.Extensions.Options;
using Microsoft.IdentityModel.Tokens;
namespace Server_Chymin.Controllers
{
public class IdentityController : ApiController
{
private readonly UserManager<User> userManager;
private readonly AppSettings appSettings;
public IdentityController(UserManager<User> userManager,IOptions<AppSettings> appSettings){this.userManager = userManager;this.appSettings = appSettings.Value;}//=> this.userManager = userManager;[Route(nameof(Register))]public async Task<ActionResult> Register(RegisterUserRequestModel model){var user = new User{Email = model.Email,UserName = model.Username};var results = await this.userManager.CreateAsync(user, model.Password);if (results.Succeeded){return Ok();}return BadRequest(results.Errors);}[Route(nameof(Login))]public async Task<ActionResult<string>> Login(LoginRequestModel model){var user = await this.userManager.FindByNameAsync(model.Username);if (user==null){return Unauthorized();}var passwordValid = await this.userManager.CheckPasswordAsync(user,model.Password);if(!passwordValid){return Unauthorized();}// generate token that is valid for 7 daysvar tokenHandler = new JwtSecurityTokenHandler();var key = Encoding.ASCII.GetBytes(this.appSettings.Secret);var tokenDescriptor = new SecurityTokenDescriptor{Subject = new ClaimsIdentity(new[]{new Claim(ClaimTypes.Name, user.Id.ToString())}),Expires = DateTime.UtcNow.AddDays(7),SigningCredentials = new SigningCredentials(new SymmetricSecurityKey(key), SecurityAlgorithms.HmacSha256Signature)};var token = tokenHandler.CreateToken(tokenDescriptor);var encryptedToken = tokenHandler.WriteToken(token);//return tokenHandler.WriteToken(token);return encryptedToken;}}}
namespace Server_Chymin
{
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.HttpsPolicy;
using Microsoft.AspNetCore.Identity;
using Microsoft.AspNetCore.Identity.UI;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Server_Chymin.Data;
using Server_Chymin.Infrastructure.Extentions;
using Server_Chymin.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
public class Startup
{
public Startup(IConfiguration configuration)
{
Configuration = configuration;
}
public IConfiguration Configuration { get; }// This method gets called by the runtime. Use this method to add services to the container.
public void ConfigureServices(IServiceCollection services)
{
services.AddDbContext<ChyminDbContext>(options =>
options.UseSqlServer(
this.Configuration.GetConnectionString("DefaultConnection")));
services.AddDatabaseDeveloperPageExceptionFilter();
services
.AddIdentity<User,IdentityRole>(options =>
{
options.Password.RequiredLength = 6;
options.Password.RequireDigit = false;
options.Password.RequireLowercase = false;
options.Password.RequireNonAlphanumeric = false;
options.Password.RequireUppercase = false;
})
.AddEntityFrameworkStores<ChyminDbContext>();
// configure strongly typed settings object
//services.Configure<AppSettings>(Configuration.GetSection("AppSettings"));
var appsettingsSection = this.Configuration.GetSection("ApplicationSettings");
services.Configure < AppSettings>(appsettingsSection);
// configure DI for application services
//services.AddScoped<IUserService, UserService>();
services.AddControllers();}// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
if(env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}

app.UseRouting();
app.UseAuthentication();
app.UseAuthorization();
app.UseEndpoints(endpoints =>
{
endpoints.MapControllers();

});
app.ApplyMigrations();
}
}
}
{
"ApplicationSettings": {
"Secret": "SOME MAGIC UNICORNS GENERATE THIS SECRET"
},
"ConnectionStrings": {
"DefaultConnection": "Server=(localdb)\\mssqllocaldb;Database=aspnet-Server_Chymin-6E663CF9-5393-428A-BD84-00C9B51361DB;Trusted_Connection=True;MultipleActiveResultSets=true"
},
"AppSettings": {
"Token": "This is Token"
},
"Logging": {
"LogLevel": {
"Default": "Information",
"Microsoft": "Warning",
"Microsoft.Hosting.Lifetime": "Information"
}
},
"AllowedHosts": "*"
}
namespace Server_Chymin
{
public class AppSettings
{
public string Secret { get; set; }
}
}
Notice we get authentication Key or token
[Authorize]public ActionResult Get(){return Ok("WORKS");}

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Khemlall Mangal

Khemlall Mangal

I am a passionate coder, QA Engineer, and someone who enjoys the outdoors.