mycorerepository/MyCore/Controllers/TokenController.cs
2019-07-14 02:39:28 +02:00

91 lines
2.9 KiB
C#

using System;
using System.Collections.Generic;
using System.IdentityModel.Tokens.Jwt;
using System.Linq;
using System.Security.Claims;
using System.Security.Cryptography;
using System.Text;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.IdentityModel.Tokens;
using MyCore.Models;
namespace MyCore.Controllers
{
[Authorize]
[Route("api/token")]
[ApiController]
public class TokenController : ControllerBase
{
[AllowAnonymous]
[HttpPost]
public ActionResult<UserInfo> Create(string username, string password)
{
var test = GenerateSHA256String(password);
if (IsValidUserAndPasswordCombination(username, password))
{
UserInfo user = new UserInfo();
user.FirstName = "Thomas";
user.LastName = "Fransolet";
user.Token = GenerateToken(username).ToString();
return user;
}
//return new ObjectResult("{\"Token\":\""+GenerateToken(username)+"\"}");
return BadRequest();
}
private object GenerateToken(string username)
{
var secretKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes("%G2YZ=\tgN7fC9M$FXDt#q*a&]Z")); // Put the secret in a file or something
var claims = new Claim[] {
new Claim(ClaimTypes.Name, username),
new Claim(JwtRegisteredClaimNames.Email, "john.doe@blinkingcaret.com"),
new Claim(ClaimTypes.Role, "Admin")
};
var token = new JwtSecurityToken(
issuer: "MyCore App",
audience: "Miotecher",
claims: claims,
notBefore: DateTime.Now,
expires: DateTime.Now.AddDays(28),
signingCredentials: new SigningCredentials(secretKey, SecurityAlgorithms.HmacSha256)
);
string jwtToken = new JwtSecurityTokenHandler().WriteToken(token);
return jwtToken;
}
private bool IsValidUserAndPasswordCombination(string username, string password)
{
if (username == "Thomas" && password == "MonsieurMagic") { return true; }
else return false;
}
public static string GenerateSHA256String(string inputString)
{
SHA256 sha256 = SHA256Managed.Create();
byte[] bytes = Encoding.UTF8.GetBytes(inputString);
byte[] hash = sha256.ComputeHash(bytes);
return GetStringFromHash(hash);
}
private static string GetStringFromHash(byte[] hash)
{
StringBuilder result = new StringBuilder();
for (int i = 0; i < hash.Length; i++)
{
result.Append(hash[i].ToString("X2"));
}
return result.ToString();
}
}
}