Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
14 changes: 14 additions & 0 deletions DTO/Identity/TokenResponse.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace DTO.Identity
{
public sealed class TokenResponse
{
public string Token { get; set; }
public string RefreshToken { get; set; }
}
}
6 changes: 4 additions & 2 deletions Data/Thoughts.Identity.DAL/Interfaces/IAuthUtils.cs
Original file line number Diff line number Diff line change
@@ -1,7 +1,9 @@
namespace Thoughts.Identity.DAL.Interfaces
using DTO.Identity;

namespace Thoughts.Identity.DAL.Interfaces
{
public interface IAuthUtils<TUser>
{
string CreateSessionToken(TUser user, IList<string> role);
TokenResponse CreateSessionToken(TUser user, IList<string> role);
}
}
1 change: 1 addition & 0 deletions Data/Thoughts.Identity.DAL/Thoughts.Identity.DAL.csproj
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@
</ItemGroup>

<ItemGroup>
<ProjectReference Include="..\..\DTO\DTO.csproj" />
<ProjectReference Include="..\Thoughts.DAL.Entities\Thoughts.DAL.Entities.csproj" />
</ItemGroup>

Expand Down
37 changes: 35 additions & 2 deletions Services/Thoughts.WebAPI.Clients/Identity/AccountClient.cs
Original file line number Diff line number Diff line change
@@ -1,19 +1,20 @@
using System.Net.Http.Json;
using System.Net;
using System.Net.Http.Headers;

using Microsoft.Extensions.Logging;

using Thoughts.DAL.Entities.Idetity;

using static WebStore.Interfaces.Services.WebAPIAddresses.Addresses.Identity;
using System.Threading;
using System.IdentityModel.Tokens.Jwt;
using static System.Net.WebRequestMethods;

namespace Thoughts.WebAPI.Clients.Identity;

public class AccountClient //: BaseClient //, UsersClient, IRolesClient
{
private readonly ILogger<AccountClient> _Logger;
private string _refreshToken;
public HttpClient Http { get; }

public AccountClient(HttpClient Http, ILogger<AccountClient> Logger)
Expand All @@ -24,6 +25,8 @@ public AccountClient(HttpClient Http, ILogger<AccountClient> Logger)

public async Task<List<IdentUser>?> GetAllUsersAsync(CancellationToken Cancel = default)
{
await CheckToken(Cancel).ConfigureAwait(false);

var response = await Http.GetAsync($"{Accounts}/GetAllUsers", Cancel).ConfigureAwait(false);

switch (response.StatusCode)
Expand All @@ -43,6 +46,8 @@ public AccountClient(HttpClient Http, ILogger<AccountClient> Logger)

public async Task<List<IdentRole>?> GetAllRolessAsync(CancellationToken Cancel = default)
{
await CheckToken(Cancel).ConfigureAwait(false);

var response = await Http.GetAsync($"{Accounts}/GetAllRoles", Cancel).ConfigureAwait(false);

switch (response.StatusCode)
Expand All @@ -60,6 +65,33 @@ public AccountClient(HttpClient Http, ILogger<AccountClient> Logger)
}
}

private async Task CheckToken(CancellationToken Cancel)
{
var token = Http.DefaultRequestHeaders.Authorization.Parameter;

var jwtSecurityTokenHandler = new JwtSecurityTokenHandler();

var decodeJWT = jwtSecurityTokenHandler.ReadJwtToken(token);

if (decodeJWT.ValidTo < DateTime.UtcNow)
{
var decodeRefreshJWT = jwtSecurityTokenHandler.ReadJwtToken(_refreshToken);
if (decodeRefreshJWT.ValidTo > DateTime.UtcNow)
{
var responseRefreshToken = await Http.GetAsync($"{Accounts}/GetRefreshToken", Cancel).ConfigureAwait(false);

if (responseRefreshToken.StatusCode == HttpStatusCode.OK)
{
var bearer = responseRefreshToken.Headers.GetValues("Authorization").FirstOrDefault();
Http.DefaultRequestHeaders.Authorization = new("Bearer", bearer);
_refreshToken = responseRefreshToken.Headers.GetValues("RefreshToken").FirstOrDefault();
}
else
throw new InvalidOperationException("Не удалось обновить токен!");
}
}
}

public async Task LoginAsync(string login, string password, CancellationToken Cancel = default)
{
var response = await Http.PostAsJsonAsync($"{Accounts}/Login", new { login, password }).ConfigureAwait(false);
Expand All @@ -68,6 +100,7 @@ public async Task LoginAsync(string login, string password, CancellationToken Ca
{
var bearer = response.Headers.GetValues("Authorization").FirstOrDefault();
Http.DefaultRequestHeaders.Authorization = new("Bearer", bearer);
_refreshToken = response.Headers.GetValues("RefreshToken").FirstOrDefault();
}
else
throw new InvalidOperationException("Не удалось получить токен от сервера! Авторизация не выполнена.");
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,8 @@
<PackageReference Include="Microsoft.AspNet.WebApi.Client" Version="5.2.9" />
<PackageReference Include="Microsoft.Extensions.Configuration.Abstractions" Version="6.0.0" />
<PackageReference Include="Microsoft.Extensions.Http" Version="6.0.0" />
<PackageReference Include="Microsoft.IdentityModel.Tokens" Version="6.8.0" />
<PackageReference Include="System.IdentityModel.Tokens.Jwt" Version="6.8.0" />
<PackageReference Include="System.Net.Http.Json" Version="6.0.0" />
</ItemGroup>

Expand Down
45 changes: 43 additions & 2 deletions Services/Thoughts.WebAPI/Controllers/Identity/AccountController.cs
Original file line number Diff line number Diff line change
@@ -1,4 +1,6 @@
using DTO.Identity;
using System.IdentityModel.Tokens.Jwt;

using DTO.Identity;
using DTO.Thoughts.Identity;

using Microsoft.AspNetCore.Authorization;
Expand Down Expand Up @@ -98,7 +100,8 @@ public async Task<IActionResult> LoginAsync([FromBody] LoginUserDTO loginUserDTO
{
_logger.LogInformation("Авторизация пользователя {0} успешна", loginUserDTO.Login);
var sessionToken = _authUtils.CreateSessionToken(user, roles);
Response.Headers.Add("Authorization", sessionToken);
Response.Headers.Add("Authorization", sessionToken.Token);
Response.Headers.Add("RefreshToken", sessionToken.RefreshToken);
return Ok();
}
}
Expand All @@ -116,6 +119,44 @@ public async Task<IActionResult> LoginAsync([FromBody] LoginUserDTO loginUserDTO
return BadRequest("Авторизовать пользователя не удалось");
}

[AllowAnonymous]
[HttpGet("GetRefreshToken")]
public async Task<IActionResult> GetRefreshTokenAsync()
{
try
{
var headersAuthorization = (string)_contextAccessor.HttpContext.Request.Headers.Authorization;
var jwtToken = headersAuthorization.Remove(0, 7);
var jwtSecurityTokenHandler = new JwtSecurityTokenHandler();

//var decodeRefreshJWT = jwtSecurityTokenHandler.ReadJwtToken(RefreshTokenDTO.RefreshToken);
var decodeRefreshJWT = jwtSecurityTokenHandler.ReadJwtToken(jwtToken);
var login = (string)decodeRefreshJWT.Payload.First(x => x.Key.Equals("unique_name")).Value;

var user = await _userManager.FindByNameAsync(login);
if (user is not null)
{
var roles = await _userManager.GetRolesAsync(user);

var sessionToken = _authUtils.CreateSessionToken(user, roles);
Response.Headers.Add("Authorization", sessionToken.Token);
Response.Headers.Add("RefreshToken", sessionToken.RefreshToken);
return Ok();
}
}
catch (Exception ex)
{
if (_logger.IsEnabled(LogLevel.Error))
{
_logger.LogError(ex, "Не удалось обновить токен пользователя");
}
}

_logger.LogInformation("Не удалось обновить токен пользователя");

return BadRequest("Не удалось обновить токен пользователя");
}

[AllowAnonymous]
[HttpPost("Logout")]
public async Task<IActionResult> LogoutAsync()
Expand Down
30 changes: 27 additions & 3 deletions Services/Thoughts.WebAPI/Services/AuthUtils.cs
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,8 @@
using System.Security.Claims;
using System.Text;

using DTO.Identity;

using Microsoft.AspNetCore.Identity;
using Microsoft.IdentityModel.Tokens;

Expand All @@ -14,15 +16,20 @@ public class AuthUtils : IAuthUtils<IdentUser>
{
private readonly IConfiguration _configuration;
private string _secretKey;
private double _accessTokenTimeMinute;
private double _refreshTokenTimeMinute;

public AuthUtils(IConfiguration configuration)
{
_configuration = configuration;
}
public string CreateSessionToken(IdentUser user, IList<string> roles)
public TokenResponse CreateSessionToken(IdentUser user, IList<string> roles)
{
double resultParse;
var config = _configuration.GetSection("SecretTokenKey");
_secretKey = config["Key"];
_accessTokenTimeMinute = double.TryParse(config["AccessTokenTimeMinute"], out resultParse) ? resultParse : 15;
_refreshTokenTimeMinute = double.TryParse(config["RefreshTokenTimeMinute"], out resultParse) ? resultParse : 360;

JwtSecurityTokenHandler jwtSecurityTokenHandler = new JwtSecurityTokenHandler();

Expand All @@ -42,16 +49,33 @@ public string CreateSessionToken(IdentUser user, IList<string> roles)
{
Subject = new ClaimsIdentity(claims.ToArray()),

Expires = DateTime.Now.AddMinutes(15),
Expires = DateTime.Now.AddMinutes(_accessTokenTimeMinute),

SigningCredentials = new SigningCredentials(
new SymmetricSecurityKey(key), SecurityAlgorithms.HmacSha256Signature)
};

SecurityToken securityToken = jwtSecurityTokenHandler.CreateToken(securityTokenDescriptor);

return jwtSecurityTokenHandler.WriteToken(securityToken);
var tokenResponse = new TokenResponse();

tokenResponse.Token = jwtSecurityTokenHandler.WriteToken(securityToken);

var securityRefreshTokenDescriptor = new SecurityTokenDescriptor()
{
Subject = new ClaimsIdentity(claims.ToArray()),

Expires = DateTime.Now.AddMinutes(_refreshTokenTimeMinute),

SigningCredentials = new SigningCredentials(
new SymmetricSecurityKey(key), SecurityAlgorithms.HmacSha256Signature)
};

SecurityToken securityRefreshToken = jwtSecurityTokenHandler.CreateToken(securityRefreshTokenDescriptor);

tokenResponse.RefreshToken = jwtSecurityTokenHandler.WriteToken(securityRefreshToken);

return tokenResponse;
}
}
}
2 changes: 1 addition & 1 deletion Services/Thoughts.WebAPI/Thoughts.WebAPI.csproj
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
<Project Sdk="Microsoft.NET.Sdk.Web">
<Project Sdk="Microsoft.NET.Sdk.Web">

<PropertyGroup>
<TargetFramework>net6.0</TargetFramework>
Expand Down
4 changes: 3 additions & 1 deletion Services/Thoughts.WebAPI/appsettings.json
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,9 @@
}
},
"SecretTokenKey": {
"Key": "vRguqNCvKJHkhs578443sa46@#sakjjRxDGMFguqNCMz8w2DGMQ=="
"Key": "vRguqNCvKJHkhs578443sa46@#sakjjRxDGMFguqNCMz8w2DGMQ==",
"AccessTokenTimeMinute": 1,
"RefreshTokenTimeMinute": 2
},
"AllowedHosts": "*"
}
3 changes: 2 additions & 1 deletion UI/Thoughts.UI.WPF/App.xaml.cs
Original file line number Diff line number Diff line change
Expand Up @@ -6,8 +6,9 @@
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;

using Polly;

using Polly.Extensions.Http;
using Polly;

using Thoughts.UI.WPF.ViewModels;
using Thoughts.WebAPI.Clients.Identity;
Expand Down
4 changes: 3 additions & 1 deletion UI/Thoughts.UI.WPF/MainWindow.xaml
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,9 @@
Background="Transparent"
Foreground="Black"
FontFamily="Helvetica"
DataContext="{Binding MainWindowModel, Source={StaticResource Locator}}"

DataContext="{Binding MainWindowModel, Source={StaticResource Locator}}"

Title="{Binding Title, Mode=OneWay}"
x:Name="MainWindows">
<Window.Resources>
Expand Down
7 changes: 5 additions & 2 deletions UI/Thoughts.UI.WPF/Styles/PasswordBoxStyle.xaml
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,8 @@
<Border.BorderBrush>
<SolidColorBrush Color="#5f9ea0"/>
</Border.BorderBrush>
<VisualStateManager.VisualStateGroups>

<VisualStateManager.VisualStateGroups>
<VisualStateGroup x:Name="CommonStates">
<VisualState x:Name="Normal">
<Storyboard>
Expand Down Expand Up @@ -60,7 +61,9 @@
To="2"
Duration="0:0:0.5"
RepeatBehavior="1x"




/>
<ColorAnimationUsingKeyFrames Storyboard.TargetName="Border"
Storyboard.TargetProperty="(Border.BorderBrush).(SolidColorBrush.Color)"
Expand Down
6 changes: 4 additions & 2 deletions UI/Thoughts.UI.WPF/Thoughts.UI.WPF.csproj
Original file line number Diff line number Diff line change
Expand Up @@ -17,9 +17,11 @@
<ItemGroup>
<PackageReference Include="FontAwesome5" Version="2.1.11" />
<PackageReference Include="Microsoft.Extensions.Hosting" Version="6.0.1" />
<PackageReference Include="Microsoft.Extensions.Http.Polly" Version="6.0.10" />

<PackageReference Include="Microsoft.Extensions.Http.Polly" Version="6.0.10" />
<PackageReference Include="Microsoft.Xaml.Behaviors.Wpf" Version="1.1.39" />
<PackageReference Include="Polly.Extensions.Http" Version="3.0.0" />
<PackageReference Include="Polly.Extensions.Http" Version="3.0.0" />

</ItemGroup>

<ItemGroup>
Expand Down
10 changes: 5 additions & 5 deletions UI/Thoughts.UI.WPF/ViewModels/AccountsViewModel.cs
Original file line number Diff line number Diff line change
@@ -1,8 +1,10 @@
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Net.Http;

using System.Windows;
using System.Windows.Controls;

using System.Windows.Input;
using System.Windows.Media;

Expand All @@ -16,20 +18,21 @@ namespace Thoughts.UI.WPF.ViewModels
{
public class AccountsViewModel : ViewModel
{

private static AccountClient _account_client;

public AccountsViewModel(AccountClient account_client)
{
_account_client = account_client;
}

private static AccountClient _account_client;

private ObservableCollection<IdentUser> _identUserCollection = new ObservableCollection<IdentUser>();
private ObservableCollection<IdentRole> _identRoleCollection = new ObservableCollection<IdentRole>();
private string _title;
private string _userName; // Admin // AdPAss_123
private bool _isAuthorization;


public ObservableCollection<IdentUser> IdentUserCollection
{
get => _identUserCollection;
Expand Down Expand Up @@ -91,7 +94,6 @@ public ICommand Login
MessageBox.Show("Авторизация не выполнена.");
}


}, (p) => !_isAuthorization);
}
}
Expand Down Expand Up @@ -170,7 +172,5 @@ private static void ChangeTitle(string name = "")
}
}
}


}
}
Loading