mirror of
https://bitbucket.org/myhomie/mycorerepository.git
synced 2025-12-06 17:51:20 +00:00
60 lines
1.9 KiB
C#
60 lines
1.9 KiB
C#
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 Microsoft.AspNetCore.Authorization;
|
|
using Microsoft.AspNetCore.Http;
|
|
using Microsoft.AspNetCore.Mvc;
|
|
using Microsoft.IdentityModel.Tokens;
|
|
|
|
namespace MyCore.Controllers
|
|
{
|
|
[Authorize]
|
|
[Route("api/token")]
|
|
[ApiController]
|
|
public class TokenController : ControllerBase
|
|
{
|
|
|
|
[AllowAnonymous]
|
|
[HttpPost]
|
|
public IActionResult Create(string username, string password)
|
|
{
|
|
if (IsValidUserAndPasswordCombination(username, password))
|
|
return new ObjectResult(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;
|
|
}
|
|
}
|
|
} |