diff options
Diffstat (limited to 'backend/api')
-rw-r--r-- | backend/api/api/Controllers/AuthController.cs | 8 | ||||
-rw-r--r-- | backend/api/api/Program.cs | 20 | ||||
-rw-r--r-- | backend/api/api/api.csproj | 1 |
3 files changed, 29 insertions, 0 deletions
diff --git a/backend/api/api/Controllers/AuthController.cs b/backend/api/api/Controllers/AuthController.cs index 100ab3ca..c74c579d 100644 --- a/backend/api/api/Controllers/AuthController.cs +++ b/backend/api/api/Controllers/AuthController.cs @@ -2,6 +2,7 @@ using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Mvc; using api.Services; +using Microsoft.AspNetCore.Authorization; namespace api.Controllers { @@ -29,6 +30,13 @@ namespace api.Controllers return Ok(_auth.Login(user)); } + [HttpGet("Auth")] + [Authorize(Roles ="User")] + public async Task<ActionResult<string>> TestAuth() + { + return Ok("works"); + } + } } diff --git a/backend/api/api/Program.cs b/backend/api/api/Program.cs index 4c2d1b9f..550f6ce1 100644 --- a/backend/api/api/Program.cs +++ b/backend/api/api/Program.cs @@ -1,7 +1,10 @@ +using System.Text; using api.Data; using api.Interfaces; using api.Services; +using Microsoft.AspNetCore.Authentication.JwtBearer; using Microsoft.Extensions.Options; +using Microsoft.IdentityModel.Tokens; using MongoDB.Driver; var builder = WebApplication.CreateBuilder(args); @@ -21,9 +24,23 @@ builder.Services.AddSingleton<IUserStoreDatabaseSettings>(sp => builder.Services.AddSingleton<IMongoClient>(s => new MongoClient(builder.Configuration.GetValue<string>("UserStoreDatabaseSettings:ConnectionString"))); +//Inject Dependencies builder.Services.AddScoped<IUserService, UserService>(); builder.Services.AddScoped<IAuthService, AuthService>(); +//Add Authentication +builder.Services.AddAuthentication( + JwtBearerDefaults.AuthenticationScheme).AddJwtBearer(options => { + options.TokenValidationParameters = new TokenValidationParameters + { + ValidateIssuerSigningKey = true, + IssuerSigningKey = new SymmetricSecurityKey(Encoding.ASCII.GetBytes(builder.Configuration.GetSection("AppSettings:JwtToken").Value)), + ValidateIssuer=false, + ValidateAudience=false + }; + + }); + builder.Services.AddControllers(); @@ -39,6 +56,9 @@ app.UseCors( // Configure the HTTP request pipeline. +//Add Authentication +app.UseAuthentication(); + app.UseAuthorization(); app.MapControllers(); diff --git a/backend/api/api/api.csproj b/backend/api/api/api.csproj index 1451fa77..6081cd21 100644 --- a/backend/api/api/api.csproj +++ b/backend/api/api/api.csproj @@ -8,6 +8,7 @@ <ItemGroup> <PackageReference Include="BCrypt.Net-Next" Version="4.0.3" /> + <PackageReference Include="Microsoft.AspNetCore.Authentication.JwtBearer" Version="6.0.3" /> <PackageReference Include="Microsoft.IdentityModel.Tokens" Version="6.16.0" /> <PackageReference Include="System.IdentityModel.Tokens.Jwt" Version="6.16.0" /> </ItemGroup> |