aboutsummaryrefslogtreecommitdiff
path: root/BackEnd/Timeline/Auth
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/Timeline/Auth
parent9deda660ef57d2687d5e44597c4ba5de46ed4097 (diff)
downloadtimeline-9adfa3c8311f4ace9388dc805f1a4df6fba97f0e.tar.gz
timeline-9adfa3c8311f4ace9388dc805f1a4df6fba97f0e.tar.bz2
timeline-9adfa3c8311f4ace9388dc805f1a4df6fba97f0e.zip
refactor: Refactor auth handler messages.
Diffstat (limited to 'BackEnd/Timeline/Auth')
-rw-r--r--BackEnd/Timeline/Auth/MyAuthenticationHandler.cs55
-rw-r--r--BackEnd/Timeline/Auth/Resource.Designer.cs153
-rw-r--r--BackEnd/Timeline/Auth/Resource.resx150
3 files changed, 333 insertions, 25 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/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 @@
+//------------------------------------------------------------------------------
+// <auto-generated>
+// 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.
+// </auto-generated>
+//------------------------------------------------------------------------------
+
+namespace Timeline.Auth {
+ using System;
+
+
+ /// <summary>
+ /// A strongly-typed resource class, for looking up localized strings, etc.
+ /// </summary>
+ // 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() {
+ }
+
+ /// <summary>
+ /// Returns the cached ResourceManager instance used by this class.
+ /// </summary>
+ [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;
+ }
+ }
+
+ /// <summary>
+ /// Overrides the current thread's CurrentUICulture property for all
+ /// resource lookups using this strongly typed resource class.
+ /// </summary>
+ [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)]
+ internal static global::System.Globalization.CultureInfo Culture {
+ get {
+ return resourceCulture;
+ }
+ set {
+ resourceCulture = value;
+ }
+ }
+
+ /// <summary>
+ /// Looks up a localized string similar to Token is found in authorization header. Token is {0} ..
+ /// </summary>
+ internal static string LogTokenFoundInHeader {
+ get {
+ return ResourceManager.GetString("LogTokenFoundInHeader", resourceCulture);
+ }
+ }
+
+ /// <summary>
+ /// Looks up a localized string similar to Token is found in query param with key &quot;{0}&quot;. Token is {1} ..
+ /// </summary>
+ internal static string LogTokenFoundInQuery {
+ get {
+ return ResourceManager.GetString("LogTokenFoundInQuery", resourceCulture);
+ }
+ }
+
+ /// <summary>
+ /// Looks up a localized string similar to No jwt token is found..
+ /// </summary>
+ internal static string LogTokenNotFound {
+ get {
+ return ResourceManager.GetString("LogTokenNotFound", resourceCulture);
+ }
+ }
+
+ /// <summary>
+ /// 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/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 @@
+<?xml version="1.0" encoding="utf-8"?>
+<root>
+ <!--
+ Microsoft ResX Schema
+
+ Version 2.0
+
+ The primary goals of this format is to allow a simple XML format
+ that is mostly human readable. The generation and parsing of the
+ various data types are done through the TypeConverter classes
+ associated with the data types.
+
+ Example:
+
+ ... ado.net/XML headers & schema ...
+ <resheader name="resmimetype">text/microsoft-resx</resheader>
+ <resheader name="version">2.0</resheader>
+ <resheader name="reader">System.Resources.ResXResourceReader, System.Windows.Forms, ...</resheader>
+ <resheader name="writer">System.Resources.ResXResourceWriter, System.Windows.Forms, ...</resheader>
+ <data name="Name1"><value>this is my long string</value><comment>this is a comment</comment></data>
+ <data name="Color1" type="System.Drawing.Color, System.Drawing">Blue</data>
+ <data name="Bitmap1" mimetype="application/x-microsoft.net.object.binary.base64">
+ <value>[base64 mime encoded serialized .NET Framework object]</value>
+ </data>
+ <data name="Icon1" type="System.Drawing.Icon, System.Drawing" mimetype="application/x-microsoft.net.object.bytearray.base64">
+ <value>[base64 mime encoded string representing a byte array form of the .NET Framework object]</value>
+ <comment>This is a comment</comment>
+ </data>
+
+ There are any number of "resheader" rows that contain simple
+ name/value pairs.
+
+ Each data row contains a name, and value. The row also contains a
+ type or mimetype. Type corresponds to a .NET class that support
+ text/value conversion through the TypeConverter architecture.
+ Classes that don't support this are serialized and stored with the
+ mimetype set.
+
+ The mimetype is used for serialized objects, and tells the
+ ResXResourceReader how to depersist the object. This is currently not
+ extensible. For a given mimetype the value must be set accordingly:
+
+ Note - application/x-microsoft.net.object.binary.base64 is the format
+ that the ResXResourceWriter will generate, however the reader can
+ read any of the formats listed below.
+
+ mimetype: application/x-microsoft.net.object.binary.base64
+ value : The object must be serialized with
+ : System.Runtime.Serialization.Formatters.Binary.BinaryFormatter
+ : and then encoded with base64 encoding.
+
+ mimetype: application/x-microsoft.net.object.soap.base64
+ value : The object must be serialized with
+ : System.Runtime.Serialization.Formatters.Soap.SoapFormatter
+ : and then encoded with base64 encoding.
+
+ mimetype: application/x-microsoft.net.object.bytearray.base64
+ value : The object must be serialized into a byte array
+ : using a System.ComponentModel.TypeConverter
+ : and then encoded with base64 encoding.
+ -->
+ <xsd:schema id="root" xmlns="" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:msdata="urn:schemas-microsoft-com:xml-msdata">
+ <xsd:import namespace="http://www.w3.org/XML/1998/namespace" />
+ <xsd:element name="root" msdata:IsDataSet="true">
+ <xsd:complexType>
+ <xsd:choice maxOccurs="unbounded">
+ <xsd:element name="metadata">
+ <xsd:complexType>
+ <xsd:sequence>
+ <xsd:element name="value" type="xsd:string" minOccurs="0" />
+ </xsd:sequence>
+ <xsd:attribute name="name" use="required" type="xsd:string" />
+ <xsd:attribute name="type" type="xsd:string" />
+ <xsd:attribute name="mimetype" type="xsd:string" />
+ <xsd:attribute ref="xml:space" />
+ </xsd:complexType>
+ </xsd:element>
+ <xsd:element name="assembly">
+ <xsd:complexType>
+ <xsd:attribute name="alias" type="xsd:string" />
+ <xsd:attribute name="name" type="xsd:string" />
+ </xsd:complexType>
+ </xsd:element>
+ <xsd:element name="data">
+ <xsd:complexType>
+ <xsd:sequence>
+ <xsd:element name="value" type="xsd:string" minOccurs="0" msdata:Ordinal="1" />
+ <xsd:element name="comment" type="xsd:string" minOccurs="0" msdata:Ordinal="2" />
+ </xsd:sequence>
+ <xsd:attribute name="name" type="xsd:string" use="required" msdata:Ordinal="1" />
+ <xsd:attribute name="type" type="xsd:string" msdata:Ordinal="3" />
+ <xsd:attribute name="mimetype" type="xsd:string" msdata:Ordinal="4" />
+ <xsd:attribute ref="xml:space" />
+ </xsd:complexType>
+ </xsd:element>
+ <xsd:element name="resheader">
+ <xsd:complexType>
+ <xsd:sequence>
+ <xsd:element name="value" type="xsd:string" minOccurs="0" msdata:Ordinal="1" />
+ </xsd:sequence>
+ <xsd:attribute name="name" type="xsd:string" use="required" />
+ </xsd:complexType>
+ </xsd:element>
+ </xsd:choice>
+ </xsd:complexType>
+ </xsd:element>
+ </xsd:schema>
+ <resheader name="resmimetype">
+ <value>text/microsoft-resx</value>
+ </resheader>
+ <resheader name="version">
+ <value>2.0</value>
+ </resheader>
+ <resheader name="reader">
+ <value>System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
+ </resheader>
+ <resheader name="writer">
+ <value>System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
+ </resheader>
+ <data name="LogTokenFoundInHeader" xml:space="preserve">
+ <value>Token is found in authorization header. Token is {0} .</value>
+ </data>
+ <data name="LogTokenFoundInQuery" xml:space="preserve">
+ <value>Token is found in query param with key "{0}". Token is {1} .</value>
+ </data>
+ <data name="LogTokenNotFound" xml:space="preserve">
+ <value>No jwt token is found.</value>
+ </data>
+ <data name="LogTokenValidationFail" xml:space="preserve">
+ <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