Skip to content

Commit

Permalink
Merge pull request #14 from babisque/authorization/feature/sso-implem…
Browse files Browse the repository at this point in the history
…entation

Endpoint to generate Bearer Token is done.
  • Loading branch information
babisque authored Jun 26, 2024
2 parents eb7d31a + e74f186 commit 8ccc1cf
Show file tree
Hide file tree
Showing 2 changed files with 61 additions and 0 deletions.
54 changes: 54 additions & 0 deletions Authorization/Authorization.API/Controllers/TokenController.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,54 @@
using System.IdentityModel.Tokens.Jwt;
using System.Security.Claims;
using System.Text;
using Authorization.DTO.Token;
using Microsoft.AspNetCore.Identity;
using Microsoft.AspNetCore.Mvc;
using Microsoft.IdentityModel.Tokens;

namespace Authorization.API.Controllers;

[ApiController]
[Route("/[controller]")]
public class TokenController : ControllerBase
{
private UserManager<IdentityUser> _userManager;

public TokenController(UserManager<IdentityUser> userManager)
{
_userManager = userManager;
}

[HttpPost]
public async Task<ActionResult> Post(TokenPostReq req)
{
var user = await _userManager.FindByNameAsync(req.Username);
if (user == null || !(await _userManager.CheckPasswordAsync(user, req.Password)))
return BadRequest("User or password is incorrect.");

var claims = await _userManager.GetClaimsAsync(user);
var roles = await _userManager.GetRolesAsync(user);

var key = Encoding.ASCII.GetBytes(
"QWERTYUIOPASDFGHJKLZXCVBNMqwertyuiopasdfghjklzxcvbnm,1234567890AOkopvdnsioHGYUASGVBI");
var tokenDescriptor = new SecurityTokenDescriptor
{
Subject = new ClaimsIdentity(new Claim[]
{
new Claim(ClaimTypes.Email, user.Email),
}),
SigningCredentials =
new SigningCredentials(new SymmetricSecurityKey(key), SecurityAlgorithms.HmacSha256Signature),
Audience = "eCommerce",
Issuer = "Issuer"
};

var tokenHandler = new JwtSecurityTokenHandler();
var token = tokenHandler.CreateToken(tokenDescriptor);

return Ok(new
{
token = tokenHandler.WriteToken(token)
});
}
}
7 changes: 7 additions & 0 deletions Authorization/Authorization.Core/DTO/Token/TokenPostReq.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
namespace Authorization.DTO.Token;

public class TokenPostReq
{
public string Username { get; set; }
public string Password { get; set; }
}

0 comments on commit 8ccc1cf

Please sign in to comment.