This commit is contained in:
Charles Showalter 2022-05-19 15:47:12 -07:00
parent 2bd34ec022
commit 0586c201c5
7 changed files with 72 additions and 9 deletions

View File

@ -1,6 +1,9 @@
using System.Security.Claims;
using API.Dtos; using API.Dtos;
using API.Errors; using API.Errors;
using Core.Entities.Identity; using Core.Entities.Identity;
using Core.Interfaces;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Identity; using Microsoft.AspNetCore.Identity;
using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.Mvc;
@ -10,12 +13,43 @@ namespace API.Controllers
{ {
private readonly UserManager<AppUser> _userManager; private readonly UserManager<AppUser> _userManager;
private readonly SignInManager<AppUser> _signInManager; private readonly SignInManager<AppUser> _signInManager;
public AccountController(UserManager<AppUser> userManager, SignInManager<AppUser> signInManager) private readonly ITokenService _tokenService;
public AccountController(UserManager<AppUser> userManager, SignInManager<AppUser> signInManager, ITokenService tokenService)
{ {
_tokenService = tokenService;
_signInManager = signInManager; _signInManager = signInManager;
_userManager = userManager; _userManager = userManager;
} }
[Authorize]
[HttpGet]
public async Task<ActionResult<UserDto>> GetCurrentUser()
{
var email = User.FindFirstValue(ClaimTypes.Email);
var user = await _userManager.FindByEmailAsync(email);
return new UserDto
{
Email = user.Email,
Token = _tokenService.CreateToken(user),
DisplayName = user.DisplayName
};
}
[HttpGet("emailexists")]
public async Task<ActionResult<bool>> CheckEmailExistsAsync([FromQuery] string email){
return await _userManager.FindByEmailAsync(email) != null;
}
[Authorize]
[HttpGet("address")]
public async Task<ActionResult<Address>> GetUserAddress()
{
var email = User.FindFirstValue(ClaimTypes.Email);
var user = await _userManager.FindByEmailAsync(email);
return user.Address;
}
[HttpPost("login")] [HttpPost("login")]
public async Task<ActionResult<UserDto>> Login(LoginDto loginDto) public async Task<ActionResult<UserDto>> Login(LoginDto loginDto)
{ {
@ -26,7 +60,7 @@ namespace API.Controllers
return new UserDto return new UserDto
{ {
Email = user.Email, Email = user.Email,
Token = "This will be a token", Token = _tokenService.CreateToken(user),
DisplayName = user.DisplayName DisplayName = user.DisplayName
}; };
} }
@ -46,9 +80,10 @@ namespace API.Controllers
return new UserDto return new UserDto
{ {
DisplayName = user.DisplayName, DisplayName = user.DisplayName,
Token = "This will be a token", Token = _tokenService.CreateToken(user),
Email = user.Email Email = user.Email
}; };
} }
} }
} }

View File

@ -1,5 +1,6 @@
using API.Errors; using API.Errors;
using Infrastructure.Data; using Infrastructure.Data;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.Mvc;
namespace API.Controllers namespace API.Controllers
@ -12,6 +13,13 @@ namespace API.Controllers
_context = context; _context = context;
} }
[HttpGet("testauth")]
[Authorize]
public ActionResult<string> GetSecretText()
{
return "secret stuff";
}
[HttpGet("notfound")] [HttpGet("notfound")]
public ActionResult GetNotFoundRequest() public ActionResult GetNotFoundRequest()
{ {

View File

@ -1,6 +1,7 @@
using API.Errors; using API.Errors;
using Core.Interfaces; using Core.Interfaces;
using Infrastructure.Data; using Infrastructure.Data;
using Infrastructure.Services;
using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.Mvc;
namespace API.Extensions namespace API.Extensions
@ -9,6 +10,7 @@ namespace API.Extensions
{ {
public static IServiceCollection AddApplicationServices(this IServiceCollection services) public static IServiceCollection AddApplicationServices(this IServiceCollection services)
{ {
services.AddScoped<ITokenService, TokenService>();
services.AddScoped<iProductRepository, ProductRepository>(); services.AddScoped<iProductRepository, ProductRepository>();
services.AddScoped<IBasketRepository, BasketRepository>(); services.AddScoped<IBasketRepository, BasketRepository>();
services.AddScoped(typeof(IGenericRepository<>), (typeof(GenericRepository<>))); services.AddScoped(typeof(IGenericRepository<>), (typeof(GenericRepository<>)));

View File

@ -1,19 +1,32 @@
using System.Text;
using Core.Entities.Identity; using Core.Entities.Identity;
using Infrastructure.Identity; using Infrastructure.Identity;
using Microsoft.AspNetCore.Authentication.JwtBearer;
using Microsoft.AspNetCore.Identity; using Microsoft.AspNetCore.Identity;
using Microsoft.IdentityModel.Tokens;
namespace API.Extensions namespace API.Extensions
{ {
public static class IdentityServiceExtensions public static class IdentityServiceExtensions
{ {
public static IServiceCollection AddIdentityServices(this IServiceCollection services) public static IServiceCollection AddIdentityServices(this IServiceCollection services, IConfiguration config)
{ {
var builder = services.AddIdentityCore<AppUser>(); var builder = services.AddIdentityCore<AppUser>();
builder = new IdentityBuilder(builder.UserType, builder.Services); builder = new IdentityBuilder(builder.UserType, builder.Services);
builder.AddEntityFrameworkStores<AppIdentityDbContext>(); builder.AddEntityFrameworkStores<AppIdentityDbContext>();
builder.AddSignInManager<SignInManager<AppUser>>(); builder.AddSignInManager<SignInManager<AppUser>>();
services.AddAuthentication(); services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
.AddJwtBearer(options =>{
options.TokenValidationParameters = new TokenValidationParameters
{
ValidateIssuerSigningKey = true,
IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(config["Token:Key"])),
ValidIssuer = config["Token:Issuer"],
ValidateIssuer = true,
ValidateAudience = false
};
});
return services; return services;
} }

View File

@ -23,7 +23,7 @@ namespace API
services.AddControllers(); services.AddControllers();
services.AddApplicationServices(); services.AddApplicationServices();
services.AddIdentityServices(); services.AddIdentityServices(_config);
services.AddSwaggerDocumentation(); services.AddSwaggerDocumentation();
services.AddDbContext<StoreContext>(x => x.UseSqlite(_config.GetConnectionString("DefaultConnection"))); services.AddDbContext<StoreContext>(x => x.UseSqlite(_config.GetConnectionString("DefaultConnection")));
services.AddDbContext<AppIdentityDbContext>(x => x.UseSqlite(_config.GetConnectionString("IdentityConnection"))); services.AddDbContext<AppIdentityDbContext>(x => x.UseSqlite(_config.GetConnectionString("IdentityConnection")));
@ -51,6 +51,7 @@ namespace API
app.UseRouting(); app.UseRouting();
app.UseStaticFiles(); app.UseStaticFiles();
app.UseCors("CorsPolicy"); app.UseCors("CorsPolicy");
app.UseAuthentication();
app.UseAuthorization(); app.UseAuthorization();
app.UseSwaggerDocumentation(); app.UseSwaggerDocumentation();
app.UseEndpoints(endpoints => app.UseEndpoints(endpoints =>

View File

@ -2,7 +2,7 @@
"Logging": { "Logging": {
"LogLevel": { "LogLevel": {
"Default": "Information", "Default": "Information",
"Microsoft.AspNetCore": "Warning" "Microsoft.AspNetCore": "Information"
} }
}, },
"ConnectionStrings": { "ConnectionStrings": {
@ -10,5 +10,9 @@
"IdentityConnection": "Data source=indentity.db", "IdentityConnection": "Data source=indentity.db",
"Redis": "localhost" "Redis": "localhost"
}, },
"Token": {
"Key": "super secret key",
"Issuer": "https://localhost:5001"
},
"ApiUrl": "https://localhost:5001/" "ApiUrl": "https://localhost:5001/"
} }

View File

@ -22,8 +22,8 @@ namespace Infrastructure.Services
{ {
var claims = new List<Claim> var claims = new List<Claim>
{ {
new Claim(ClaimTypes.Email, user.Email), new Claim(JwtRegisteredClaimNames.Email, user.Email),
new Claim(ClaimTypes.GivenName, user.DisplayName) new Claim(JwtRegisteredClaimNames.GivenName, user.DisplayName)
}; };
var creds = new SigningCredentials(_key, SecurityAlgorithms.HmacSha512Signature); var creds = new SigningCredentials(_key, SecurityAlgorithms.HmacSha512Signature);