Fix Key Generation

This commit is contained in:
hydrant
2019-09-22 16:53:38 +02:00
parent b9c0db505c
commit f99178bf25
3 changed files with 29 additions and 22 deletions

View File

@@ -5,6 +5,7 @@ using System.Linq;
using System.Security.Claims; using System.Security.Claims;
using System.Text; using System.Text;
using System.Threading.Tasks; using System.Threading.Tasks;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options; using Microsoft.Extensions.Options;
using Microsoft.IdentityModel.Tokens; using Microsoft.IdentityModel.Tokens;
using ReallifeGamemode.Database; using ReallifeGamemode.Database;
@@ -15,11 +16,13 @@ namespace ReallifeGamemode.DataService.Logic
{ {
public class JwtTokenGenerator : LogicBase public class JwtTokenGenerator : LogicBase
{ {
private ServerConfig config; private readonly ILogger<JwtTokenGenerator> logger;
private readonly ServerConfig config;
public JwtTokenGenerator(IOptions<ServerConfig> config, DatabaseContext dbContext) : base(dbContext) public JwtTokenGenerator(IOptions<ServerConfig> config, DatabaseContext dbContext, ILogger<JwtTokenGenerator> logger) : base(dbContext)
{ {
this.config = config.Value; this.config = config.Value;
this.logger = logger;
} }
public string GenerateUserToken(User user) public string GenerateUserToken(User user)
@@ -40,10 +43,9 @@ namespace ReallifeGamemode.DataService.Logic
new Claim(ClaimTypes.Name, user.Id.ToString()), new Claim(ClaimTypes.Name, user.Id.ToString()),
new Claim(ClaimTypes.Role, user.AdminLevel.ToString()) new Claim(ClaimTypes.Role, user.AdminLevel.ToString())
}), }),
Expires = DateTime.Now.AddDays(1), Expires = DateTime.UtcNow.AddDays(1),
IssuedAt = DateTime.Now, IssuedAt = DateTime.UtcNow,
SigningCredentials = new SigningCredentials(new SymmetricSecurityKey(key), SecurityAlgorithms.HmacSha256Signature), SigningCredentials = new SigningCredentials(new SymmetricSecurityKey(key), SecurityAlgorithms.HmacSha256Signature),
Issuer = "LOGDATASERVICE"
}; };
var token = tokenHandler.WriteToken(tokenHandler.CreateToken(tokenDescriptor)); var token = tokenHandler.WriteToken(tokenHandler.CreateToken(tokenDescriptor));
@@ -62,10 +64,9 @@ namespace ReallifeGamemode.DataService.Logic
new Claim(ClaimTypes.Name, 1.ToString()), new Claim(ClaimTypes.Name, 1.ToString()),
new Claim(ClaimTypes.Role, (AdminLevel.PROJEKTLEITUNG).ToString()) new Claim(ClaimTypes.Role, (AdminLevel.PROJEKTLEITUNG).ToString())
}), }),
Expires = DateTime.Now.AddDays(1), Expires = DateTime.UtcNow.AddDays(1),
IssuedAt = DateTime.Now, IssuedAt = DateTime.UtcNow,
SigningCredentials = new SigningCredentials(new SymmetricSecurityKey(key), SecurityAlgorithms.HmacSha256Signature), SigningCredentials = new SigningCredentials(new SymmetricSecurityKey(key), SecurityAlgorithms.HmacSha256Signature)
Issuer = "LOGDATASERVICE"
}; };
var token = tokenHandler.WriteToken(tokenHandler.CreateToken(tokenDescriptor)); var token = tokenHandler.WriteToken(tokenHandler.CreateToken(tokenDescriptor));

View File

@@ -12,6 +12,7 @@ using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging; using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options; using Microsoft.Extensions.Options;
using Microsoft.IdentityModel.Logging;
using Microsoft.IdentityModel.Tokens; using Microsoft.IdentityModel.Tokens;
using Microsoft.OpenApi.Models; using Microsoft.OpenApi.Models;
using ReallifeGamemode.Database.Models; using ReallifeGamemode.Database.Models;
@@ -23,17 +24,21 @@ namespace ReallifeGamemode.DataService
{ {
public class Startup public class Startup
{ {
public Startup(IConfiguration configuration) private readonly ILogger<Startup> logger;
{ private readonly IConfiguration configuration;
Configuration = configuration; private readonly IHostingEnvironment environment;
}
public IConfiguration Configuration { get; } public Startup(IConfiguration configuration, IHostingEnvironment environment, ILogger<Startup> logger)
{
this.configuration = configuration;
this.environment = environment;
this.logger = logger;
}
// This method gets called by the runtime. Use this method to add services to the container. // This method gets called by the runtime. Use this method to add services to the container.
public void ConfigureServices(IServiceCollection services) public void ConfigureServices(IServiceCollection services)
{ {
services.Configure<ServerConfig>(cfg => Configuration.Bind(cfg)); services.Configure<ServerConfig>(cfg => configuration.Bind(cfg));
services.AddDbContext<DatabaseContext>(); services.AddDbContext<DatabaseContext>();
@@ -48,7 +53,7 @@ namespace ReallifeGamemode.DataService
j.SerializerSettings.DateFormatHandling = Newtonsoft.Json.DateFormatHandling.IsoDateFormat; j.SerializerSettings.DateFormatHandling = Newtonsoft.Json.DateFormatHandling.IsoDateFormat;
}); });
var tokenKey = Encoding.UTF8.GetBytes(Configuration["TokenSecret"]); var tokenKey = Encoding.ASCII.GetBytes(configuration["TokenSecret"]);
services.AddAuthentication(o => services.AddAuthentication(o =>
{ {
o.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme; o.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
@@ -56,7 +61,8 @@ namespace ReallifeGamemode.DataService
}) })
.AddJwtBearer(o => .AddJwtBearer(o =>
{ {
o.RequireHttpsMetadata = true; o.IncludeErrorDetails = true;
o.RequireHttpsMetadata = this.environment.IsProduction();
o.SaveToken = false; o.SaveToken = false;
o.TokenValidationParameters = new TokenValidationParameters o.TokenValidationParameters = new TokenValidationParameters
{ {

View File

@@ -6,16 +6,16 @@
<appendToFile value="true" /> <appendToFile value="true" />
<maximumFileSize value="32MB" /> <maximumFileSize value="32MB" />
<maxSizeRollBackups value="2" /> <maxSizeRollBackups value="2" />
<threshold value="All" /> <threshold value="Debug" />
<layout type="log4net.Layout.PatternLayout"> <layout type="log4net.Layout.PatternLayout">
<conversionPattern value="%date %-5level %logger [%property{NDC}] - %message%newline" /> <conversionPattern value="%date %-5level %logger - %message%newline" />
</layout> </layout>
</appender> </appender>
<appender name="ErrorRollingFile" type="log4net.Appender.RollingFileAppender"> <appender name="ErrorRollingFile" type="log4net.Appender.RollingFileAppender">
<file value="log\" /> <file value="log\" />
<datePattern value="dd-MM-yyyy'.log'" /> <datePattern value="dd-MM-yyyy'.err'" />
<staticLogFileName value="false" /> <staticLogFileName value="false" />
<appendToFile value="true" /> <appendToFile value="true" />
<maximumFileSize value="32MB" /> <maximumFileSize value="32MB" />
@@ -23,12 +23,12 @@
<threshold value="Warn" /> <threshold value="Warn" />
<layout type="log4net.Layout.PatternLayout"> <layout type="log4net.Layout.PatternLayout">
<conversionPattern value="%date %-5level %logger [%property{NDC}] - %message%newline" /> <conversionPattern value="%date %-5level %logger - %message%newline" />
</layout> </layout>
</appender> </appender>
<root> <root>
<level value="ALL" /> <level value="Debug" />
<appender-ref ref="AllRollingFile" /> <appender-ref ref="AllRollingFile" />
<appender-ref ref="ErrorRollingFile" /> <appender-ref ref="ErrorRollingFile" />
</root> </root>