Update project structure
This commit is contained in:
72
WebAPI/Controllers/AuthController.cs
Normal file
72
WebAPI/Controllers/AuthController.cs
Normal file
@@ -0,0 +1,72 @@
|
||||
using Google.Apis.Auth;
|
||||
using Google.Apis.Http;
|
||||
using Microsoft.AspNetCore.Mvc;
|
||||
using Microsoft.Extensions.Configuration;
|
||||
using Microsoft.Identity.Client.Platforms.Features.DesktopOs.Kerberos;
|
||||
using Microsoft.IdentityModel.Tokens;
|
||||
using System.Configuration;
|
||||
using System.IdentityModel.Tokens.Jwt;
|
||||
using System.Security.Claims;
|
||||
using System.Text;
|
||||
using WebAPI.Models;
|
||||
|
||||
namespace WebAPI.Controllers
|
||||
{
|
||||
[ApiController]
|
||||
[Route("api/[controller]")]
|
||||
public class AuthController : Controller
|
||||
{
|
||||
private readonly AppDbContext db;
|
||||
private readonly IConfiguration configuration;
|
||||
public AuthController(
|
||||
AppDbContext _db, IConfiguration _configuration)
|
||||
{ db = _db; configuration = _configuration; }
|
||||
|
||||
[HttpPost]
|
||||
[Route("apiToken")]
|
||||
public async Task<IActionResult> apiToken([FromBody] string credential)
|
||||
{
|
||||
var settings = new GoogleJsonWebSignature.ValidationSettings()
|
||||
{
|
||||
Audience = new List<string> { configuration.GetValue<string>("GoogleClientId") }
|
||||
};
|
||||
var payload = await GoogleJsonWebSignature.ValidateAsync(credential, settings);
|
||||
var user = db.Users.Where(x => x.Email == payload.Email).FirstOrDefault();
|
||||
if (user != null)
|
||||
{
|
||||
return Ok(JWTGenerator(user));
|
||||
}
|
||||
else
|
||||
{
|
||||
return BadRequest();
|
||||
}
|
||||
}
|
||||
|
||||
private dynamic JWTGenerator(User user)
|
||||
{
|
||||
var tokenHandler = new JwtSecurityTokenHandler();
|
||||
var key = Encoding.ASCII.GetBytes(configuration.GetValue<string>("Secret"));
|
||||
|
||||
var tokenDescriptor = new SecurityTokenDescriptor
|
||||
{
|
||||
Subject = new ClaimsIdentity(new[] { new Claim("username", user.UserName) }),
|
||||
Expires = DateTime.UtcNow.AddDays(7),
|
||||
SigningCredentials = new SigningCredentials(new SymmetricSecurityKey(key), SecurityAlgorithms.HmacSha512Signature)
|
||||
};
|
||||
var token = tokenHandler.CreateToken(tokenDescriptor);
|
||||
var encrypterToken = tokenHandler.WriteToken(token);
|
||||
|
||||
HttpContext.Response.Cookies.Append("token", encrypterToken,
|
||||
new CookieOptions
|
||||
{
|
||||
Expires = DateTime.Now.AddDays(7),
|
||||
HttpOnly = true,
|
||||
Secure = true,
|
||||
IsEssential = true,
|
||||
SameSite = SameSiteMode.None
|
||||
});
|
||||
|
||||
return new { token = encrypterToken, username = user.UserName };
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user