aboutsummaryrefslogtreecommitdiff
path: root/BackEnd
diff options
context:
space:
mode:
authorcrupest <crupest@outlook.com>2021-04-24 19:13:35 +0800
committercrupest <crupest@outlook.com>2021-04-24 19:13:35 +0800
commit9adfa3c8311f4ace9388dc805f1a4df6fba97f0e (patch)
tree8f281b19367613dbd2633e0bc0e0e02a529bae09 /BackEnd
parent9deda660ef57d2687d5e44597c4ba5de46ed4097 (diff)
downloadtimeline-9adfa3c8311f4ace9388dc805f1a4df6fba97f0e.tar.gz
timeline-9adfa3c8311f4ace9388dc805f1a4df6fba97f0e.tar.bz2
timeline-9adfa3c8311f4ace9388dc805f1a4df6fba97f0e.zip
refactor: Refactor auth handler messages.
Diffstat (limited to 'BackEnd')
-rw-r--r--BackEnd/Timeline/Auth/MyAuthenticationHandler.cs55
-rw-r--r--BackEnd/Timeline/Auth/Resource.Designer.cs (renamed from BackEnd/Timeline/Resources/Authentication/AuthHandler.Designer.cs)64
-rw-r--r--BackEnd/Timeline/Auth/Resource.resx (renamed from BackEnd/Timeline/Resources/Authentication/AuthHandler.resx)20
-rw-r--r--BackEnd/Timeline/Timeline.csproj14
4 files changed, 115 insertions, 38 deletions
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<MyAuthenticationHandler> _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<string, string?>()
{
- [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/Resources/Authentication/AuthHandler.Designer.cs b/BackEnd/Timeline/Auth/Resource.Designer.cs
index fd4540ea..e9ef970e 100644
--- a/BackEnd/Timeline/Resources/Authentication/AuthHandler.Designer.cs
+++ b/BackEnd/Timeline/Auth/Resource.Designer.cs
@@ -8,7 +8,7 @@
// </auto-generated>
//------------------------------------------------------------------------------
-namespace Timeline.Resources.Authentication {
+namespace Timeline.Auth {
using System;
@@ -22,14 +22,14 @@ namespace Timeline.Resources.Authentication {
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Resources.Tools.StronglyTypedResourceBuilder", "16.0.0.0")]
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
[global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()]
- internal class AuthHandler {
+ 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 AuthHandler() {
+ internal Resource() {
}
/// <summary>
@@ -39,7 +39,7 @@ namespace Timeline.Resources.Authentication {
internal static global::System.Resources.ResourceManager ResourceManager {
get {
if (object.ReferenceEquals(resourceMan, null)) {
- global::System.Resources.ResourceManager temp = new global::System.Resources.ResourceManager("Timeline.Resources.Authentication.AuthHandler", typeof(AuthHandler).Assembly);
+ global::System.Resources.ResourceManager temp = new global::System.Resources.ResourceManager("Timeline.Auth.Resource", typeof(Resource).Assembly);
resourceMan = temp;
}
return resourceMan;
@@ -88,12 +88,66 @@ namespace Timeline.Resources.Authentication {
}
/// <summary>
- /// Looks up a localized string similar to A jwt token validation failed..
+ /// Looks up a localized string similar to A jwt token validation failed. Error reason: {0}.
/// </summary>
internal static string LogTokenValidationFail {
get {
return ResourceManager.GetString("LogTokenValidationFail", resourceCulture);
}
}
+
+ /// <summary>
+ /// Looks up a localized string similar to You must use a token to authenticate to access this resource..
+ /// </summary>
+ internal static string MessageNoToken {
+ get {
+ return ResourceManager.GetString("MessageNoToken", resourceCulture);
+ }
+ }
+
+ /// <summary>
+ /// Looks up a localized string similar to The token is of bad format. It might not be created by this server..
+ /// </summary>
+ internal static string MessageTokenBadFormat {
+ get {
+ return ResourceManager.GetString("MessageTokenBadFormat", resourceCulture);
+ }
+ }
+
+ /// <summary>
+ /// Looks up a localized string similar to The token is out of date and expired. Please create a new one..
+ /// </summary>
+ internal static string MessageTokenTimeExpired {
+ get {
+ return ResourceManager.GetString("MessageTokenTimeExpired", resourceCulture);
+ }
+ }
+
+ /// <summary>
+ /// Looks up a localized string similar to A unknown error occured when verify token..
+ /// </summary>
+ internal static string MessageTokenUnknownError {
+ get {
+ return ResourceManager.GetString("MessageTokenUnknownError", resourceCulture);
+ }
+ }
+
+ /// <summary>
+ /// Looks up a localized string similar to The owner of the token does not exist. It might have been deleted..
+ /// </summary>
+ internal static string MessageTokenUserNotExist {
+ get {
+ return ResourceManager.GetString("MessageTokenUserNotExist", resourceCulture);
+ }
+ }
+
+ /// <summary>
+ /// Looks up a localized string similar to The token is of old version and expired. Please create a new one..
+ /// </summary>
+ internal static string MessageTokenVersionExpired {
+ get {
+ return ResourceManager.GetString("MessageTokenVersionExpired", resourceCulture);
+ }
+ }
}
}
diff --git a/BackEnd/Timeline/Resources/Authentication/AuthHandler.resx b/BackEnd/Timeline/Auth/Resource.resx
index 4cddc8ce..21f2b2de 100644
--- a/BackEnd/Timeline/Resources/Authentication/AuthHandler.resx
+++ b/BackEnd/Timeline/Auth/Resource.resx
@@ -127,6 +127,24 @@
<value>No jwt token is found.</value>
</data>
<data name="LogTokenValidationFail" xml:space="preserve">
- <value>A jwt token validation failed.</value>
+ <value>A jwt token validation failed. Error reason: {0}</value>
+ </data>
+ <data name="MessageNoToken" xml:space="preserve">
+ <value>You must use a token to authenticate to access this resource.</value>
+ </data>
+ <data name="MessageTokenBadFormat" xml:space="preserve">
+ <value>The token is of bad format. It might not be created by this server.</value>
+ </data>
+ <data name="MessageTokenTimeExpired" xml:space="preserve">
+ <value>The token is out of date and expired. Please create a new one.</value>
+ </data>
+ <data name="MessageTokenUnknownError" xml:space="preserve">
+ <value>A unknown error occured when verify token.</value>
+ </data>
+ <data name="MessageTokenUserNotExist" xml:space="preserve">
+ <value>The owner of the token does not exist. It might have been deleted.</value>
+ </data>
+ <data name="MessageTokenVersionExpired" xml:space="preserve">
+ <value>The token is of old version and expired. Please create a new one.</value>
</data>
</root> \ No newline at end of file
diff --git a/BackEnd/Timeline/Timeline.csproj b/BackEnd/Timeline/Timeline.csproj
index 6b565598..272c8b1e 100644
--- a/BackEnd/Timeline/Timeline.csproj
+++ b/BackEnd/Timeline/Timeline.csproj
@@ -56,10 +56,10 @@
</ItemGroup>
<ItemGroup>
- <Compile Update="Resources\Authentication\AuthHandler.Designer.cs">
- <DesignTime>True</DesignTime>
- <AutoGen>True</AutoGen>
- <DependentUpon>AuthHandler.resx</DependentUpon>
+ <Compile Update="Auth\Resource.Designer.cs">
+ <DesignTime>True</DesignTime>
+ <AutoGen>True</AutoGen>
+ <DependentUpon>Resource.resx</DependentUpon>
</Compile>
<Compile Update="Resources\Controllers\ControllerAuthExtensions.Designer.cs">
<DesignTime>True</DesignTime>
@@ -169,9 +169,9 @@
</ItemGroup>
<ItemGroup>
- <EmbeddedResource Update="Resources\Authentication\AuthHandler.resx">
- <Generator>ResXFileCodeGenerator</Generator>
- <LastGenOutput>AuthHandler.Designer.cs</LastGenOutput>
+ <EmbeddedResource Update="Auth\Resource.resx">
+ <Generator>ResXFileCodeGenerator</Generator>
+ <LastGenOutput>Resource.Designer.cs</LastGenOutput>
</EmbeddedResource>
<EmbeddedResource Update="Resources\Controllers\ControllerAuthExtensions.resx">
<Generator>ResXFileCodeGenerator</Generator>