Explorar el Código

JWT auth between frontend and backend

feature/1162_JWT_auth_between_be_and_f-b
Dzenis Hadzifejzovic hace 3 años
padre
commit
b1bfb2a435

+ 2
- 2
Diligent.WebAPI.Business/Services/Interfaces/IUserService.cs Ver fichero

@@ -3,7 +3,7 @@
public interface IUserService
{
AuthenticateResponseDto? Authenticate(AuthenticateRequestDto model);
IEnumerable<User?> GetAll();
User? GetById(int id);
Task<IEnumerable<User?>> GetAll();
Task<User?> GetById(int id);
}
}

+ 9
- 13
Diligent.WebAPI.Business/Services/UserService.cs Ver fichero

@@ -4,24 +4,20 @@
public class UserService : IUserService
{
private readonly AuthorizationSettings _authSettings;
private readonly DatabaseContext _context;

public UserService(IOptions<AuthorizationSettings> authSettings)
public UserService(IOptions<AuthorizationSettings> authSettings, DatabaseContext context)
{
_authSettings = authSettings.Value;
_context = context;
}

// User list for testing
private readonly List<User> _users = new List<User>
{
new User { Id = 1, FirstName = "Test", LastName = "User", Username = "test", Password = "test" }
};

public AuthenticateResponseDto? Authenticate(AuthenticateRequestDto model)
{
var user = _users.SingleOrDefault(x => x.Username == model.Username && x.Password == model.Password);
var user = _context.User.SingleOrDefault(x => x.Username == model.Username && x.Password == model.Password);

// return null if user not found
if (user == null)
if (user == null)
return null;

// authentication successful so generate jwt token
@@ -37,14 +33,14 @@
};
}

public IEnumerable<User> GetAll()
public async Task<IEnumerable<User?>> GetAll()
{
return _users;
return await _context.User.ToListAsync();
}

public User? GetById(int id)
public async Task<User?> GetById(int id)
{
return _users.FirstOrDefault(x => x.Id == id);
return await _context.User.FirstOrDefaultAsync(x => x.Id == id);
}

private string GenerateJwtToken(User user)

+ 1
- 0
Diligent.WebAPI.Data/DatabaseContext.cs Ver fichero

@@ -7,6 +7,7 @@ public class DatabaseContext : DbContext
public DbSet<InsurancePolicy> InsurancePolicies { get; set; }
public DbSet<WebhookSubscription> WebhookSubscriptions { get; set; }
public DbSet<WebhookDefinition> WebhookDefinitions { get; set; }
public DbSet<User> User { get; set; }

public DatabaseContext(DbContextOptions<DatabaseContext> options) : base(options) { }


+ 326
- 0
Diligent.WebAPI.Data/Migrations/20221024095648_UserAdded.Designer.cs Ver fichero

@@ -0,0 +1,326 @@
// <auto-generated />
using System;
using Diligent.WebAPI.Data;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Infrastructure;
using Microsoft.EntityFrameworkCore.Metadata;
using Microsoft.EntityFrameworkCore.Migrations;
using Microsoft.EntityFrameworkCore.Storage.ValueConversion;

#nullable disable

namespace Diligent.WebAPI.Data.Migrations
{
[DbContext(typeof(DatabaseContext))]
[Migration("20221024095648_UserAdded")]
partial class UserAdded
{
protected override void BuildTargetModel(ModelBuilder modelBuilder)
{
#pragma warning disable 612, 618
modelBuilder
.HasAnnotation("ProductVersion", "6.0.3")
.HasAnnotation("Relational:MaxIdentifierLength", 128);

SqlServerModelBuilderExtensions.UseIdentityColumns(modelBuilder, 1L, 1);

modelBuilder.Entity("Diligent.WebAPI.Data.Entities.InsuranceCompany", b =>
{
b.Property<long>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("bigint");

SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property<long>("Id"), 1L, 1);

b.Property<string>("City")
.IsRequired()
.HasColumnType("nvarchar(max)");

b.Property<string>("Country")
.IsRequired()
.HasColumnType("nvarchar(max)");

b.Property<DateTime>("CreatedAtUtc")
.HasColumnType("datetime2");

b.Property<DateTime?>("DeletedAtUtc")
.HasColumnType("datetime2");

b.Property<string>("Fax")
.IsRequired()
.HasColumnType("nvarchar(max)");

b.Property<string>("LegalAddress")
.IsRequired()
.HasColumnType("nvarchar(max)");

b.Property<string>("LegalEmail")
.IsRequired()
.HasColumnType("nvarchar(max)");

b.Property<string>("Name")
.IsRequired()
.HasColumnType("nvarchar(max)");

b.Property<string>("PhoneNumber")
.IsRequired()
.HasColumnType("nvarchar(max)");

b.Property<string>("PostalCode")
.IsRequired()
.HasColumnType("nvarchar(max)");

b.Property<DateTime?>("UpdatedAtUtc")
.HasColumnType("datetime2");

b.HasKey("Id");

b.ToTable("InsuranceCompanies");
});

modelBuilder.Entity("Diligent.WebAPI.Data.Entities.InsurancePolicy", b =>
{
b.Property<long>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("bigint");

SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property<long>("Id"), 1L, 1);

b.Property<DateTime>("CreatedAtUtc")
.HasColumnType("datetime2");

b.Property<DateTime?>("DeletedAtUtc")
.HasColumnType("datetime2");

b.Property<DateTime>("EndDate")
.HasColumnType("datetime2");

b.Property<long>("InsurerId")
.HasColumnType("bigint");

b.Property<decimal>("Premium")
.HasColumnType("decimal(18,2)");

b.Property<DateTime>("StartDate")
.HasColumnType("datetime2");

b.Property<string>("Type")
.IsRequired()
.HasColumnType("nvarchar(max)");

b.Property<DateTime?>("UpdatedAtUtc")
.HasColumnType("datetime2");

b.HasKey("Id");

b.HasIndex("InsurerId");

b.ToTable("InsurancePolicies");
});

modelBuilder.Entity("Diligent.WebAPI.Data.Entities.Insurer", b =>
{
b.Property<long>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("bigint");

SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property<long>("Id"), 1L, 1);

b.Property<string>("Address")
.IsRequired()
.HasColumnType("nvarchar(max)");

b.Property<string>("City")
.IsRequired()
.HasColumnType("nvarchar(max)");

b.Property<string>("Country")
.IsRequired()
.HasColumnType("nvarchar(max)");

b.Property<DateTime>("CreatedAtUtc")
.HasColumnType("datetime2");

b.Property<DateTime>("DateOfBirth")
.HasColumnType("datetime2");

b.Property<DateTime?>("DeletedAtUtc")
.HasColumnType("datetime2");

b.Property<string>("Email")
.IsRequired()
.HasColumnType("nvarchar(max)");

b.Property<string>("FirstName")
.IsRequired()
.HasColumnType("nvarchar(max)");

b.Property<long>("InsuranceCompanyId")
.HasColumnType("bigint");

b.Property<string>("LastName")
.IsRequired()
.HasColumnType("nvarchar(max)");

b.Property<string>("PhoneNumber")
.IsRequired()
.HasColumnType("nvarchar(max)");

b.Property<string>("PostalCode")
.IsRequired()
.HasColumnType("nvarchar(max)");

b.Property<DateTime?>("UpdatedAtUtc")
.HasColumnType("datetime2");

b.HasKey("Id");

b.HasIndex("InsuranceCompanyId");

b.ToTable("Insurers");
});

modelBuilder.Entity("Diligent.WebAPI.Data.Entities.User", b =>
{
b.Property<long>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("bigint");

SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property<long>("Id"), 1L, 1);

b.Property<DateTime>("CreatedAtUtc")
.HasColumnType("datetime2");

b.Property<DateTime?>("DeletedAtUtc")
.HasColumnType("datetime2");

b.Property<string>("FirstName")
.IsRequired()
.HasColumnType("nvarchar(max)");

b.Property<string>("LastName")
.IsRequired()
.HasColumnType("nvarchar(max)");

b.Property<string>("Password")
.IsRequired()
.HasColumnType("nvarchar(max)");

b.Property<DateTime?>("UpdatedAtUtc")
.HasColumnType("datetime2");

b.Property<string>("Username")
.IsRequired()
.HasColumnType("nvarchar(max)");

b.HasKey("Id");

b.ToTable("User");
});

modelBuilder.Entity("Diligent.WebAPI.Data.Entities.WebhookDefinition", b =>
{
b.Property<long>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("bigint");

SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property<long>("Id"), 1L, 1);

b.Property<DateTime>("CreatedAtUtc")
.HasColumnType("datetime2");

b.Property<DateTime?>("DeletedAtUtc")
.HasColumnType("datetime2");

b.Property<string>("Description")
.IsRequired()
.HasColumnType("nvarchar(max)");

b.Property<string>("DisplayName")
.IsRequired()
.HasMaxLength(100)
.HasColumnType("nvarchar(100)");

b.Property<string>("Name")
.IsRequired()
.HasMaxLength(100)
.HasColumnType("nvarchar(100)");

b.Property<DateTime?>("UpdatedAtUtc")
.HasColumnType("datetime2");

b.HasKey("Id");

b.ToTable("WebhookDefinitions");
});

modelBuilder.Entity("Diligent.WebAPI.Data.Entities.WebhookSubscription", b =>
{
b.Property<long>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("bigint");

SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property<long>("Id"), 1L, 1);

b.Property<DateTime>("CreatedAtUtc")
.HasColumnType("datetime2");

b.Property<DateTime?>("DeletedAtUtc")
.HasColumnType("datetime2");

b.Property<bool>("IsActive")
.HasColumnType("bit");

b.Property<DateTime?>("UpdatedAtUtc")
.HasColumnType("datetime2");

b.Property<long>("WebhookDefinitionId")
.HasColumnType("bigint");

b.Property<string>("WebhookURL")
.IsRequired()
.HasColumnType("nvarchar(max)");

b.HasKey("Id");

b.HasIndex("WebhookDefinitionId");

b.ToTable("WebhookSubscriptions");
});

modelBuilder.Entity("Diligent.WebAPI.Data.Entities.InsurancePolicy", b =>
{
b.HasOne("Diligent.WebAPI.Data.Entities.Insurer", "Insurer")
.WithMany()
.HasForeignKey("InsurerId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();

b.Navigation("Insurer");
});

modelBuilder.Entity("Diligent.WebAPI.Data.Entities.Insurer", b =>
{
b.HasOne("Diligent.WebAPI.Data.Entities.InsuranceCompany", "InsuranceCompany")
.WithMany()
.HasForeignKey("InsuranceCompanyId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();

b.Navigation("InsuranceCompany");
});

modelBuilder.Entity("Diligent.WebAPI.Data.Entities.WebhookSubscription", b =>
{
b.HasOne("Diligent.WebAPI.Data.Entities.WebhookDefinition", "WebhookDefinition")
.WithMany()
.HasForeignKey("WebhookDefinitionId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();

b.Navigation("WebhookDefinition");
});
#pragma warning restore 612, 618
}
}
}

+ 38
- 0
Diligent.WebAPI.Data/Migrations/20221024095648_UserAdded.cs Ver fichero

@@ -0,0 +1,38 @@
using System;
using Microsoft.EntityFrameworkCore.Migrations;

#nullable disable

namespace Diligent.WebAPI.Data.Migrations
{
public partial class UserAdded : Migration
{
protected override void Up(MigrationBuilder migrationBuilder)
{
migrationBuilder.CreateTable(
name: "User",
columns: table => new
{
Id = table.Column<long>(type: "bigint", nullable: false)
.Annotation("SqlServer:Identity", "1, 1"),
FirstName = table.Column<string>(type: "nvarchar(max)", nullable: false),
LastName = table.Column<string>(type: "nvarchar(max)", nullable: false),
Username = table.Column<string>(type: "nvarchar(max)", nullable: false),
Password = table.Column<string>(type: "nvarchar(max)", nullable: false),
CreatedAtUtc = table.Column<DateTime>(type: "datetime2", nullable: false),
UpdatedAtUtc = table.Column<DateTime>(type: "datetime2", nullable: true),
DeletedAtUtc = table.Column<DateTime>(type: "datetime2", nullable: true)
},
constraints: table =>
{
table.PrimaryKey("PK_User", x => x.Id);
});
}

protected override void Down(MigrationBuilder migrationBuilder)
{
migrationBuilder.DropTable(
name: "User");
}
}
}

+ 38
- 0
Diligent.WebAPI.Data/Migrations/DatabaseContextModelSnapshot.cs Ver fichero

@@ -178,6 +178,44 @@ namespace Diligent.WebAPI.Data.Migrations
b.ToTable("Insurers");
});

modelBuilder.Entity("Diligent.WebAPI.Data.Entities.User", b =>
{
b.Property<long>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("bigint");

SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property<long>("Id"), 1L, 1);

b.Property<DateTime>("CreatedAtUtc")
.HasColumnType("datetime2");

b.Property<DateTime?>("DeletedAtUtc")
.HasColumnType("datetime2");

b.Property<string>("FirstName")
.IsRequired()
.HasColumnType("nvarchar(max)");

b.Property<string>("LastName")
.IsRequired()
.HasColumnType("nvarchar(max)");

b.Property<string>("Password")
.IsRequired()
.HasColumnType("nvarchar(max)");

b.Property<DateTime?>("UpdatedAtUtc")
.HasColumnType("datetime2");

b.Property<string>("Username")
.IsRequired()
.HasColumnType("nvarchar(max)");

b.HasKey("Id");

b.ToTable("User");
});

modelBuilder.Entity("Diligent.WebAPI.Data.Entities.WebhookDefinition", b =>
{
b.Property<long>("Id")

+ 18
- 0
Diligent.WebAPI.Host/Extensions/CorsConfigurationExtension.cs Ver fichero

@@ -0,0 +1,18 @@
namespace Diligent.WebAPI.Host.Extensions
{
public static class CorsConfigurationExtension
{
public static void ConfigureCors(this WebApplicationBuilder builder)
{
var services = builder.Services;
services.AddCors(options =>
{
options.AddPolicy("CorsPolicy", builder =>
builder.WithOrigins("http://localhost:3000")
.AllowAnyMethod()
.AllowAnyHeader()
.AllowCredentials());
});
}
}
}

+ 2
- 0
Diligent.WebAPI.Host/Extensions/HostConfigurationExtension.cs Ver fichero

@@ -7,6 +7,7 @@
/// </summary>
public static void ConfigureHost(this WebApplicationBuilder builder)
{
builder.ConfigureCors();
builder.ConfigureAuth();
builder.ConfigureValidationMiddleware();
builder.ConfigureSwagger();
@@ -21,6 +22,7 @@
/// </summary>
public static void ConfigureHost(this WebApplication app)
{
app.UseCors("CorsPolicy");
app.UseCorrelationId();
app.MapControllers();


+ 1
- 1
Diligent.WebAPI.Host/appsettings.Development.json Ver fichero

@@ -1,6 +1,6 @@
{
"ConnectionStrings": {
"WebApi": "Data Source=localhost,2433;User=sa;Password=developer_pw;Initial Catalog=WebApiDB;MultipleActiveResultSets=True"
"WebApi": "server=localhost;database=HR;trusted_connection=True;"
},
"Authorization": {
"Secret": "SECRET_ASKGFH#$_#((Y)#I%EWJGDSJTGKEOS@$SAF"

Cargando…
Cancelar
Guardar