namespace InlogExampleService.Controllers { using System; using System.Collections.Generic; using System.IdentityModel.Tokens.Jwt; using System.Linq; using System.Security.Claims; using System.Text; using System.Threading.Tasks; using InlogExampleService.Models.Dtos; using Microsoft.AspNet.OData; using Microsoft.AspNet.OData.Routing; using Microsoft.AspNetCore.Identity; using Microsoft.AspNetCore.Mvc; using Microsoft.Extensions.Configuration; using Microsoft.IdentityModel.Tokens; public class AccountController : ODataController { public AccountController( UserManager userManager, SignInManager signInManager, IConfiguration configuration) { this.UserManager = userManager; this.SignInManager = signInManager; this.Configuration = configuration; } private SignInManager SignInManager { get; } private UserManager UserManager { get; } private IConfiguration Configuration { get; } [HttpPost] [ODataRoute("Inloggen")] public async Task Inloggen([FromBody] InlogDto inlogGegevens) { var user = await this.UserManager.FindByNameAsync(inlogGegevens.Gebruikersnaam); if (user is null) { return this.BadRequest(new { message = "Gebruikersnaam of wachtwoord is fout" }); } var result = await this.SignInManager.CheckPasswordSignInAsync(user, inlogGegevens.Wachtwoord, true); if (!result.Succeeded) { return this.BadRequest(new { message = "Gebruikersnaam of wachtwoord is fout" }); } var jwt = await this.GenerateJwtTokenAsync(user); var resultaat = new { jwt, }; return this.Ok(resultaat); } private async Task GenerateJwtTokenAsync(Models.InlogExampleUser user) { var claims = new List { new Claim(JwtRegisteredClaimNames.Sub, user.UserName), new Claim(JwtRegisteredClaimNames.Jti, Guid.NewGuid().ToString()), new Claim(ClaimTypes.NameIdentifier, user.Id), new Claim("AdministratieId", user.AdministratieId.ToString()), new Claim("InspecteurId", user.InspecteurId.ToString()), }; var key = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(this.Configuration["JwtKey"])); var creds = new SigningCredentials(key, SecurityAlgorithms.HmacSha256); var expires = DateTime.Now.AddDays(Convert.ToDouble(this.Configuration["JwtExpireDays"])); var roles = await this.UserManager.GetRolesAsync(user); claims.AddRange(roles.Select(x => new Claim(ClaimTypes.Role, x))); var token = new JwtSecurityToken( issuer: this.Configuration["JwtIssuer"], audience: this.Configuration["JwtIssuer"], claims: claims, expires: expires, signingCredentials: creds); return new JwtSecurityTokenHandler().WriteToken(token); } } }