Compare commits

...

3 Commits

  1. 46
      Controllers/AuthController.cs
  2. 2
      Controllers/BlogPostController.cs
  3. 8
      DTO/UserDTO.cs
  4. 14
      Models/UserIdentity.cs
  5. 55
      Program.cs
  6. 6
      appsettings.json
  7. 2
      backend.csproj

46
Controllers/AuthController.cs

@ -0,0 +1,46 @@ @@ -0,0 +1,46 @@
using System.IdentityModel.Tokens.Jwt;
using System.Security.Claims;
using System.Text;
using Microsoft.AspNetCore.Mvc;
using Microsoft.IdentityModel.Tokens;
namespace backend.Controllers;
[ApiController]
[Route("[controller]")]
public class AuthController : ControllerBase
{
public IConfiguration _configuration;
public AuthController(IConfiguration configuration)
{
_configuration = configuration;
}
[HttpPost("login")]
public async Task<IActionResult> Login(string username, string password)
{
if (username == "" || password == "")
{
return BadRequest("Invalid username or password");
}
if (username == "test" && password == "test")
{
var secretKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(_configuration["Jwt:secret"]));
var signinCredentials = new SigningCredentials(secretKey, SecurityAlgorithms.HmacSha256);
var tokeOptions = new JwtSecurityToken(
issuer: _configuration["Jwt:Issuer"],
audience: _configuration["Jwt:Audience"],
claims: new List<Claim>(),
expires: DateTime.Now.AddDays(1),
signingCredentials: signinCredentials
);
var tokenString = new JwtSecurityTokenHandler().WriteToken(tokeOptions);
return Ok(new { Token = tokenString });
}
return BadRequest("Invalid username or password");
}
}

2
Controllers/BlogPostController.cs

@ -1,5 +1,6 @@ @@ -1,5 +1,6 @@
using backend.Models;
using backend.Services;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
namespace backend.Controllers;
@ -26,6 +27,7 @@ public class BlogPostController: ControllerBase @@ -26,6 +27,7 @@ public class BlogPostController: ControllerBase
public async Task<List<BlogPost>> GetLast(int n) =>
await _blogPostService.GetLastNPostsAsync(n);
[Authorize]
[HttpPost]
public async Task<IActionResult> Post([FromBody]BlogPost post)
{

8
DTO/UserDTO.cs

@ -0,0 +1,8 @@ @@ -0,0 +1,8 @@
namespace backend.DTO;
public class UserDTO
{
public string UserName { get; set; }
public string? Email { get; set; }
public string Password { get; set; }
}

14
Models/UserIdentity.cs

@ -0,0 +1,14 @@ @@ -0,0 +1,14 @@
using MongoDB.Bson.Serialization.Attributes;
namespace backend.Models;
public class UserIdentity
{
[BsonId]
[BsonRepresentation(MongoDB.Bson.BsonType.ObjectId)]
public string Id { get; set; }
public string UserName { get; set; }
public string Password { get; set; }
public string Email { get; set; }
public string Role { get; set; }
}

55
Program.cs

@ -1,5 +1,9 @@ @@ -1,5 +1,9 @@
using System.Text;
using backend.Models;
using backend.Services;
using Microsoft.AspNetCore.Authentication.JwtBearer;
using Microsoft.IdentityModel.Tokens;
using Microsoft.OpenApi.Models;
var builder = WebApplication.CreateBuilder(args);
@ -7,14 +11,62 @@ var builder = WebApplication.CreateBuilder(args); @@ -7,14 +11,62 @@ var builder = WebApplication.CreateBuilder(args);
builder.Services.Configure<BlogDatabaseSettings>(builder.Configuration.GetSection("BlogDatabase"));
builder.Services.AddSingleton<UserService>();
builder.Services.AddSingleton<BlogPostService>();
builder.Services.AddControllers();
//Authentication
builder.Services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme).AddJwtBearer(
options =>
{
options.RequireHttpsMetadata = false;
options.SaveToken = false;
options.TokenValidationParameters = new TokenValidationParameters
{
ValidateIssuer = true,
ValidateAudience = true,
ValidateLifetime = true,
ValidIssuer = builder.Configuration["Jwt:Issuer"],
ValidAudience = builder.Configuration["Jwt:Audience"],
IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(builder.Configuration["Jwt:secret"]))
};
});
// Learn more about configuring Swagger/OpenAPI at https://aka.ms/aspnetcore/swashbuckle
builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen();
builder.Services.AddSwaggerGen(c =>
{
c.SwaggerDoc("v1", new OpenApiInfo { Title = "WebServer", Version = "v1" });
// We need to tell swagger that we want to support authentication
c.AddSecurityDefinition("Bearer", new OpenApiSecurityScheme()
{
Name = "Authorization",
Type = SecuritySchemeType.Http,
Scheme = "Bearer",
In = ParameterLocation.Header,
BearerFormat = "Bearer",
Description = "The Bearer token needed to access the initial part of the api.",
});
// And again since once is not enough?
c.AddSecurityRequirement(new OpenApiSecurityRequirement
{
{
new OpenApiSecurityScheme
{
Reference = new OpenApiReference
{
Type = ReferenceType.SecurityScheme,
Id = "Bearer",
},
},
Array.Empty<string>()
},
});
});
var app = builder.Build();
@ -28,6 +80,7 @@ if (app.Environment.IsDevelopment()) @@ -28,6 +80,7 @@ if (app.Environment.IsDevelopment())
app.UseHttpsRedirection();
app.UseAuthentication();
app.UseAuthorization();
app.MapControllers();

6
appsettings.json

@ -1,4 +1,10 @@ @@ -1,4 +1,10 @@
{
"Jwt": {
"secret": "s6v9y$B&E)H@McQf",
"Issuer": "http://www.olivierboeren.nl",
"Audience": "http://www.olivierboeren.nl",
},
"BlogDatabase": {
"ConnectionString": "mongodb://localhost:27017",
"DatabaseName": "Blog",

2
backend.csproj

@ -7,8 +7,10 @@ @@ -7,8 +7,10 @@
</PropertyGroup>
<ItemGroup>
<PackageReference Include="Microsoft.AspNetCore.Authentication.JwtBearer" Version="6.0.5" />
<PackageReference Include="MongoDB.Driver" Version="2.15.1" />
<PackageReference Include="Swashbuckle.AspNetCore" Version="6.2.3" />
<PackageReference Include="System.IdentityModel.Tokens.Jwt" Version="6.18.0" />
</ItemGroup>
</Project>

Loading…
Cancel
Save