From 6877db6a535e57fd1d7e01c966a6451dc6f186f0 Mon Sep 17 00:00:00 2001 From: crupest Date: Sat, 24 Apr 2021 19:13:35 +0800 Subject: refactor: Refactor auth handler messages. --- BackEnd/Timeline/Auth/MyAuthenticationHandler.cs | 55 ++++---- BackEnd/Timeline/Auth/Resource.Designer.cs | 153 +++++++++++++++++++++++ BackEnd/Timeline/Auth/Resource.resx | 150 ++++++++++++++++++++++ 3 files changed, 333 insertions(+), 25 deletions(-) create mode 100644 BackEnd/Timeline/Auth/Resource.Designer.cs create mode 100644 BackEnd/Timeline/Auth/Resource.resx (limited to 'BackEnd/Timeline/Auth') diff --git a/BackEnd/Timeline/Auth/MyAuthenticationHandler.cs b/BackEnd/Timeline/Auth/MyAuthenticationHandler.cs index f1f71b20..f3d18a0e 100644 --- a/BackEnd/Timeline/Auth/MyAuthenticationHandler.cs +++ b/BackEnd/Timeline/Auth/MyAuthenticationHandler.cs @@ -14,7 +14,6 @@ using System.Threading.Tasks; using Timeline.Models; using Timeline.Models.Http; using Timeline.Services; -using static Timeline.Resources.Authentication.AuthHandler; namespace Timeline.Auth { @@ -37,16 +36,28 @@ namespace Timeline.Auth { private const string TokenErrorCodeKey = "TokenErrorCode"; - private static CommonResponse CreateChallengeResponseBody(int errorCode) + private static int GetErrorCodeForUserTokenException(UserTokenException e) { - return new CommonResponse(errorCode, errorCode switch + return e switch { - ErrorCodes.Common.Token.TimeExpired => "The token is out of date and expired. Please create a new one.", - ErrorCodes.Common.Token.VersionExpired => "The token is of old version and expired. Please create a new one.", - ErrorCodes.Common.Token.BadFormat => "The token is of bad format. It might not be created by this server.", - ErrorCodes.Common.Token.UserNotExist => "The owner of the token does not exist. It might have been deleted.", - _ => "Unknown error." - }); + UserTokenTimeExpiredException => ErrorCodes.Common.Token.TimeExpired, + UserTokenVersionExpiredException => ErrorCodes.Common.Token.VersionExpired, + UserTokenBadFormatException => ErrorCodes.Common.Token.BadFormat, + UserTokenUserNotExistException => ErrorCodes.Common.Token.UserNotExist, + _ => ErrorCodes.Common.Token.Unknown + }; + } + + private static string GetTokenErrorMessageFromErrorCode(int errorCode) + { + return errorCode switch + { + ErrorCodes.Common.Token.TimeExpired => Resource.MessageTokenTimeExpired, + ErrorCodes.Common.Token.VersionExpired => Resource.MessageTokenVersionExpired, + ErrorCodes.Common.Token.BadFormat => Resource.MessageTokenBadFormat, + ErrorCodes.Common.Token.UserNotExist => Resource.MessageTokenUserNotExist, + _ => Resource.MessageTokenUnknownError + }; } private readonly ILogger _logger; @@ -72,7 +83,7 @@ namespace Timeline.Auth if (!string.IsNullOrEmpty(header) && header.StartsWith("Bearer ", StringComparison.OrdinalIgnoreCase)) { var token = header["Bearer ".Length..].Trim(); - _logger.LogInformation(LogTokenFoundInHeader, token); + _logger.LogInformation(Resource.LogTokenFoundInHeader, token); return token; } @@ -83,7 +94,7 @@ namespace Timeline.Auth string token = Request.Query[paramQueryKey]; if (!string.IsNullOrEmpty(token)) { - _logger.LogInformation(LogTokenFoundInQuery, paramQueryKey, token); + _logger.LogInformation(Resource.LogTokenFoundInQuery, paramQueryKey, token); return token; } } @@ -97,7 +108,7 @@ namespace Timeline.Auth var token = ExtractToken(); if (string.IsNullOrEmpty(token)) { - _logger.LogInformation(LogTokenNotFound); + _logger.LogInformation(Resource.LogTokenNotFound); return AuthenticateResult.NoResult(); } @@ -117,19 +128,14 @@ namespace Timeline.Auth return AuthenticateResult.Success(new AuthenticationTicket(principal, AuthenticationConstants.Scheme)); } - catch (Exception e) when (!(e is ArgumentException)) + catch (UserTokenException e) { - _logger.LogInformation(e, LogTokenValidationFail); + var errorCode = GetErrorCodeForUserTokenException(e); + + _logger.LogInformation(e, Resource.LogTokenValidationFail, GetTokenErrorMessageFromErrorCode(errorCode)); return AuthenticateResult.Fail(e, new AuthenticationProperties(new Dictionary() { - [TokenErrorCodeKey] = (e switch - { - UserTokenTimeExpiredException => ErrorCodes.Common.Token.TimeExpired, - UserTokenVersionExpiredException => ErrorCodes.Common.Token.VersionExpired, - UserTokenBadFormatException => ErrorCodes.Common.Token.BadFormat, - UserTokenUserNotExistException => ErrorCodes.Common.Token.UserNotExist, - _ => ErrorCodes.Common.Token.Unknown - }).ToString(CultureInfo.InvariantCulture) + [TokenErrorCodeKey] = errorCode.ToString(CultureInfo.InvariantCulture) })); } } @@ -144,14 +150,13 @@ namespace Timeline.Auth { if (!int.TryParse(tokenErrorCode, out var errorCode)) errorCode = ErrorCodes.Common.Token.Unknown; - body = CreateChallengeResponseBody(errorCode); + body = new CommonResponse(errorCode, GetTokenErrorMessageFromErrorCode(errorCode)); } else { - body = new CommonResponse(ErrorCodes.Common.Unauthorized, "You must use a token to authenticate."); + body = new CommonResponse(ErrorCodes.Common.Unauthorized, Resource.MessageNoToken); } - var bodyData = JsonSerializer.SerializeToUtf8Bytes(body, typeof(CommonResponse), _jsonOptions.CurrentValue.JsonSerializerOptions); Response.ContentType = MimeTypes.ApplicationJson; diff --git a/BackEnd/Timeline/Auth/Resource.Designer.cs b/BackEnd/Timeline/Auth/Resource.Designer.cs new file mode 100644 index 00000000..e9ef970e --- /dev/null +++ b/BackEnd/Timeline/Auth/Resource.Designer.cs @@ -0,0 +1,153 @@ +//------------------------------------------------------------------------------ +// +// This code was generated by a tool. +// Runtime Version:4.0.30319.42000 +// +// Changes to this file may cause incorrect behavior and will be lost if +// the code is regenerated. +// +//------------------------------------------------------------------------------ + +namespace Timeline.Auth { + using System; + + + /// + /// A strongly-typed resource class, for looking up localized strings, etc. + /// + // This class was auto-generated by the StronglyTypedResourceBuilder + // class via a tool like ResGen or Visual Studio. + // To add or remove a member, edit your .ResX file then rerun ResGen + // with the /str option, or rebuild your VS project. + [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Resources.Tools.StronglyTypedResourceBuilder", "16.0.0.0")] + [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] + [global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()] + internal class Resource { + + private static global::System.Resources.ResourceManager resourceMan; + + private static global::System.Globalization.CultureInfo resourceCulture; + + [global::System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")] + internal Resource() { + } + + /// + /// Returns the cached ResourceManager instance used by this class. + /// + [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)] + internal static global::System.Resources.ResourceManager ResourceManager { + get { + if (object.ReferenceEquals(resourceMan, null)) { + global::System.Resources.ResourceManager temp = new global::System.Resources.ResourceManager("Timeline.Auth.Resource", typeof(Resource).Assembly); + resourceMan = temp; + } + return resourceMan; + } + } + + /// + /// Overrides the current thread's CurrentUICulture property for all + /// resource lookups using this strongly typed resource class. + /// + [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)] + internal static global::System.Globalization.CultureInfo Culture { + get { + return resourceCulture; + } + set { + resourceCulture = value; + } + } + + /// + /// Looks up a localized string similar to Token is found in authorization header. Token is {0} .. + /// + internal static string LogTokenFoundInHeader { + get { + return ResourceManager.GetString("LogTokenFoundInHeader", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to Token is found in query param with key "{0}". Token is {1} .. + /// + internal static string LogTokenFoundInQuery { + get { + return ResourceManager.GetString("LogTokenFoundInQuery", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to No jwt token is found.. + /// + internal static string LogTokenNotFound { + get { + return ResourceManager.GetString("LogTokenNotFound", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to A jwt token validation failed. Error reason: {0}. + /// + internal static string LogTokenValidationFail { + get { + return ResourceManager.GetString("LogTokenValidationFail", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to You must use a token to authenticate to access this resource.. + /// + internal static string MessageNoToken { + get { + return ResourceManager.GetString("MessageNoToken", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to The token is of bad format. It might not be created by this server.. + /// + internal static string MessageTokenBadFormat { + get { + return ResourceManager.GetString("MessageTokenBadFormat", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to The token is out of date and expired. Please create a new one.. + /// + internal static string MessageTokenTimeExpired { + get { + return ResourceManager.GetString("MessageTokenTimeExpired", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to A unknown error occured when verify token.. + /// + internal static string MessageTokenUnknownError { + get { + return ResourceManager.GetString("MessageTokenUnknownError", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to The owner of the token does not exist. It might have been deleted.. + /// + internal static string MessageTokenUserNotExist { + get { + return ResourceManager.GetString("MessageTokenUserNotExist", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to The token is of old version and expired. Please create a new one.. + /// + internal static string MessageTokenVersionExpired { + get { + return ResourceManager.GetString("MessageTokenVersionExpired", resourceCulture); + } + } + } +} diff --git a/BackEnd/Timeline/Auth/Resource.resx b/BackEnd/Timeline/Auth/Resource.resx new file mode 100644 index 00000000..21f2b2de --- /dev/null +++ b/BackEnd/Timeline/Auth/Resource.resx @@ -0,0 +1,150 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + text/microsoft-resx + + + 2.0 + + + System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + Token is found in authorization header. Token is {0} . + + + Token is found in query param with key "{0}". Token is {1} . + + + No jwt token is found. + + + A jwt token validation failed. Error reason: {0} + + + You must use a token to authenticate to access this resource. + + + The token is of bad format. It might not be created by this server. + + + The token is out of date and expired. Please create a new one. + + + A unknown error occured when verify token. + + + The owner of the token does not exist. It might have been deleted. + + + The token is of old version and expired. Please create a new one. + + \ No newline at end of file -- cgit v1.2.3