Auth optimization

This commit is contained in:
Andre Beging
2022-04-04 15:19:58 +02:00
parent 83fb4a3c5e
commit 1513ed9169
8 changed files with 100 additions and 44 deletions

View File

@@ -6,4 +6,8 @@
<Nullable>enable</Nullable> <Nullable>enable</Nullable>
</PropertyGroup> </PropertyGroup>
<ItemGroup>
<ProjectReference Include="..\FoodsharingSiegen.Shared\FoodsharingSiegen.Shared.csproj" />
</ItemGroup>
</Project> </Project>

View File

@@ -5,6 +5,7 @@ using FoodsharingSiegen.Contracts.Entity;
using FoodsharingSiegen.Server.Data; using FoodsharingSiegen.Server.Data;
using FoodsharingSiegen.Server.Data.Service; using FoodsharingSiegen.Server.Data.Service;
using FoodsharingSiegen.Server.Service; using FoodsharingSiegen.Server.Service;
using FoodsharingSiegen.Shared.Helper;
using Microsoft.AspNetCore.Components.Authorization; using Microsoft.AspNetCore.Components.Authorization;
using Microsoft.EntityFrameworkCore; using Microsoft.EntityFrameworkCore;
using Microsoft.IdentityModel.Tokens; using Microsoft.IdentityModel.Tokens;
@@ -92,25 +93,7 @@ namespace FoodsharingSiegen.Server.Auth
if (User != null) if (User != null)
{ {
var serializedToken = AuthHelper.CreateToken(User.Id);
// Daten korrekt
var tokenHandler = new JwtSecurityTokenHandler();
var tokenDescriptor = new SecurityTokenDescriptor
{
Subject = new ClaimsIdentity(new[]
{
new Claim(ClaimTypes.NameIdentifier, User.Id.ToString()),
}),
Expires = DateTime.UtcNow.AddDays(30),
Issuer = "FS-Siegen",
Audience = "FS-Siegen",
SigningCredentials = new SigningCredentials(AuthHelper.GetSigningKey(), SecurityAlgorithms.HmacSha256Signature)
};
var token = tokenHandler.CreateToken(tokenDescriptor);
var serializedToken = tokenHandler.WriteToken(token);
await _localStorageService.SetItem(StorageKeys.TokenKey, serializedToken); await _localStorageService.SetItem(StorageKeys.TokenKey, serializedToken);
return new OperationResult(); return new OperationResult();

View File

@@ -1,6 +1,7 @@
using System.Security.Claims; using System.Security.Claims;
using FoodsharingSiegen.Contracts; using FoodsharingSiegen.Contracts;
using FoodsharingSiegen.Server.Auth; using FoodsharingSiegen.Server.Auth;
using FoodsharingSiegen.Shared.Helper;
using Microsoft.AspNetCore.Components.Authorization; using Microsoft.AspNetCore.Components.Authorization;
namespace FoodsharingSiegen.Server.Service namespace FoodsharingSiegen.Server.Service

View File

@@ -35,7 +35,8 @@ namespace FoodsharingSiegen.Server.Data.Service
if (targetProspect == null) return new OperationResult<Interaction>(new Exception("Invalid prospect id")); if (targetProspect == null) return new OperationResult<Interaction>(new Exception("Invalid prospect id"));
interaction.ProspectId = Guid.Empty; interaction.ProspectId = Guid.Empty;
interaction.Created = DateTime.UtcNow;
targetProspect.Interactions.Add(interaction); targetProspect.Interactions.Add(interaction);
await Context.SaveChangesAsync(); await Context.SaveChangesAsync();
@@ -111,7 +112,7 @@ namespace FoodsharingSiegen.Server.Data.Service
{ {
try try
{ {
var prospects = await Context.Prospects.AsNoTracking().Include(x => x.Interactions).ThenInclude(x => x.User).OrderBy(x => x.Name).ToListAsync(); var prospects = await Context.Prospects.AsNoTracking().Include(x => x.Interactions.OrderBy(i => i.Date)).ThenInclude(x => x.User).OrderBy(x => x.Name).ToListAsync();
return new OperationResult<List<Prospect>>(prospects); return new OperationResult<List<Prospect>>(prospects);
} }
catch (Exception e) catch (Exception e)

View File

@@ -1,20 +1,28 @@
@using FoodsharingSiegen.Contracts.Entity @using FoodsharingSiegen.Contracts.Entity
<Modal @ref="ModalReference"> <Modal @ref="ModalReference">
<ModalContent Centered Size="ModalSize.Small"> <ModalContent Centered Size="ModalSize.Default">
<ModalHeader> <ModalHeader>
<h6>@_header</h6> <h6>@_header</h6>
<CloseButton/> <CloseButton/>
</ModalHeader> </ModalHeader>
<ModalBody> <ModalBody>
<Field> <div class="row">
<Select TValue="Guid" @bind-SelectedValue="SelectedUser"> <div class="col">
@foreach (var user in Users ?? new List<User>()) <label for="aim-userselect">Benutzer</label>
{ <Select TValue="Guid" @bind-SelectedValue="SelectedUser" id="aim-userselect">
<SelectItem Value="@user.Id">@user.Name</SelectItem> @foreach (var user in Users ?? new List<User>())
} {
</Select> <SelectItem Value="@user.Id">@user.Name</SelectItem>
</Field> }
</Select>
</div>
<div class="col">
<label for="aim-datepicker">Datum</label>
<DatePicker TValue="DateTime" @bind-Date="Interaction.Date" ElementId="aim-datepicker" Max="DateTime.UtcNow.AddDays(7)"/>
</div>
</div>
@if (_showInfo) @if (_showInfo)
{ {
<Field> <Field>

View File

@@ -0,0 +1,13 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFramework>net6.0</TargetFramework>
<ImplicitUsings>enable</ImplicitUsings>
<Nullable>enable</Nullable>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="System.IdentityModel.Tokens.Jwt" Version="6.16.0" />
</ItemGroup>
</Project>

View File

@@ -1,15 +1,45 @@
using System.IdentityModel.Tokens.Jwt; using System.IdentityModel.Tokens.Jwt;
using System.Security.Claims;
using System.Security.Cryptography; using System.Security.Cryptography;
using System.Text; using System.Text;
using Microsoft.IdentityModel.Tokens; using Microsoft.IdentityModel.Tokens;
namespace FoodsharingSiegen.Server.Auth namespace FoodsharingSiegen.Shared.Helper
{ {
/// <summary> /// <summary>
/// The auth helper class (a. beging, 04.04.2022) /// The auth helper class (a. beging, 04.04.2022)
/// </summary> /// </summary>
public static class AuthHelper public static class AuthHelper
{ {
#region Public Method CreateToken
/// <summary>
/// Creates the token using the specified user id (a. beging, 04.04.2022)
/// </summary>
/// <param name="userId">The user id</param>
/// <returns>The string</returns>
public static string CreateToken(Guid userId)
{
var tokenHandler = new JwtSecurityTokenHandler();
var tokenDescriptor = new SecurityTokenDescriptor
{
Subject = new ClaimsIdentity(new[]
{
new Claim(ClaimTypes.NameIdentifier, userId.ToString()),
new Claim("CanDoShit","yes")
}),
Expires = DateTime.UtcNow.AddDays(30),
Issuer = Issuer,
Audience = Audience,
SigningCredentials = new SigningCredentials(GetSigningKey(), SecurityAlgorithms.HmacSha256Signature)
};
var token = tokenHandler.CreateToken(tokenDescriptor);
return tokenHandler.WriteToken(token);
}
#endregion
#region Public Method Decrypt #region Public Method Decrypt
/// <summary> /// <summary>
@@ -61,16 +91,6 @@ namespace FoodsharingSiegen.Server.Auth
#endregion #endregion
#region Public Method GetSigningKey
/// <summary>
/// Gets the signing key (a. beging, 04.04.2022)
/// </summary>
/// <returns>The security key</returns>
public static SecurityKey GetSigningKey() => new SymmetricSecurityKey(Encoding.ASCII.GetBytes(SigningKey));
#endregion
#region Public Method ValidateToken #region Public Method ValidateToken
/// <summary> /// <summary>
@@ -89,10 +109,10 @@ namespace FoodsharingSiegen.Server.Auth
IssuerSigningKey = GetSigningKey(), IssuerSigningKey = GetSigningKey(),
ValidateAudience = true, ValidateAudience = true,
ValidAudience = "FS-Siegen", ValidAudience = Audience,
ValidateIssuer = true, ValidateIssuer = true,
ValidIssuer = "FS-Siegen" ValidIssuer = Issuer
}); });
return result.IsValid; return result.IsValid;
@@ -125,9 +145,29 @@ namespace FoodsharingSiegen.Server.Auth
#endregion #endregion
#region Private Method GetSigningKey
/// <summary>
/// Gets the signing key (a. beging, 04.04.2022)
/// </summary>
/// <returns>The security key</returns>
private static SecurityKey GetSigningKey() => new SymmetricSecurityKey(Encoding.ASCII.GetBytes(SigningKey));
#endregion
/// <summary> /// <summary>
/// The signing key /// The signing key
/// </summary> /// </summary>
public const string SigningKey = "2uasw2§$%1nd47n9s43&%Zs3529s23&/%AW"; private const string SigningKey = "2uasw2§$%1nd47n9s43&%Zs3529s23&/%AW";
/// <summary>
/// The audience
/// </summary>
private const string Audience = "FS-Siegen";
/// <summary>
/// The issuer
/// </summary>
private const string Issuer = "FS-Siegen";
} }
} }

View File

@@ -4,6 +4,8 @@ Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "FoodsharingSiegen.Server",
EndProject EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "FoodsharingSiegen.Contracts", "FoodsharingSiegen.Contracts\FoodsharingSiegen.Contracts.csproj", "{F39AE3B4-E4CE-421E-AFB0-E9C9B3B670FE}" Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "FoodsharingSiegen.Contracts", "FoodsharingSiegen.Contracts\FoodsharingSiegen.Contracts.csproj", "{F39AE3B4-E4CE-421E-AFB0-E9C9B3B670FE}"
EndProject EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "FoodsharingSiegen.Shared", "FoodsharingSiegen.Shared\FoodsharingSiegen.Shared.csproj", "{625167D9-A375-40AF-82DE-87484519F6D9}"
EndProject
Global Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution GlobalSection(SolutionConfigurationPlatforms) = preSolution
Debug|Any CPU = Debug|Any CPU Debug|Any CPU = Debug|Any CPU
@@ -18,5 +20,9 @@ Global
{F39AE3B4-E4CE-421E-AFB0-E9C9B3B670FE}.Debug|Any CPU.Build.0 = Debug|Any CPU {F39AE3B4-E4CE-421E-AFB0-E9C9B3B670FE}.Debug|Any CPU.Build.0 = Debug|Any CPU
{F39AE3B4-E4CE-421E-AFB0-E9C9B3B670FE}.Release|Any CPU.ActiveCfg = Release|Any CPU {F39AE3B4-E4CE-421E-AFB0-E9C9B3B670FE}.Release|Any CPU.ActiveCfg = Release|Any CPU
{F39AE3B4-E4CE-421E-AFB0-E9C9B3B670FE}.Release|Any CPU.Build.0 = Release|Any CPU {F39AE3B4-E4CE-421E-AFB0-E9C9B3B670FE}.Release|Any CPU.Build.0 = Release|Any CPU
{625167D9-A375-40AF-82DE-87484519F6D9}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{625167D9-A375-40AF-82DE-87484519F6D9}.Debug|Any CPU.Build.0 = Debug|Any CPU
{625167D9-A375-40AF-82DE-87484519F6D9}.Release|Any CPU.ActiveCfg = Release|Any CPU
{625167D9-A375-40AF-82DE-87484519F6D9}.Release|Any CPU.Build.0 = Release|Any CPU
EndGlobalSection EndGlobalSection
EndGlobal EndGlobal