From 5ff7ad3d0efea3a296a5b85d1102f69907ebcc6e Mon Sep 17 00:00:00 2001 From: Mahdiyar Ghannad Date: Wed, 16 Aug 2023 19:58:59 +0330 Subject: [PATCH] Add RegenerateToken & update client --- .../OpenAPI.cs | 124 ++++++++++++++++++ .../OpenAPI.nswag.json | 67 ++++++++++ ...AuthenticationsMicroservice.Clients.csproj | 2 +- .../Common/RegenerateTokenContract.cs | 14 ++ .../JWTManager.cs | 8 +- .../Controllers/UserController.cs | 39 ++++++ 6 files changed, 247 insertions(+), 7 deletions(-) create mode 100644 src/CSharp/EasyMicroservices.AuthenticationsMicroservice.Domain/Contracts/Common/RegenerateTokenContract.cs diff --git a/src/CSharp/EasyMicroservices.AuthenticationsMicroservice.Clients/Connected Services/AuthenticationsGeneratedServices/OpenAPI.cs b/src/CSharp/EasyMicroservices.AuthenticationsMicroservice.Clients/Connected Services/AuthenticationsGeneratedServices/OpenAPI.cs index 9617b45..228ee95 100644 --- a/src/CSharp/EasyMicroservices.AuthenticationsMicroservice.Clients/Connected Services/AuthenticationsGeneratedServices/OpenAPI.cs +++ b/src/CSharp/EasyMicroservices.AuthenticationsMicroservice.Clients/Connected Services/AuthenticationsGeneratedServices/OpenAPI.cs @@ -287,6 +287,84 @@ public virtual async System.Threading.Tasks.TaskSuccess + /// A server side error occurred. + public virtual System.Threading.Tasks.Task RegenerateTokenAsync(RegenerateTokenContract body) + { + return RegenerateTokenAsync(body, System.Threading.CancellationToken.None); + } + + /// A cancellation token that can be used by other objects or threads to receive notice of cancellation. + /// Success + /// A server side error occurred. + public virtual async System.Threading.Tasks.Task RegenerateTokenAsync(RegenerateTokenContract body, System.Threading.CancellationToken cancellationToken) + { + var urlBuilder_ = new System.Text.StringBuilder(); + urlBuilder_.Append(BaseUrl != null ? BaseUrl.TrimEnd('/') : "").Append("/api/Users/RegenerateToken"); + + var client_ = _httpClient; + var disposeClient_ = false; + try + { + using (var request_ = new System.Net.Http.HttpRequestMessage()) + { + var json_ = Newtonsoft.Json.JsonConvert.SerializeObject(body, _settings.Value); + var content_ = new System.Net.Http.StringContent(json_); + content_.Headers.ContentType = System.Net.Http.Headers.MediaTypeHeaderValue.Parse("application/json"); + request_.Content = content_; + request_.Method = new System.Net.Http.HttpMethod("POST"); + request_.Headers.Accept.Add(System.Net.Http.Headers.MediaTypeWithQualityHeaderValue.Parse("text/plain")); + + PrepareRequest(client_, request_, urlBuilder_); + + var url_ = urlBuilder_.ToString(); + request_.RequestUri = new System.Uri(url_, System.UriKind.RelativeOrAbsolute); + + PrepareRequest(client_, request_, url_); + + var response_ = await client_.SendAsync(request_, System.Net.Http.HttpCompletionOption.ResponseHeadersRead, cancellationToken).ConfigureAwait(false); + var disposeResponse_ = true; + try + { + var headers_ = System.Linq.Enumerable.ToDictionary(response_.Headers, h_ => h_.Key, h_ => h_.Value); + if (response_.Content != null && response_.Content.Headers != null) + { + foreach (var item_ in response_.Content.Headers) + headers_[item_.Key] = item_.Value; + } + + ProcessResponse(client_, response_); + + var status_ = (int)response_.StatusCode; + if (status_ == 200) + { + var objectResponse_ = await ReadObjectResponseAsync(response_, headers_, cancellationToken).ConfigureAwait(false); + if (objectResponse_.Object == null) + { + throw new ApiException("Response was null which was not expected.", status_, objectResponse_.Text, headers_, null); + } + return objectResponse_.Object; + } + else + { + var responseData_ = response_.Content == null ? null : await response_.Content.ReadAsStringAsync().ConfigureAwait(false); + throw new ApiException("The HTTP status code of the response was not expected (" + status_ + ").", status_, responseData_, headers_, null); + } + } + finally + { + if (disposeResponse_) + response_.Dispose(); + } + } + } + finally + { + if (disposeClient_) + client_.Dispose(); + } + } + /// Success /// A server side error occurred. public virtual System.Threading.Tasks.Task TestAsync() @@ -1570,6 +1648,52 @@ protected virtual void RaisePropertyChanged([System.Runtime.CompilerServices.Cal } } + [System.CodeDom.Compiler.GeneratedCode("NJsonSchema", "13.19.0.0 (NJsonSchema v10.9.0.0 (Newtonsoft.Json v13.0.3.0))")] + public partial class RegenerateTokenContract : System.ComponentModel.INotifyPropertyChanged + { + private long _userId; + private System.Collections.Generic.ICollection _claims; + + [Newtonsoft.Json.JsonProperty("userId", Required = Newtonsoft.Json.Required.DisallowNull, NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore)] + public long UserId + { + get { return _userId; } + + set + { + if (_userId != value) + { + _userId = value; + RaisePropertyChanged(); + } + } + } + + [Newtonsoft.Json.JsonProperty("claims", Required = Newtonsoft.Json.Required.Default, NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore)] + public System.Collections.Generic.ICollection Claims + { + get { return _claims; } + + set + { + if (_claims != value) + { + _claims = value; + RaisePropertyChanged(); + } + } + } + + public event System.ComponentModel.PropertyChangedEventHandler PropertyChanged; + + protected virtual void RaisePropertyChanged([System.Runtime.CompilerServices.CallerMemberName] string propertyName = null) + { + var handler = PropertyChanged; + if (handler != null) + handler(this, new System.ComponentModel.PropertyChangedEventArgs(propertyName)); + } + } + [System.CodeDom.Compiler.GeneratedCode("NJsonSchema", "13.19.0.0 (NJsonSchema v10.9.0.0 (Newtonsoft.Json v13.0.3.0))")] public partial class UserClaimContract : System.ComponentModel.INotifyPropertyChanged { diff --git a/src/CSharp/EasyMicroservices.AuthenticationsMicroservice.Clients/Connected Services/AuthenticationsGeneratedServices/OpenAPI.nswag.json b/src/CSharp/EasyMicroservices.AuthenticationsMicroservice.Clients/Connected Services/AuthenticationsGeneratedServices/OpenAPI.nswag.json index 51feaa1..52f1fe3 100644 --- a/src/CSharp/EasyMicroservices.AuthenticationsMicroservice.Clients/Connected Services/AuthenticationsGeneratedServices/OpenAPI.nswag.json +++ b/src/CSharp/EasyMicroservices.AuthenticationsMicroservice.Clients/Connected Services/AuthenticationsGeneratedServices/OpenAPI.nswag.json @@ -152,6 +152,55 @@ } } }, + "/api/Users/RegenerateToken": { + "post": { + "tags": [ + "Users" + ], + "operationId": "RegenerateToken", + "requestBody": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/RegenerateTokenContract" + } + }, + "text/json": { + "schema": { + "$ref": "#/components/schemas/RegenerateTokenContract" + } + }, + "application/*+json": { + "schema": { + "$ref": "#/components/schemas/RegenerateTokenContract" + } + } + } + }, + "responses": { + "200": { + "description": "Success", + "content": { + "text/plain": { + "schema": { + "$ref": "#/components/schemas/UserResponseContractMessageContract" + } + }, + "application/json": { + "schema": { + "$ref": "#/components/schemas/UserResponseContractMessageContract" + } + }, + "text/json": { + "schema": { + "$ref": "#/components/schemas/UserResponseContractMessageContract" + } + } + } + } + } + } + }, "/api/Users/Test": { "get": { "tags": [ @@ -736,6 +785,24 @@ } } }, + "RegenerateTokenContract": { + "type": "object", + "additionalProperties": false, + "properties": { + "userId": { + "type": "integer", + "format": "int64" + }, + "claims": { + "title": "List", + "type": "array", + "nullable": true, + "items": { + "$ref": "#/components/schemas/ClaimContract" + } + } + } + }, "UserClaimContract": { "type": "object", "additionalProperties": false, diff --git a/src/CSharp/EasyMicroservices.AuthenticationsMicroservice.Clients/EasyMicroservices.AuthenticationsMicroservice.Clients.csproj b/src/CSharp/EasyMicroservices.AuthenticationsMicroservice.Clients/EasyMicroservices.AuthenticationsMicroservice.Clients.csproj index b8982bf..54dc15a 100644 --- a/src/CSharp/EasyMicroservices.AuthenticationsMicroservice.Clients/EasyMicroservices.AuthenticationsMicroservice.Clients.csproj +++ b/src/CSharp/EasyMicroservices.AuthenticationsMicroservice.Clients/EasyMicroservices.AuthenticationsMicroservice.Clients.csproj @@ -5,7 +5,7 @@ AnyCPU;x64;x86 EasyMicroservices true - 0.0.0.5 + 0.0.0.6 client generated code. EasyMicroservices@gmail.com microservice,auth,authentication,client diff --git a/src/CSharp/EasyMicroservices.AuthenticationsMicroservice.Domain/Contracts/Common/RegenerateTokenContract.cs b/src/CSharp/EasyMicroservices.AuthenticationsMicroservice.Domain/Contracts/Common/RegenerateTokenContract.cs new file mode 100644 index 0000000..8780368 --- /dev/null +++ b/src/CSharp/EasyMicroservices.AuthenticationsMicroservice.Domain/Contracts/Common/RegenerateTokenContract.cs @@ -0,0 +1,14 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace EasyMicroservices.AuthenticationsMicroservice.Contracts.Common +{ + public class RegenerateTokenContract + { + public long UserId { get; set; } + public List Claims { get; set; } + } +} diff --git a/src/CSharp/EasyMicroservices.AuthenticationsMicroservice.Services/JWTManager.cs b/src/CSharp/EasyMicroservices.AuthenticationsMicroservice.Services/JWTManager.cs index 4d1e896..7cdf78e 100644 --- a/src/CSharp/EasyMicroservices.AuthenticationsMicroservice.Services/JWTManager.cs +++ b/src/CSharp/EasyMicroservices.AuthenticationsMicroservice.Services/JWTManager.cs @@ -30,10 +30,8 @@ public JWTManager(IContractLogic> Login(UserSummaryContract cred) { - string Password = await AuthenticationHelper.HashPassword(cred.Password); - var userRecords = await _userLogic.GetAll(); - var user = userRecords.Result.Where(x => x.UserName == cred.UserName && x.Password == Password); + var user = userRecords.Result.Where(x => x.UserName == cred.UserName && x.Password == cred.Password); if (!user.Any()) return (FailedReasonType.AccessDenied, "Username or password is invalid."); //"Username or password is invalid." @@ -48,9 +46,7 @@ public virtual async Task> GenerateToken(U if (!response) return response.ToContract(); - string Password = await AuthenticationHelper.HashPassword(cred.Password); - - var user = await _userLogic.GetBy(x => x.UserName == cred.UserName && x.Password == Password); + var user = await _userLogic.GetBy(x => x.UserName == cred.UserName && x.Password == cred.Password); var tokenHandler = new JwtSecurityTokenHandler(); var key = Encoding.UTF8.GetBytes(_config.GetValue("JWT:Key")); diff --git a/src/CSharp/EasyMicroservices.AuthenticationsMicroservice.WebApi/Controllers/UserController.cs b/src/CSharp/EasyMicroservices.AuthenticationsMicroservice.WebApi/Controllers/UserController.cs index 935a461..1d29333 100644 --- a/src/CSharp/EasyMicroservices.AuthenticationsMicroservice.WebApi/Controllers/UserController.cs +++ b/src/CSharp/EasyMicroservices.AuthenticationsMicroservice.WebApi/Controllers/UserController.cs @@ -2,10 +2,12 @@ using EasyMicroservices.AuthenticationsMicroservice.Contracts.Requests; using EasyMicroservices.AuthenticationsMicroservice.Contracts.Responses; using EasyMicroservices.AuthenticationsMicroservice.Database.Entities; +using EasyMicroservices.AuthenticationsMicroservice.Helpers; using EasyMicroservices.AuthenticationsMicroservice.Interfaces; using EasyMicroservices.Cores.AspCoreApi; using EasyMicroservices.Cores.Database.Interfaces; using EasyMicroservices.ServiceContracts; +using Microsoft.AspNetCore.Authentication; using Microsoft.AspNetCore.Authentication.JwtBearer; using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Identity; @@ -42,6 +44,9 @@ public async Task> Register(AddUserRequestContract request [HttpPost] public async Task> Login(UserSummaryContract request) { + string password = await AuthenticationHelper.HashPassword(request.Password); + request.Password = password; + var response = await _jwtManager.Login(request); return response; @@ -51,11 +56,45 @@ public async Task> Login(UserSummaryContract request) [HttpPost] public async Task> GenerateToken(UserClaimContract request) { + string password = await AuthenticationHelper.HashPassword(request.Password); + request.Password = password; + var response = await _jwtManager.GenerateToken(request); return response; } + [HttpPost] + public async Task> RegenerateToken(RegenerateTokenContract request) + { + var user = await _contractLogic.GetById(new Cores.Contracts.Requests.GetIdRequestContract + { + Id = request.UserId + }); + + if (user) + { + + string password = user.Result.Password; + + var req = new UserClaimContract + { + Password = password, + UserName = user.Result.UserName, + Claims = request.Claims + }; + + var response = await _jwtManager.GenerateToken(req); + + return new UserResponseContract + { + Token = response.Result.Token + }; + } + + return user.ToContract(); + } + [HttpGet] [Authorize] public string Test()