diff --git a/exercise.wwwapi/Configuration/ConfigurationSettings.cs b/exercise.wwwapi/Configuration/ConfigurationSettings.cs new file mode 100644 index 0000000..be681a0 --- /dev/null +++ b/exercise.wwwapi/Configuration/ConfigurationSettings.cs @@ -0,0 +1,15 @@ +namespace exercise.wwwapi.Configuration +{ + public class ConfigurationSettings : IConfigurationSettings + { + IConfiguration _configuration; + public ConfigurationSettings() + { + _configuration = new ConfigurationBuilder().AddJsonFile("appsettings.json").Build(); + } + public string GetValue(string key) + { + return _configuration.GetValue(key)!; + } + } +} diff --git a/exercise.wwwapi/Configuration/IConfigurationSettings.cs b/exercise.wwwapi/Configuration/IConfigurationSettings.cs new file mode 100644 index 0000000..d06bc43 --- /dev/null +++ b/exercise.wwwapi/Configuration/IConfigurationSettings.cs @@ -0,0 +1,7 @@ +namespace exercise.wwwapi.Configuration +{ + public interface IConfigurationSettings + { + string GetValue(string key); + } +} diff --git a/exercise.wwwapi/DTO/Requests/BlogPost.cs b/exercise.wwwapi/DTO/Requests/BlogPost.cs new file mode 100644 index 0000000..86dafe5 --- /dev/null +++ b/exercise.wwwapi/DTO/Requests/BlogPost.cs @@ -0,0 +1,8 @@ +namespace exercise.wwwapi.DTO.Requests +{ + public class BlogPost + { + public string Header { get; set; } + public string Text { get; set; } + } +} diff --git a/exercise.wwwapi/DTO/Requests/BlogPut.cs b/exercise.wwwapi/DTO/Requests/BlogPut.cs new file mode 100644 index 0000000..680730b --- /dev/null +++ b/exercise.wwwapi/DTO/Requests/BlogPut.cs @@ -0,0 +1,8 @@ +namespace exercise.wwwapi.DTO.Requests +{ + public class BlogPut + { + public string? Header { get; set; } + public string? Text { get; set; } + } +} diff --git a/exercise.wwwapi/DTO/Requests/UserPost.cs b/exercise.wwwapi/DTO/Requests/UserPost.cs new file mode 100644 index 0000000..3aa2cd4 --- /dev/null +++ b/exercise.wwwapi/DTO/Requests/UserPost.cs @@ -0,0 +1,11 @@ +using System.ComponentModel.DataAnnotations.Schema; + +namespace exercise.wwwapi.DTO.Requests +{ + public class AuthorPost + { + public string Name { get; set; } + public string Email { get; set; } + public string Password { get; set; } + } +} diff --git a/exercise.wwwapi/DTO/Requests/UserPut.cs b/exercise.wwwapi/DTO/Requests/UserPut.cs new file mode 100644 index 0000000..a94ae0a --- /dev/null +++ b/exercise.wwwapi/DTO/Requests/UserPut.cs @@ -0,0 +1,9 @@ +namespace exercise.wwwapi.DTO.Requests +{ + public class UserPut + { + public string? Name { get; set; } + public string? Email { get; set; } + public string? Password { get; set; } + } +} diff --git a/exercise.wwwapi/DTO/Requests/UserRequestDto.cs b/exercise.wwwapi/DTO/Requests/UserRequestDto.cs new file mode 100644 index 0000000..b19f241 --- /dev/null +++ b/exercise.wwwapi/DTO/Requests/UserRequestDto.cs @@ -0,0 +1,12 @@ +using System.ComponentModel.DataAnnotations.Schema; + +namespace exercise.wwwapi.DTO.Requests +{ + [NotMapped] + public class UserRequestDto + { + public required string Username { get; set; } + public required string Password { get; set; } + public required string Email { get; set; } + } +} diff --git a/exercise.wwwapi/DTO/Response/BlogDTO.cs b/exercise.wwwapi/DTO/Response/BlogDTO.cs new file mode 100644 index 0000000..0da4ed9 --- /dev/null +++ b/exercise.wwwapi/DTO/Response/BlogDTO.cs @@ -0,0 +1,9 @@ +namespace exercise.wwwapi.DTO.Requests +{ + public class BlogDTO + { + public int Id { get; set; } + public string Header { get; set; } + public string Text { get; set; } + } +} diff --git a/exercise.wwwapi/DTO/Response/BlogUserDTO.cs b/exercise.wwwapi/DTO/Response/BlogUserDTO.cs new file mode 100644 index 0000000..3239ec0 --- /dev/null +++ b/exercise.wwwapi/DTO/Response/BlogUserDTO.cs @@ -0,0 +1,9 @@ +namespace exercise.wwwapi.DTO.Requests +{ + public class BlogAuthorDTO + { + public int Id { get; set; } + public string Header { get; set; } + public string Text { get; set; } + } +} diff --git a/exercise.wwwapi/DTO/Response/Payload.cs b/exercise.wwwapi/DTO/Response/Payload.cs new file mode 100644 index 0000000..e246a0b --- /dev/null +++ b/exercise.wwwapi/DTO/Response/Payload.cs @@ -0,0 +1,11 @@ +using System.ComponentModel.DataAnnotations.Schema; + +namespace exercise.wwwapi.DTO.Response +{ + [NotMapped] + public class Payload where T : class + { + public string status { get; set; } = "success"; + public T data { get; set; } + } +} diff --git a/exercise.wwwapi/DTO/Response/UserDTO.cs b/exercise.wwwapi/DTO/Response/UserDTO.cs new file mode 100644 index 0000000..6287332 --- /dev/null +++ b/exercise.wwwapi/DTO/Response/UserDTO.cs @@ -0,0 +1,13 @@ +using exercise.wwwapi.Models; + +namespace exercise.wwwapi.DTO.Requests +{ + public class UserDTO + { + public int Id { get; set; } + public string Name { get; set; } + public string Email { get; set; } + public string PasswordHash { get; set; } + public List Blogs { get; set; } = new List(); + } +} diff --git a/exercise.wwwapi/DTO/Response/UserResponseDto.cs b/exercise.wwwapi/DTO/Response/UserResponseDto.cs new file mode 100644 index 0000000..89ea5ee --- /dev/null +++ b/exercise.wwwapi/DTO/Response/UserResponseDto.cs @@ -0,0 +1,12 @@ +using System.ComponentModel.DataAnnotations.Schema; + +namespace exercise.wwwapi.DTO.Response +{ + [NotMapped] + public class UserResponseDto + { + public string Username { get; set; } + public string PasswordHash { get; set; } + public string Email { get; set; } + } +} diff --git a/exercise.wwwapi/Data/DataContext.cs b/exercise.wwwapi/Data/DataContext.cs new file mode 100644 index 0000000..158797f --- /dev/null +++ b/exercise.wwwapi/Data/DataContext.cs @@ -0,0 +1,22 @@ +using System.Collections.Generic; +using System.Net.Sockets; +using exercise.wwwapi.Models; +using Microsoft.EntityFrameworkCore; + +namespace exercise.wwwapi.Data +{ + public class DataContext : DbContext + { + public DataContext(DbContextOptions options) : base(options) + { + + } + protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder) + { + //optionsBuilder.UseInMemoryDatabase(databaseName: "Database"); + } + + public DbSet Users { get; set; } + public DbSet Blogs { get; set; } + } +} diff --git a/exercise.wwwapi/Endpoints/AuthApi.cs b/exercise.wwwapi/Endpoints/AuthApi.cs new file mode 100644 index 0000000..e35e2a9 --- /dev/null +++ b/exercise.wwwapi/Endpoints/AuthApi.cs @@ -0,0 +1,93 @@ +using exercise.wwwapi.Configuration; +using exercise.wwwapi.DTO.Requests; +using exercise.wwwapi.DTO.Response; +using exercise.wwwapi.Models; +using exercise.wwwapi.Repository; +using Microsoft.AspNetCore.Authorization; +using Microsoft.AspNetCore.Mvc; +using Microsoft.IdentityModel.Tokens; +using System.IdentityModel.Tokens.Jwt; +using System.Security.Claims; +using System.Text; + + +namespace exercise.wwwapi.Endpoints +{ + public static class AuthApi + { + public static void ConfigureAuthApi(this WebApplication app) + { + app.MapPost("register", Register); + app.MapPost("login", Login); + app.MapGet("users", GetUsers); + + } + [Authorize] + [ProducesResponseType(StatusCodes.Status200OK)] + [ProducesResponseType(StatusCodes.Status401Unauthorized)] + private static async Task GetUsers(IRepository service, ClaimsPrincipal user) + { + return TypedResults.Ok(service.GetAll()); + } + [ProducesResponseType(StatusCodes.Status200OK)] + [ProducesResponseType(StatusCodes.Status409Conflict)] + private static async Task Register(UserRequestDto request, IRepository service) + { + + //user exists + if (service.GetAll().Where(u => u.Username == request.Username).Any()) return Results.Conflict(new Payload() { status = "Username already exists!", data = request }); + + string passwordHash = BCrypt.Net.BCrypt.HashPassword(request.Password); + + var user = new User(); + + user.Username = request.Username; + user.PasswordHash = passwordHash; + user.Email = request.Email; + + service.Insert(user); + service.Save(); + + return Results.Ok(new Payload() { data = "Created Account" }); + } + + [ProducesResponseType(StatusCodes.Status200OK)] + [ProducesResponseType(StatusCodes.Status400BadRequest)] + private static async Task Login(UserRequestDto request, IRepository service, IConfigurationSettings config) + { + //user doesn't exist + if (!service.GetAll().Where(u => u.Username == request.Username).Any()) return Results.BadRequest(new Payload() { status = "User does not exist", data = request }); + + User user = service.GetAll().FirstOrDefault(u => u.Username == request.Username)!; + + + if (!BCrypt.Net.BCrypt.Verify(request.Password, user.PasswordHash)) + { + return Results.BadRequest(new Payload() { status = "Wrong Password", data = request }); + } + string token = CreateToken(user, config); + return Results.Ok(new Payload() { data = token }) ; + + } + private static string CreateToken(User user, IConfigurationSettings config) + { + List claims = new List + { + new Claim(ClaimTypes.Sid, user.Id.ToString()), + new Claim(ClaimTypes.Name, user.Username), + new Claim(ClaimTypes.Email, user.Email), + + }; + + var key = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(config.GetValue("AppSettings:Token"))); + var credentials = new SigningCredentials(key, SecurityAlgorithms.HmacSha512Signature); + var token = new JwtSecurityToken( + claims: claims, + expires: DateTime.Now.AddDays(1), + signingCredentials: credentials + ); + var jwt = new JwtSecurityTokenHandler().WriteToken(token); + return jwt; + } + } +} diff --git a/exercise.wwwapi/Endpoints/SecureApi.cs b/exercise.wwwapi/Endpoints/SecureApi.cs new file mode 100644 index 0000000..19db16b --- /dev/null +++ b/exercise.wwwapi/Endpoints/SecureApi.cs @@ -0,0 +1,83 @@ +using AutoMapper; +using exercise.wwwapi.DTO.Requests; +using exercise.wwwapi.DTO.Response; +using exercise.wwwapi.Helpers; +using exercise.wwwapi.Models; +using exercise.wwwapi.Repository; +using Microsoft.AspNetCore.Authorization; +using Microsoft.AspNetCore.Mvc; +using System.Security.Claims; + +namespace exercise.wwwapi.Endpoints +{ + public static class SecureApi + { + public static void ConfigureSecureApi(this WebApplication app) + { + var blog = app.MapGroup("/blog"); + blog.MapGet("/", GetBlogs); + blog.MapPost("/", CreateBlog); + blog.MapPut("/{id}", UpdateBlog); + } + + [Authorize] + [ProducesResponseType(StatusCodes.Status200OK)] + [ProducesResponseType(StatusCodes.Status401Unauthorized)] + private static async Task GetBlogs(IRepository service, ClaimsPrincipal user) + { + var blogs = service.GetAll(b => b.User); + + var result = blogs.Select(b => new BlogDTO + { + Id = b.Id, + Header = b.Header, + Text = b.Text + }).ToList(); + return TypedResults.Ok(new Payload>{ data = result }); + } + + [Authorize] + [ProducesResponseType(StatusCodes.Status201Created)] + [ProducesResponseType(StatusCodes.Status401Unauthorized)] + private static async Task CreateBlog(IRepository service, [FromBody] BlogPost model, ClaimsPrincipal user) + { + Blog blog = new Blog() + { + Header = model.Header, + Text = model.Text, + UserId = user.UserRealId().Value + }; + service.Insert(blog); + service.Save(); + + var result = new BlogDTO + { + Header = blog.Header, + Text = blog.Text, + }; + return Results.Created($"/blogs/{blog.Id}", new Payload { data = result }); + } + + [Authorize] + [ProducesResponseType(StatusCodes.Status201Created)] + [ProducesResponseType(StatusCodes.Status401Unauthorized)] + private static async Task UpdateBlog(IRepository service, int id, [FromBody] BlogPut model, ClaimsPrincipal user) + { + Blog blog = service.GetById(id); + if (blog == null) return Results.NotFound("Screening not found"); + if (model.Header != null) blog.Header = model.Header; + if (model.Text != null) blog.Text = model.Text; + + service.Update(blog); + service.Save(); + + var result = new BlogDTO + { + Id = id, + Header = blog.Header, + Text = blog.Text, + }; + return Results.Created($"/blogs/{id}", new Payload { data = result }); + } + } +} diff --git a/exercise.wwwapi/Helpers/ClaimsPrincipalHelper.cs b/exercise.wwwapi/Helpers/ClaimsPrincipalHelper.cs new file mode 100644 index 0000000..a2ecf2e --- /dev/null +++ b/exercise.wwwapi/Helpers/ClaimsPrincipalHelper.cs @@ -0,0 +1,31 @@ +using System.Security.Claims; + +namespace exercise.wwwapi.Helpers +{ + public static class ClaimsPrincipalHelper + { + public static int? UserRealId(this ClaimsPrincipal user) + { + Claim? claim = user.FindFirst(ClaimTypes.Sid); + return int.Parse(claim?.Value); + } + public static string UserId(this ClaimsPrincipal user) + { + IEnumerable claims = user.Claims.Where(c => c.Type == ClaimTypes.NameIdentifier); + return claims.Count() >= 2 ? claims.ElementAt(1).Value : null; + + } + + public static string? Email(this ClaimsPrincipal user) + { + Claim? claim = user.FindFirst(ClaimTypes.Email); + return claim?.Value; + } + public static string? Role(this ClaimsPrincipal user) + { + Claim? claim = user.FindFirst(ClaimTypes.Role); + return claim?.Value; + } + + } +} diff --git a/exercise.wwwapi/Models/Blog.cs b/exercise.wwwapi/Models/Blog.cs new file mode 100644 index 0000000..973a64a --- /dev/null +++ b/exercise.wwwapi/Models/Blog.cs @@ -0,0 +1,24 @@ +using System.ComponentModel.DataAnnotations; +using System.ComponentModel.DataAnnotations.Schema; +using System.Reflection.Metadata; + +namespace exercise.wwwapi.Models +{ + [Table("blogs")] + public class Blog + { + [Key] + [Column("id")] + public int Id { get; set; } + [Column("header")] + public string Header { get; set; } + [Column("text")] + public string Text { get; set; } + + [ForeignKey("User")] + public int UserId { get; set; } + + public User User { get; set; } + + } +} diff --git a/exercise.wwwapi/Models/User.cs b/exercise.wwwapi/Models/User.cs new file mode 100644 index 0000000..3612515 --- /dev/null +++ b/exercise.wwwapi/Models/User.cs @@ -0,0 +1,22 @@ +using System.ComponentModel.DataAnnotations; +using System.ComponentModel.DataAnnotations.Schema; +using System.Reflection.Metadata; + +namespace exercise.wwwapi.Models +{ + [Table("users")] + public class User + { + [Key] + [Column("id")] + public int Id { get; set; } + [Column("username")] + public string Username { get; set; } + [Column("email")] + public string Email { get; set; } + [Column("passwordhash")] + public string PasswordHash { get; set; } + public List Blogs { get; set; } = new List(); + + } +} diff --git a/exercise.wwwapi/Program.cs b/exercise.wwwapi/Program.cs index 47f22ef..4d41516 100644 --- a/exercise.wwwapi/Program.cs +++ b/exercise.wwwapi/Program.cs @@ -1,6 +1,103 @@ +using exercise.wwwapi.Configuration; +using exercise.wwwapi.Data; +using exercise.wwwapi.Endpoints; +using exercise.wwwapi.Models; +using exercise.wwwapi.Repository; +using Microsoft.AspNetCore.Authentication.JwtBearer; +using Microsoft.EntityFrameworkCore; +using Microsoft.Extensions.Options; +using Microsoft.IdentityModel.Tokens; +using Microsoft.OpenApi.Models; +using Scalar.AspNetCore; +using System.Diagnostics; +using System.Text; + var builder = WebApplication.CreateBuilder(args); +builder.Logging.ClearProviders(); +builder.Logging.AddConsole(); +var config = new ConfigurationSettings(); // Add services to the container. +builder.Services.AddScoped(); +builder.Services.AddScoped, Repository>(); +builder.Services.AddScoped, Repository>(); +builder.Services.AddScoped>(); +builder.Services.AddDbContext(options => { + + options.UseNpgsql(builder.Configuration.GetConnectionString("DefaultConnectionString")); + options.LogTo(message => Debug.WriteLine(message)); + +}); +//authentication verifying who they say they are +//authorization verifying what they have access to +builder.Services.AddAuthentication(x => +{ + x.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme; + x.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme; + x.DefaultScheme = JwtBearerDefaults.AuthenticationScheme; + +}).AddJwtBearer(x => +{ + x.TokenValidationParameters = new TokenValidationParameters + { + + IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(config.GetValue("AppSettings:Token"))), + ValidateIssuer = false, + ValidateAudience = false, + ValidateLifetime = false, + ValidateIssuerSigningKey = false + + }; +}); +builder.Services.AddSwaggerGen(s => +{ + s.SwaggerDoc("v1", new OpenApiInfo + { + Version = "v1", + Title = "C# API Authentication", + Description = "Demo of an API using JWT as an authentication method", + Contact = new OpenApiContact + { + Name = "Nigel", + Email = "nigel@nigel.nigel", + Url = new Uri("https://www.boolean.co.uk") + }, + License = new OpenApiLicense + { + Name = "Boolean", + Url = new Uri("https://github.com/boolean-uk/csharp-api-auth") + } + + }); + + s.AddSecurityDefinition("Bearer", new OpenApiSecurityScheme + { + Description = "Add an Authorization header with a JWT token using the Bearer scheme see the app.http file for an example.)", + Name = "Authorization", + Type = SecuritySchemeType.ApiKey, + In = ParameterLocation.Header, + Scheme = "Bearer" + }); + + s.AddSecurityRequirement(new OpenApiSecurityRequirement + { + { + new OpenApiSecurityScheme + { + Reference = new OpenApiReference + { + Type = ReferenceType.SecurityScheme, + Id = "Bearer" + } + }, + Array.Empty() + } + }); + +}); +builder.Services.AddAuthorization(); + +builder.Services.AddControllers(); // Learn more about configuring Swagger/OpenAPI at https://aka.ms/aspnetcore/swashbuckle builder.Services.AddEndpointsApiExplorer(); builder.Services.AddSwaggerGen(); @@ -12,9 +109,29 @@ { app.UseSwagger(); app.UseSwaggerUI(); + app.UseSwaggerUI(options => + { + options.SwaggerEndpoint("/openapi/v1.json", "Demo API"); + }); + app.MapScalarApiReference(); } +app.UseCors(x => x + .AllowAnyMethod() + .AllowAnyHeader() + .SetIsOriginAllowed(origin => true) // allow any origin + .AllowCredentials()); // allow credentials + app.UseHttpsRedirection(); +app.UseAuthentication(); + +app.UseAuthorization(); + +app.MapControllers(); + +app.ConfigureAuthApi(); + +app.ConfigureSecureApi(); -app.Run(); \ No newline at end of file +app.Run(); diff --git a/exercise.wwwapi/Repository/IRepository.cs b/exercise.wwwapi/Repository/IRepository.cs new file mode 100644 index 0000000..0b2be5a --- /dev/null +++ b/exercise.wwwapi/Repository/IRepository.cs @@ -0,0 +1,17 @@ +using System.Linq.Expressions; +using Microsoft.EntityFrameworkCore; + +namespace exercise.wwwapi.Repository +{ + public interface IRepository where T : class + { + IEnumerable GetAll(); + IEnumerable GetAll(params Expression>[] includeExpressions); + T GetById(object id); + void Insert(T obj); + void Update(T obj); + void Delete(object id); + void Save(); + DbSet Table { get; } + } +} diff --git a/exercise.wwwapi/Repository/Repository.cs b/exercise.wwwapi/Repository/Repository.cs new file mode 100644 index 0000000..4d03dbb --- /dev/null +++ b/exercise.wwwapi/Repository/Repository.cs @@ -0,0 +1,65 @@ +using System.Collections.Generic; +using System.Linq.Expressions; +using exercise.wwwapi.Data; +using Microsoft.EntityFrameworkCore; + +namespace exercise.wwwapi.Repository +{ + public class Repository : IRepository where T : class + { + + + private DataContext _db; + private DbSet _table = null; + + public Repository(DataContext db) + { + _db = db; + _table = _db.Set(); + } + + public IEnumerable GetAll(params Expression>[] includeExpressions) + { + if (includeExpressions.Any()) + { + var set = includeExpressions + .Aggregate>, IQueryable> + (_table, (current, expression) => current.Include(expression)); + } + return _table.ToList(); + } + + public IEnumerable GetAll() + { + return _table.ToList(); + } + public T GetById(object id) + { + return _table.Find(id); + } + + public void Insert(T obj) + { + _table.Add(obj); + } + public void Update(T obj) + { + _table.Attach(obj); + _db.Entry(obj).State = EntityState.Modified; + } + + public void Delete(object id) + { + T existing = _table.Find(id); + _table.Remove(existing); + } + + + public void Save() + { + _db.SaveChanges(); + } + public DbSet Table { get { return _table; } } + + } +} diff --git a/exercise.wwwapi/appsettings.example.json b/exercise.wwwapi/appsettings.example.json deleted file mode 100644 index 7a9d42d..0000000 --- a/exercise.wwwapi/appsettings.example.json +++ /dev/null @@ -1,15 +0,0 @@ -{ - "Logging": { - "LogLevel": { - "Default": "Information", - "Microsoft.AspNetCore": "Warning" - } - }, - "AllowedHosts": "*", - "JwtTokenSettings": { - "ValidIssuer": "YourCompanyServer", - "ValidAudience": "YourProductAudience", - "SymmetricSecurityKey": "SOME_RANDOM_SECRET", - "JwtRegisteredClaimNamesSub": "SOME_RANDOM_CODE" - } -} diff --git a/exercise.wwwapi/exercise.wwwapi.csproj b/exercise.wwwapi/exercise.wwwapi.csproj index 56929a8..e94197b 100644 --- a/exercise.wwwapi/exercise.wwwapi.csproj +++ b/exercise.wwwapi/exercise.wwwapi.csproj @@ -1,4 +1,4 @@ - + net9.0 @@ -8,7 +8,22 @@ - + + + + + + + all + runtime; build; native; contentfiles; analyzers; buildtransitive + + + + all + runtime; build; native; contentfiles; analyzers; buildtransitive + + +