.Net Core : Token based Authentication in webAPI
Startup.cs
public void ConfigureServices(IServiceCollection services)
{
services.AddDbContextPool<AppDbContext>(options => options.UseSqlServer(Configuration.GetConnectionString("DotNetCoreDB")));
services.AddIdentity<IdentityUser, IdentityRole>()
.AddEntityFrameworkStores<AppDbContext>()
.AddDefaultTokenProviders();
services.AddAuthentication(options =>
{
options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
options.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
options.DefaultScheme = JwtBearerDefaults.AuthenticationScheme;
})
.AddJwtBearer(options =>
{
options.SaveToken = true;
options.RequireHttpsMetadata = false;
options.TokenValidationParameters = new Microsoft.IdentityModel.Tokens.TokenValidationParameters()
{
ValidateIssuer = true,
ValidateAudience = true,
ValidAudience = "http://mydomain.com",
ValidIssuer = "http://mydomain.com",
IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes("Secret 1234567890 phase"))
};
});
services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1);
}
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
app.UseAuthentication();
app.UseMvc();
}
EmployeeController.cs
[Route("api/[controller]")]
[ApiController]
[Authorize]
public class EmployeeController : Controller
{
private readonly UserManager<IdentityUser> userManager;
private readonly SignInManager<IdentityUser> signInManager;
public EmployeeController(UserManager<IdentityUser> userManager, SignInManager<IdentityUser> signInManager)
{
this.userManager = userManager;
this.signInManager = signInManager;
}
[HttpGet]
public ActionResult<IEnumerable<string>> Get()
{
return userManager.Users.Select(u => u.UserName).ToArray();
}
[HttpPost]
[AllowAnonymous]
[Route("Register")]
public async Task<JsonResult> Post(VMRegister vmRegister)
{
IdentityResult result = new IdentityResult();
string errorMessage = "success";
if (ModelState.IsValid)
{
var user = new IdentityUser
{
UserName = vmRegister.EmailId,
Email = vmRegister.EmailId
};
result = await userManager.CreateAsync(user, vmRegister.Password);
if (result.Succeeded)
{
//to Signin user
//signInManager.SignInAsync(user, isPersistent: false).Start();
}
else
{
if (result.Errors.Count() > 0)
{
errorMessage = "";
foreach (var error in result.Errors)
{
errorMessage += error.Description;
}
}
}
}
return Json(new { id = "1", message = errorMessage });
}
[HttpPost]
[AllowAnonymous]
[Route("Login")]
public async Task<IActionResult> Login(VMLogin vmLogin)
{
var user = await userManager.FindByNameAsync(vmLogin.EmailId);
if (user != null && await userManager.CheckPasswordAsync(user, vmLogin.Password))
{
var claims = new[]
{
new Claim(JwtRegisteredClaimNames.Sub, user.UserName),
new Claim(JwtRegisteredClaimNames.Jti, Guid.NewGuid().ToString())
};
var signinKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes("Secret 1234567890 phase"));
var token = new JwtSecurityToken(
issuer: "http://mydomain.com",
audience: "http://mydomain.com",
expires: DateTime.UtcNow.AddHours(1),
claims: claims,
signingCredentials: new Microsoft.IdentityModel.Tokens.SigningCredentials(signinKey, SecurityAlgorithms.HmacSha256)
);
return Ok(
new
{
token = new JwtSecurityTokenHandler().WriteToken(token),
expiration = token.ValidTo
});
}
return Unauthorized();
}
}
Testing
No comments:
Post a Comment