diff options
author | crupest <crupest@outlook.com> | 2020-02-21 15:10:37 +0800 |
---|---|---|
committer | crupest <crupest@outlook.com> | 2020-02-21 15:10:37 +0800 |
commit | f389661667a510d6accfb412482578b66527e6e4 (patch) | |
tree | 57a8579bc8b6d2be2831c8e55d5b5b0f552def35 | |
parent | 3fa9899e17df4b1012e8b645915ac15022b84f9b (diff) | |
download | timeline-f389661667a510d6accfb412482578b66527e6e4.tar.gz timeline-f389661667a510d6accfb412482578b66527e6e4.tar.bz2 timeline-f389661667a510d6accfb412482578b66527e6e4.zip |
Move jwt token key from configuration to database and auto generatable.
20 files changed, 615 insertions, 27 deletions
diff --git a/Timeline.Tests/Helpers/TestApplication.cs b/Timeline.Tests/Helpers/TestApplication.cs index 5fbc2fb0..52c2f2e2 100644 --- a/Timeline.Tests/Helpers/TestApplication.cs +++ b/Timeline.Tests/Helpers/TestApplication.cs @@ -7,6 +7,7 @@ using System; using System.Collections.Generic;
using System.IO;
using Timeline.Entities;
+using Timeline.Migrations;
namespace Timeline.Tests.Helpers
{
@@ -33,6 +34,11 @@ namespace Timeline.Tests.Helpers using (var context = new DatabaseContext(options))
{
context.Database.EnsureCreated();
+ context.JwtToken.Add(new JwtTokenEntity
+ {
+ Key = JwtTokenGenerateHelper.GenerateKey()
+ });
+ context.SaveChanges();
}
Factory = factory.WithWebHostBuilder(builder =>
diff --git a/Timeline/Configs/JwtConfiguration.cs b/Timeline/Configs/JwtConfiguration.cs index fc27f4ee..af8052de 100644 --- a/Timeline/Configs/JwtConfiguration.cs +++ b/Timeline/Configs/JwtConfiguration.cs @@ -4,7 +4,6 @@ {
public string Issuer { get; set; } = default!;
public string Audience { get; set; } = default!;
- public string SigningKey { get; set; } = default!;
/// <summary>
/// Set the default value of expire offset of jwt token.
diff --git a/Timeline/Entities/DatabaseContext.cs b/Timeline/Entities/DatabaseContext.cs index 18e3e660..039cbd51 100644 --- a/Timeline/Entities/DatabaseContext.cs +++ b/Timeline/Entities/DatabaseContext.cs @@ -4,10 +4,9 @@ namespace Timeline.Entities {
public class DatabaseContext : DbContext
{
- public DatabaseContext(DbContextOptions options)
+ public DatabaseContext(DbContextOptions<DatabaseContext> options)
: base(options)
{
-
}
protected override void OnModelCreating(ModelBuilder modelBuilder)
@@ -21,5 +20,6 @@ namespace Timeline.Entities public DbSet<TimelineEntity> Timelines { get; set; } = default!;
public DbSet<TimelinePostEntity> TimelinePosts { get; set; } = default!;
public DbSet<TimelineMemberEntity> TimelineMembers { get; set; } = default!;
+ public DbSet<JwtTokenEntity> JwtToken { get; set; } = default!;
}
}
diff --git a/Timeline/Entities/JwtTokenEntity.cs b/Timeline/Entities/JwtTokenEntity.cs new file mode 100644 index 00000000..40cb230a --- /dev/null +++ b/Timeline/Entities/JwtTokenEntity.cs @@ -0,0 +1,17 @@ +using System.ComponentModel.DataAnnotations;
+using System.ComponentModel.DataAnnotations.Schema;
+
+namespace Timeline.Entities
+{
+ [Table("jwt_token")]
+ public class JwtTokenEntity
+ {
+ [Column("id"), Key, DatabaseGenerated(DatabaseGeneratedOption.Identity)]
+ public long Id { get; set; }
+
+ [Required, Column("key")]
+#pragma warning disable CA1819 // Properties should not return arrays
+ public byte[] Key { get; set; } = default!;
+#pragma warning restore CA1819 // Properties should not return arrays
+ }
+}
diff --git a/Timeline/Migrations/20200105150407_Initialize.Designer.cs b/Timeline/Migrations/20200105150407_Initialize.Designer.cs index 5594262a..ca93fcb3 100644 --- a/Timeline/Migrations/20200105150407_Initialize.Designer.cs +++ b/Timeline/Migrations/20200105150407_Initialize.Designer.cs @@ -6,7 +6,7 @@ using Microsoft.EntityFrameworkCore.Migrations; using Microsoft.EntityFrameworkCore.Storage.ValueConversion;
using Timeline.Entities;
-namespace Timeline.Migrations.DevelopmentDatabase
+namespace Timeline.Migrations
{
[DbContext(typeof(DatabaseContext))]
[Migration("20200105150407_Initialize")]
diff --git a/Timeline/Migrations/20200105150407_Initialize.cs b/Timeline/Migrations/20200105150407_Initialize.cs index c6efaa4b..2881ee64 100644 --- a/Timeline/Migrations/20200105150407_Initialize.cs +++ b/Timeline/Migrations/20200105150407_Initialize.cs @@ -1,7 +1,7 @@ using System;
using Microsoft.EntityFrameworkCore.Migrations;
-namespace Timeline.Migrations.DevelopmentDatabase
+namespace Timeline.Migrations
{
public partial class Initialize : Migration
{
diff --git a/Timeline/Migrations/20200131100517_RefactorUser.Designer.cs b/Timeline/Migrations/20200131100517_RefactorUser.Designer.cs index f494810a..fb5e8a30 100644 --- a/Timeline/Migrations/20200131100517_RefactorUser.Designer.cs +++ b/Timeline/Migrations/20200131100517_RefactorUser.Designer.cs @@ -6,7 +6,7 @@ using Microsoft.EntityFrameworkCore.Migrations; using Microsoft.EntityFrameworkCore.Storage.ValueConversion;
using Timeline.Entities;
-namespace Timeline.Migrations.DevelopmentDatabase
+namespace Timeline.Migrations
{
[DbContext(typeof(DatabaseContext))]
[Migration("20200131100517_RefactorUser")]
diff --git a/Timeline/Migrations/20200131100517_RefactorUser.cs b/Timeline/Migrations/20200131100517_RefactorUser.cs index ade65eb1..533f4bc4 100644 --- a/Timeline/Migrations/20200131100517_RefactorUser.cs +++ b/Timeline/Migrations/20200131100517_RefactorUser.cs @@ -1,6 +1,6 @@ using Microsoft.EntityFrameworkCore.Migrations;
-namespace Timeline.Migrations.DevelopmentDatabase
+namespace Timeline.Migrations
{
public partial class RefactorUser : Migration
{
diff --git a/Timeline/Migrations/20200221064341_AddJwtToken.Designer.cs b/Timeline/Migrations/20200221064341_AddJwtToken.Designer.cs new file mode 100644 index 00000000..56596249 --- /dev/null +++ b/Timeline/Migrations/20200221064341_AddJwtToken.Designer.cs @@ -0,0 +1,260 @@ +// <auto-generated />
+using System;
+using Microsoft.EntityFrameworkCore;
+using Microsoft.EntityFrameworkCore.Infrastructure;
+using Microsoft.EntityFrameworkCore.Migrations;
+using Microsoft.EntityFrameworkCore.Storage.ValueConversion;
+using Timeline.Entities;
+
+namespace Timeline.Migrations
+{
+ [DbContext(typeof(DatabaseContext))]
+ [Migration("20200221064341_AddJwtToken")]
+ partial class AddJwtToken
+ {
+ protected override void BuildTargetModel(ModelBuilder modelBuilder)
+ {
+#pragma warning disable 612, 618
+ modelBuilder
+ .HasAnnotation("ProductVersion", "3.1.2");
+
+ modelBuilder.Entity("Timeline.Entities.JwtTokenEntity", b =>
+ {
+ b.Property<long>("Id")
+ .ValueGeneratedOnAdd()
+ .HasColumnName("id")
+ .HasColumnType("INTEGER");
+
+ b.Property<byte[]>("Token")
+ .IsRequired()
+ .HasColumnName("token")
+ .HasColumnType("BLOB");
+
+ b.HasKey("Id");
+
+ b.ToTable("jwt_token");
+ });
+
+ modelBuilder.Entity("Timeline.Entities.TimelineEntity", b =>
+ {
+ b.Property<long>("Id")
+ .ValueGeneratedOnAdd()
+ .HasColumnName("id")
+ .HasColumnType("INTEGER");
+
+ b.Property<DateTime>("CreateTime")
+ .HasColumnName("create_time")
+ .HasColumnType("TEXT");
+
+ b.Property<string>("Description")
+ .HasColumnName("description")
+ .HasColumnType("TEXT");
+
+ b.Property<string>("Name")
+ .HasColumnName("name")
+ .HasColumnType("TEXT");
+
+ b.Property<long>("OwnerId")
+ .HasColumnName("owner")
+ .HasColumnType("INTEGER");
+
+ b.Property<int>("Visibility")
+ .HasColumnName("visibility")
+ .HasColumnType("INTEGER");
+
+ b.HasKey("Id");
+
+ b.HasIndex("OwnerId");
+
+ b.ToTable("timelines");
+ });
+
+ modelBuilder.Entity("Timeline.Entities.TimelineMemberEntity", b =>
+ {
+ b.Property<long>("Id")
+ .ValueGeneratedOnAdd()
+ .HasColumnName("id")
+ .HasColumnType("INTEGER");
+
+ b.Property<long>("TimelineId")
+ .HasColumnName("timeline")
+ .HasColumnType("INTEGER");
+
+ b.Property<long>("UserId")
+ .HasColumnName("user")
+ .HasColumnType("INTEGER");
+
+ b.HasKey("Id");
+
+ b.HasIndex("TimelineId");
+
+ b.HasIndex("UserId");
+
+ b.ToTable("timeline_members");
+ });
+
+ modelBuilder.Entity("Timeline.Entities.TimelinePostEntity", b =>
+ {
+ b.Property<long>("Id")
+ .ValueGeneratedOnAdd()
+ .HasColumnName("id")
+ .HasColumnType("INTEGER");
+
+ b.Property<long>("AuthorId")
+ .HasColumnName("author")
+ .HasColumnType("INTEGER");
+
+ b.Property<string>("Content")
+ .HasColumnName("content")
+ .HasColumnType("TEXT");
+
+ b.Property<DateTime>("LastUpdated")
+ .HasColumnName("last_updated")
+ .HasColumnType("TEXT");
+
+ b.Property<DateTime>("Time")
+ .HasColumnName("time")
+ .HasColumnType("TEXT");
+
+ b.Property<long>("TimelineId")
+ .HasColumnName("timeline")
+ .HasColumnType("INTEGER");
+
+ b.HasKey("Id");
+
+ b.HasIndex("AuthorId");
+
+ b.HasIndex("TimelineId");
+
+ b.ToTable("timeline_posts");
+ });
+
+ modelBuilder.Entity("Timeline.Entities.UserAvatarEntity", b =>
+ {
+ b.Property<long>("Id")
+ .ValueGeneratedOnAdd()
+ .HasColumnName("id")
+ .HasColumnType("INTEGER");
+
+ b.Property<byte[]>("Data")
+ .HasColumnName("data")
+ .HasColumnType("BLOB");
+
+ b.Property<string>("ETag")
+ .HasColumnName("etag")
+ .HasColumnType("TEXT")
+ .HasMaxLength(30);
+
+ b.Property<DateTime>("LastModified")
+ .HasColumnName("last_modified")
+ .HasColumnType("TEXT");
+
+ b.Property<string>("Type")
+ .HasColumnName("type")
+ .HasColumnType("TEXT");
+
+ b.Property<long>("UserId")
+ .HasColumnName("user")
+ .HasColumnType("INTEGER");
+
+ b.HasKey("Id");
+
+ b.HasIndex("UserId")
+ .IsUnique();
+
+ b.ToTable("user_avatars");
+ });
+
+ modelBuilder.Entity("Timeline.Entities.UserEntity", b =>
+ {
+ b.Property<long>("Id")
+ .ValueGeneratedOnAdd()
+ .HasColumnName("id")
+ .HasColumnType("INTEGER");
+
+ b.Property<string>("Nickname")
+ .HasColumnName("nickname")
+ .HasColumnType("TEXT")
+ .HasMaxLength(100);
+
+ b.Property<string>("Password")
+ .IsRequired()
+ .HasColumnName("password")
+ .HasColumnType("TEXT");
+
+ b.Property<string>("Roles")
+ .IsRequired()
+ .HasColumnName("roles")
+ .HasColumnType("TEXT");
+
+ b.Property<string>("Username")
+ .IsRequired()
+ .HasColumnName("username")
+ .HasColumnType("TEXT")
+ .HasMaxLength(26);
+
+ b.Property<long>("Version")
+ .ValueGeneratedOnAdd()
+ .HasColumnName("version")
+ .HasColumnType("INTEGER")
+ .HasDefaultValue(0L);
+
+ b.HasKey("Id");
+
+ b.HasIndex("Username")
+ .IsUnique();
+
+ b.ToTable("users");
+ });
+
+ modelBuilder.Entity("Timeline.Entities.TimelineEntity", b =>
+ {
+ b.HasOne("Timeline.Entities.UserEntity", "Owner")
+ .WithMany("Timelines")
+ .HasForeignKey("OwnerId")
+ .OnDelete(DeleteBehavior.Cascade)
+ .IsRequired();
+ });
+
+ modelBuilder.Entity("Timeline.Entities.TimelineMemberEntity", b =>
+ {
+ b.HasOne("Timeline.Entities.TimelineEntity", "Timeline")
+ .WithMany("Members")
+ .HasForeignKey("TimelineId")
+ .OnDelete(DeleteBehavior.Cascade)
+ .IsRequired();
+
+ b.HasOne("Timeline.Entities.UserEntity", "User")
+ .WithMany("TimelinesJoined")
+ .HasForeignKey("UserId")
+ .OnDelete(DeleteBehavior.Cascade)
+ .IsRequired();
+ });
+
+ modelBuilder.Entity("Timeline.Entities.TimelinePostEntity", b =>
+ {
+ b.HasOne("Timeline.Entities.UserEntity", "Author")
+ .WithMany("TimelinePosts")
+ .HasForeignKey("AuthorId")
+ .OnDelete(DeleteBehavior.Cascade)
+ .IsRequired();
+
+ b.HasOne("Timeline.Entities.TimelineEntity", "Timeline")
+ .WithMany("Posts")
+ .HasForeignKey("TimelineId")
+ .OnDelete(DeleteBehavior.Cascade)
+ .IsRequired();
+ });
+
+ modelBuilder.Entity("Timeline.Entities.UserAvatarEntity", b =>
+ {
+ b.HasOne("Timeline.Entities.UserEntity", "User")
+ .WithOne("Avatar")
+ .HasForeignKey("Timeline.Entities.UserAvatarEntity", "UserId")
+ .OnDelete(DeleteBehavior.Cascade)
+ .IsRequired();
+ });
+#pragma warning restore 612, 618
+ }
+ }
+}
diff --git a/Timeline/Migrations/20200221064341_AddJwtToken.cs b/Timeline/Migrations/20200221064341_AddJwtToken.cs new file mode 100644 index 00000000..628970c6 --- /dev/null +++ b/Timeline/Migrations/20200221064341_AddJwtToken.cs @@ -0,0 +1,45 @@ +using System;
+using System.Security.Cryptography;
+using Microsoft.EntityFrameworkCore.Migrations;
+
+namespace Timeline.Migrations
+{
+ public static class JwtTokenGenerateHelper
+ {
+ public static byte[] GenerateKey()
+ {
+ using var random = RandomNumberGenerator.Create();
+ var key = new byte[16];
+ random.GetBytes(key);
+ return key;
+ }
+ }
+
+ public partial class AddJwtToken : Migration
+ {
+ protected override void Up(MigrationBuilder migrationBuilder)
+ {
+ migrationBuilder.CreateTable(
+ name: "jwt_token",
+ columns: table => new
+ {
+ id = table.Column<long>(nullable: false)
+ .Annotation("Sqlite:Autoincrement", true),
+ key = table.Column<byte[]>(nullable: false)
+ },
+ constraints: table =>
+ {
+ table.PrimaryKey("PK_jwt_token", x => x.id);
+ });
+
+
+ migrationBuilder.InsertData("jwt_token", "key", JwtTokenGenerateHelper.GenerateKey());
+ }
+
+ protected override void Down(MigrationBuilder migrationBuilder)
+ {
+ migrationBuilder.DropTable(
+ name: "jwt_token");
+ }
+ }
+}
diff --git a/Timeline/Migrations/DatabaseContextModelSnapshot.cs b/Timeline/Migrations/DatabaseContextModelSnapshot.cs index e635a1b1..d5f9c0e4 100644 --- a/Timeline/Migrations/DatabaseContextModelSnapshot.cs +++ b/Timeline/Migrations/DatabaseContextModelSnapshot.cs @@ -5,7 +5,7 @@ using Microsoft.EntityFrameworkCore.Infrastructure; using Microsoft.EntityFrameworkCore.Storage.ValueConversion;
using Timeline.Entities;
-namespace Timeline.Migrations.DevelopmentDatabase
+namespace Timeline.Migrations
{
[DbContext(typeof(DatabaseContext))]
partial class DatabaseContextModelSnapshot : ModelSnapshot
@@ -14,7 +14,24 @@ namespace Timeline.Migrations.DevelopmentDatabase {
#pragma warning disable 612, 618
modelBuilder
- .HasAnnotation("ProductVersion", "3.1.1");
+ .HasAnnotation("ProductVersion", "3.1.2");
+
+ modelBuilder.Entity("Timeline.Entities.JwtTokenEntity", b =>
+ {
+ b.Property<long>("Id")
+ .ValueGeneratedOnAdd()
+ .HasColumnName("id")
+ .HasColumnType("INTEGER");
+
+ b.Property<byte[]>("Token")
+ .IsRequired()
+ .HasColumnName("token")
+ .HasColumnType("BLOB");
+
+ b.HasKey("Id");
+
+ b.ToTable("jwt_token");
+ });
modelBuilder.Entity("Timeline.Entities.TimelineEntity", b =>
{
diff --git a/Timeline/Program.cs b/Timeline/Program.cs index 1a7a723a..125fccbc 100644 --- a/Timeline/Program.cs +++ b/Timeline/Program.cs @@ -13,10 +13,6 @@ namespace Timeline public static void Main(string[] args)
{
CreateWebHostBuilder(args)
- .ConfigureAppConfiguration((context, config) =>
- {
- config.AddEnvironmentVariables("TIMELINE_");
- })
.Build().Run();
}
diff --git a/Timeline/Properties/launchSettings.json b/Timeline/Properties/launchSettings.json index 3819fe0f..4bae443c 100644 --- a/Timeline/Properties/launchSettings.json +++ b/Timeline/Properties/launchSettings.json @@ -4,7 +4,7 @@ "commandName": "Project", "environmentVariables": { "ASPNETCORE_ENVIRONMENT": "Development", - "TIMELINE_WORKDIR": "D:\\timeline-development" + "ASPNETCORE_WORKDIR": "D:\\timeline-development" } } } diff --git a/Timeline/Resources/Services/UserTokenService.Designer.cs b/Timeline/Resources/Services/UserTokenService.Designer.cs new file mode 100644 index 00000000..3c3c7e41 --- /dev/null +++ b/Timeline/Resources/Services/UserTokenService.Designer.cs @@ -0,0 +1,72 @@ +//------------------------------------------------------------------------------
+// <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.Resources.Services {
+ 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 UserTokenService {
+
+ private static global::System.Resources.ResourceManager resourceMan;
+
+ private static global::System.Globalization.CultureInfo resourceCulture;
+
+ [global::System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")]
+ internal UserTokenService() {
+ }
+
+ /// <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.Resources.Services.UserTokenService", typeof(UserTokenService).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 Jwt token key is not set in database. Maybe you forget to migrate the database..
+ /// </summary>
+ internal static string JwtKeyNotExist {
+ get {
+ return ResourceManager.GetString("JwtKeyNotExist", resourceCulture);
+ }
+ }
+ }
+}
diff --git a/Timeline/Resources/Services/UserTokenService.resx b/Timeline/Resources/Services/UserTokenService.resx new file mode 100644 index 00000000..1ce78427 --- /dev/null +++ b/Timeline/Resources/Services/UserTokenService.resx @@ -0,0 +1,123 @@ +<?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="JwtKeyNotExist" xml:space="preserve">
+ <value>Jwt token key is not set in database. Maybe you forget to migrate the database.</value>
+ </data>
+</root>
\ No newline at end of file diff --git a/Timeline/Services/PathProvider.cs b/Timeline/Services/PathProvider.cs new file mode 100644 index 00000000..15e66972 --- /dev/null +++ b/Timeline/Services/PathProvider.cs @@ -0,0 +1,41 @@ +using Microsoft.Extensions.Configuration;
+using System;
+using System.Collections.Generic;
+using System.IO;
+using System.Linq;
+using System.Threading.Tasks;
+
+namespace Timeline.Services
+{
+ public interface IPathProvider
+ {
+ public string GetWorkingDirectory();
+ public string GetDatabaseFilePath();
+ }
+
+ public class PathProvider : IPathProvider
+ {
+ const string DatabaseFileName = "timeline.db";
+
+ private readonly IConfiguration _configuration;
+
+ private readonly string _workingDirectory;
+
+
+ public PathProvider(IConfiguration configuration)
+ {
+ _configuration = configuration;
+ _workingDirectory = configuration.GetValue<string>("WorkDir");
+ }
+
+ public string GetWorkingDirectory()
+ {
+ return _workingDirectory;
+ }
+
+ public string GetDatabaseFilePath()
+ {
+ return Path.Combine(_workingDirectory, DatabaseFileName);
+ }
+ }
+}
diff --git a/Timeline/Services/UserTokenService.cs b/Timeline/Services/UserTokenService.cs index 731eb1db..86f3a0f7 100644 --- a/Timeline/Services/UserTokenService.cs +++ b/Timeline/Services/UserTokenService.cs @@ -3,9 +3,10 @@ using Microsoft.IdentityModel.Tokens; using System;
using System.Globalization;
using System.IdentityModel.Tokens.Jwt;
+using System.Linq;
using System.Security.Claims;
-using System.Text;
using Timeline.Configs;
+using Timeline.Entities;
namespace Timeline.Services
{
@@ -49,16 +50,19 @@ namespace Timeline.Services private readonly JwtSecurityTokenHandler _tokenHandler = new JwtSecurityTokenHandler();
private SymmetricSecurityKey _tokenSecurityKey;
- public JwtUserTokenService(IOptionsMonitor<JwtConfiguration> jwtConfig, IClock clock)
+ public JwtUserTokenService(IOptionsMonitor<JwtConfiguration> jwtConfig, IClock clock, DatabaseContext database)
{
_jwtConfig = jwtConfig;
_clock = clock;
- _tokenSecurityKey = new SymmetricSecurityKey(Encoding.ASCII.GetBytes(jwtConfig.CurrentValue.SigningKey));
- jwtConfig.OnChange(config =>
+ var key = database.JwtToken.Select(t => t.Key).SingleOrDefault();
+
+ if (key == null)
{
- _tokenSecurityKey = new SymmetricSecurityKey(Encoding.ASCII.GetBytes(config.SigningKey));
- });
+ throw new InvalidOperationException(Resources.Services.UserTokenService.JwtKeyNotExist);
+ }
+
+ _tokenSecurityKey = new SymmetricSecurityKey(key);
}
public string GenerateToken(UserTokenInfo tokenInfo)
@@ -77,8 +81,7 @@ namespace Timeline.Services Subject = identity,
Issuer = config.Issuer,
Audience = config.Audience,
- SigningCredentials = new SigningCredentials(
- new SymmetricSecurityKey(Encoding.ASCII.GetBytes(config.SigningKey)), SecurityAlgorithms.HmacSha384),
+ SigningCredentials = new SigningCredentials(_tokenSecurityKey, SecurityAlgorithms.HmacSha384),
IssuedAt = _clock.GetCurrentTime(),
Expires = tokenInfo.ExpireAt.GetValueOrDefault(_clock.GetCurrentTime().AddSeconds(config.DefaultExpireOffset)),
NotBefore = _clock.GetCurrentTime() // I must explicitly set this or it will use the current time by default and mock is not work in which case test will not pass.
diff --git a/Timeline/Startup.cs b/Timeline/Startup.cs index f305c39d..14bd14cc 100644 --- a/Timeline/Startup.cs +++ b/Timeline/Startup.cs @@ -9,7 +9,6 @@ using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.DependencyInjection.Extensions;
using Microsoft.Extensions.Hosting;
using System;
-using System.IO;
using System.Text.Json.Serialization;
using Timeline.Auth;
using Timeline.Configs;
@@ -84,6 +83,8 @@ namespace Timeline });
}
+ services.AddScoped<IPathProvider, PathProvider>();
+
services.AddAutoMapper(GetType().Assembly);
services.AddTransient<IClock, Clock>();
@@ -99,10 +100,10 @@ namespace Timeline services.TryAddSingleton<IActionContextAccessor, ActionContextAccessor>();
- var dbConnectionString = $"Data Source={Path.Combine(workDir, "timeline.db")}";
- services.AddDbContext<DatabaseContext>(options =>
+ services.AddDbContext<DatabaseContext>((services, options )=>
{
- options.UseSqlite(dbConnectionString);
+ var pathProvider = services.GetRequiredService<IPathProvider>();
+ options.UseSqlite($"Data Source={pathProvider.GetDatabaseFilePath()}");
});
}
diff --git a/Timeline/Timeline.csproj b/Timeline/Timeline.csproj index e82e80f9..2dcc3c9f 100644 --- a/Timeline/Timeline.csproj +++ b/Timeline/Timeline.csproj @@ -117,6 +117,11 @@ <AutoGen>True</AutoGen>
<DependentUpon>UserService.resx</DependentUpon>
</Compile>
+ <Compile Update="Resources\Services\UserTokenService.Designer.cs">
+ <DesignTime>True</DesignTime>
+ <AutoGen>True</AutoGen>
+ <DependentUpon>UserTokenService.resx</DependentUpon>
+ </Compile>
</ItemGroup>
<ItemGroup>
@@ -185,5 +190,9 @@ <Generator>ResXFileCodeGenerator</Generator>
<LastGenOutput>UserService.Designer.cs</LastGenOutput>
</EmbeddedResource>
+ <EmbeddedResource Update="Resources\Services\UserTokenService.resx">
+ <Generator>ResXFileCodeGenerator</Generator>
+ <LastGenOutput>UserTokenService.Designer.cs</LastGenOutput>
+ </EmbeddedResource>
</ItemGroup>
</Project>
diff --git a/Timeline/appsettings.json b/Timeline/appsettings.json index d55d0597..09840cd6 100644 --- a/Timeline/appsettings.json +++ b/Timeline/appsettings.json @@ -7,7 +7,6 @@ "Jwt": {
"Issuer": "api.crupest.xyz",
"Audience": "api.crupest.xyz",
- "SigningKey": "this is very very very very very long secret"
},
"Cors": [ "https://www.crupest.xyz", "https://crupest.xyz" ]
}
|