-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
commit 0994dd3 Author: DustSwiffer <[email protected]> Date: Sat Jul 20 00:38:36 2024 +0200 implementation of microsoft identity
- Loading branch information
1 parent
995e1c3
commit 8f9030c
Showing
24 changed files
with
1,535 additions
and
44 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,53 @@ | ||
using System.IdentityModel.Tokens.Jwt; | ||
using System.Security.Claims; | ||
using System.Text; | ||
using AdvancedAPI.Data.Repositories.Interfaces; | ||
using AdvancedAPI.Data.ViewModels.Authentication; | ||
using Business.Services.Interfaces; | ||
using Microsoft.AspNetCore.Identity; | ||
using Microsoft.IdentityModel.Tokens; | ||
|
||
namespace Business.Services; | ||
|
||
/// <inheritdoc /> | ||
public class AuthenticationService : IAuthenticationService | ||
{ | ||
private readonly IIdentityRepository _identityRepository; | ||
private readonly IConfiguration _configuration; | ||
|
||
/// <summary> | ||
/// Constructor. | ||
/// </summary> | ||
public AuthenticationService(IIdentityRepository identityRepository, IConfiguration configuration) | ||
{ | ||
_identityRepository = identityRepository; | ||
_configuration = configuration; | ||
} | ||
|
||
/// <inheritdoc /> | ||
public async Task<JwtSecurityToken?> Login(LoginRequestModel requestModel, CancellationToken ct = default) | ||
{ | ||
IdentityUser? user = await _identityRepository.GetUser(requestModel.Username); | ||
if (user != null && await _identityRepository.CheckPassword(user, requestModel.Password)) | ||
{ | ||
Claim[] authClaims = new[] | ||
{ | ||
new Claim(JwtRegisteredClaimNames.Sub, user.UserName), | ||
new Claim(JwtRegisteredClaimNames.Jti, Guid.NewGuid().ToString()), | ||
}; | ||
|
||
SymmetricSecurityKey authSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(_configuration["Jwt:Key"])); | ||
|
||
JwtSecurityToken token = new JwtSecurityToken( | ||
issuer: _configuration["Jwt:Issuer"], | ||
audience: _configuration["Jwt:Audience"], | ||
expires: DateTime.Now.AddHours(3), | ||
claims: authClaims, | ||
signingCredentials: new SigningCredentials(authSigningKey, SecurityAlgorithms.HmacSha256)); | ||
|
||
return token; | ||
} | ||
|
||
return null; | ||
} | ||
} |
15 changes: 15 additions & 0 deletions
15
AdvancedAPI.Business/Services/Interfaces/IAuthenticationService.cs
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,15 @@ | ||
using System.IdentityModel.Tokens.Jwt; | ||
using AdvancedAPI.Data.ViewModels.Authentication; | ||
|
||
namespace Business.Services.Interfaces; | ||
|
||
/// <summary> | ||
/// Authentication service. | ||
/// </summary> | ||
public interface IAuthenticationService | ||
{ | ||
/// <summary> | ||
/// Logs in the user and returns a token. | ||
/// </summary> | ||
public Task<JwtSecurityToken?> Login(LoginRequestModel requestModel, CancellationToken ct = default); | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,27 @@ | ||
using Microsoft.EntityFrameworkCore; | ||
using Microsoft.EntityFrameworkCore.Design; | ||
|
||
namespace AdvancedAPI.Data | ||
{ | ||
/// <summary> | ||
/// Factory for creating <see cref="AdvancedApiContext"/> instances at design time for EF Core tooling. | ||
/// </summary> | ||
public class AdvancedApiContextFactory : IDesignTimeDbContextFactory<AdvancedApiContext> | ||
{ | ||
/// <summary> | ||
/// Creates a new <see cref="AdvancedApiContext"/> with design-time configuration. | ||
/// </summary> | ||
public AdvancedApiContext CreateDbContext(string[] args) | ||
{ | ||
IConfigurationRoot? configuration = new ConfigurationBuilder() | ||
.SetBasePath(Directory.GetCurrentDirectory()) | ||
.AddJsonFile("appsettings.json") | ||
.Build(); | ||
|
||
DbContextOptionsBuilder<AdvancedApiContext> optionsBuilder = new DbContextOptionsBuilder<AdvancedApiContext>(); | ||
optionsBuilder.UseSqlServer(configuration.GetConnectionString("DefaultConnection")); | ||
|
||
return new AdvancedApiContext(optionsBuilder.Options); | ||
} | ||
} | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,65 @@ | ||
using Microsoft.AspNetCore.Identity; | ||
|
||
namespace AdvancedAPI.Data | ||
{ | ||
/// <summary> | ||
/// Database initializer. | ||
/// </summary> | ||
public class DbInitializer | ||
{ | ||
/// <summary> | ||
/// Initialization of the database. | ||
/// </summary> | ||
public static async Task Initialize(IServiceProvider serviceProvider) | ||
{ | ||
UserManager<IdentityUser> userManager = serviceProvider.GetRequiredService<UserManager<IdentityUser>>(); | ||
RoleManager<IdentityRole> roleManager = serviceProvider.GetRequiredService<RoleManager<IdentityRole>>(); | ||
|
||
// Seed roles | ||
await SeedRoles(roleManager); | ||
|
||
// Seed admin user | ||
await SeedAdminUser(userManager); | ||
} | ||
|
||
/// <summary> | ||
/// Seeding roles into the database. | ||
/// </summary> | ||
private static async Task SeedRoles(RoleManager<IdentityRole> roleManager) | ||
{ | ||
string[] roleNames = { "Admin", "User" }; | ||
|
||
foreach (string roleName in roleNames) | ||
{ | ||
bool roleExist = await roleManager.RoleExistsAsync(roleName); | ||
if (!roleExist) | ||
{ | ||
// Create the roles and seed them to the database | ||
await roleManager.CreateAsync(new IdentityRole(roleName)); | ||
} | ||
} | ||
} | ||
|
||
/// <summary> | ||
/// Seeding user into the database. | ||
/// </summary> | ||
private static async Task SeedAdminUser(UserManager<IdentityUser> userManager) | ||
{ | ||
IdentityUser? adminUser = await userManager.FindByEmailAsync("[email protected]"); | ||
if (adminUser == null) | ||
{ | ||
adminUser = new IdentityUser | ||
{ | ||
UserName = "[email protected]", | ||
Email = "[email protected]", | ||
}; | ||
|
||
IdentityResult? result = await userManager.CreateAsync(adminUser, "P@ssw0rd"); | ||
if (result.Succeeded) | ||
{ | ||
await userManager.AddToRoleAsync(adminUser, "Admin"); | ||
} | ||
} | ||
} | ||
} | ||
} |
Oops, something went wrong.