Compare commits

..

No commits in common. '152c7b148c64e36e40a6ffb8e202245046784a9e' and 'e157e8b120d770a57e6b67de371a3448677e0bec' have entirely different histories.

@ -79,7 +79,7 @@ public class LoginController : ControllerBase
if (result.Succeeded) if (result.Succeeded)
{ {
return Redirect(returnUrl ?? "/"); return Redirect(returnUrl ?? "");
} }
if (result.IsLockedOut) if (result.IsLockedOut)

@ -1,24 +0,0 @@
using Microsoft.AspNetCore.Mvc;
using OAuthServer.Services;
namespace OAuthServer.Controllers;
[ApiController]
public class OAuthController : ControllerBase
{
private readonly ILogger<OAuthController> _logger;
private readonly JwtService _jwt;
public OAuthController(ILogger<OAuthController> logger, JwtService jwt)
{
_logger = logger;
_jwt = jwt;
}
[HttpPost]
[Route("get-token")]
public ActionResult GenerateToken()
{
return Ok(_jwt.GenerateToken());
}
}

@ -1,4 +1,4 @@
<Project Sdk="Microsoft.NET.Sdk.Web"> <Project Sdk="Microsoft.NET.Sdk.Web">
<PropertyGroup> <PropertyGroup>
<TargetFramework>net8.0</TargetFramework> <TargetFramework>net8.0</TargetFramework>
@ -6,20 +6,19 @@
<ImplicitUsings>enable</ImplicitUsings> <ImplicitUsings>enable</ImplicitUsings>
<InvariantGlobalization>true</InvariantGlobalization> <InvariantGlobalization>true</InvariantGlobalization>
<DockerDefaultTargetOS>Linux</DockerDefaultTargetOS> <DockerDefaultTargetOS>Linux</DockerDefaultTargetOS>
<UserSecretsId>01456bf0-f709-42b0-ad41-af6d7b94cab7</UserSecretsId>
</PropertyGroup> </PropertyGroup>
<ItemGroup> <ItemGroup>
<PackageReference Include="Microsoft.AspNetCore.Authentication.JwtBearer" Version="8.0.2" /> <PackageReference Include="Microsoft.AspNetCore.Authentication.JwtBearer" Version="8.0.2" />
<PackageReference Include="Microsoft.AspNetCore.Identity.EntityFrameworkCore" Version="8.0.2" /> <PackageReference Include="Microsoft.AspNetCore.Identity.EntityFrameworkCore" Version="8.0.2" />
<PackageReference Include="Microsoft.AspNetCore.OpenApi" Version="8.0.1" /> <PackageReference Include="Microsoft.AspNetCore.OpenApi" Version="8.0.1"/>
<PackageReference Include="Microsoft.EntityFrameworkCore" Version="8.0.2" /> <PackageReference Include="Microsoft.EntityFrameworkCore" Version="8.0.2" />
<PackageReference Include="Microsoft.EntityFrameworkCore.Design" Version="8.0.2"> <PackageReference Include="Microsoft.EntityFrameworkCore.Design" Version="8.0.2">
<PrivateAssets>all</PrivateAssets> <PrivateAssets>all</PrivateAssets>
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets> <IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
</PackageReference> </PackageReference>
<PackageReference Include="Microsoft.EntityFrameworkCore.Sqlite" Version="8.0.2" /> <PackageReference Include="Microsoft.EntityFrameworkCore.Sqlite" Version="8.0.2" />
<PackageReference Include="Swashbuckle.AspNetCore" Version="6.4.0" /> <PackageReference Include="Swashbuckle.AspNetCore" Version="6.4.0"/>
</ItemGroup> </ItemGroup>
<ItemGroup> <ItemGroup>

@ -1,13 +1,11 @@
using System.Security.Cryptography; using Microsoft.AspNetCore.Authentication.JwtBearer;
using Microsoft.AspNetCore.DataProtection; using Microsoft.AspNetCore.DataProtection;
using Microsoft.AspNetCore.DataProtection.AuthenticatedEncryption; using Microsoft.AspNetCore.DataProtection.AuthenticatedEncryption;
using Microsoft.AspNetCore.DataProtection.AuthenticatedEncryption.ConfigurationModel; using Microsoft.AspNetCore.DataProtection.AuthenticatedEncryption.ConfigurationModel;
using Microsoft.AspNetCore.Identity; using Microsoft.AspNetCore.Identity;
using Microsoft.EntityFrameworkCore; using Microsoft.EntityFrameworkCore;
using Microsoft.IdentityModel.Tokens;
using Microsoft.OpenApi.Models; using Microsoft.OpenApi.Models;
using OAuthServer; using OAuthServer;
using OAuthServer.Services;
var builder = WebApplication.CreateBuilder(args); var builder = WebApplication.CreateBuilder(args);
@ -33,20 +31,6 @@ builder.Services.AddSwaggerGen(options =>
Id = "Bearer" Id = "Bearer"
} }
}); });
options.AddSecurityRequirement(new OpenApiSecurityRequirement
{
{
new OpenApiSecurityScheme
{
Reference = new OpenApiReference
{
Type = ReferenceType.SecurityScheme,
Id = "Bearer"
}
},
new string[] { }
}
});
}); });
builder.Services.AddDbContext<AppDbContext>(options => { options.UseSqlite("DataSource=db.sqlite3"); }); builder.Services.AddDbContext<AppDbContext>(options => { options.UseSqlite("DataSource=db.sqlite3"); });
@ -55,24 +39,24 @@ builder.Services.AddIdentity<IdentityUser, IdentityRole>(options => { options.St
.AddEntityFrameworkStores<AppDbContext>() .AddEntityFrameworkStores<AppDbContext>()
.AddDefaultTokenProviders(); .AddDefaultTokenProviders();
// Load the signing key from a file if it exists or create a new one
var rsaKey = JwtService.GetSigningKey();
// Add the JWT authentication method
builder.Services.AddAuthentication().AddJwtBearer("OAuthToken", options => builder.Services.AddAuthentication().AddJwtBearer("OAuthToken", options =>
{ {
options.SaveToken = false; // options.RequireHttpsMetadata = false;
options.TokenValidationParameters = new TokenValidationParameters() // options.SaveToken = true;
{ // options.TokenValidationParameters = new TokenValidationParameters()
ValidateIssuer = false, // {
ValidateAudience = false, // ValidateIssuer = true,
RequireSignedTokens = true, // ValidateAudience = true,
IssuerSigningKey = new RsaSecurityKey(rsaKey) // RequireSignedTokens = true,
}; // ValidIssuer = builder.Configuration["Jwt:Issuer"],
// ValidAudience = builder.Configuration["Jwt:Audience"],
// IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(Environment.GetEnvironmentVariable("JWT_KEY")))
// };
}); });
builder.Services.Configure<IdentityOptions>(options => builder.Services.Configure<IdentityOptions>(options =>
{ {
// SignIn settings. // SignIn settings.
options.SignIn.RequireConfirmedAccount = false; options.SignIn.RequireConfirmedAccount = false;
options.SignIn.RequireConfirmedEmail = false; options.SignIn.RequireConfirmedEmail = false;
@ -132,12 +116,10 @@ builder.Services.AddAuthorization(options =>
// Require the External role to authenticate with a different authentication method // Require the External role to authenticate with a different authentication method
options.AddPolicy("External", policy => policy options.AddPolicy("External", policy => policy
.RequireRole("External") .RequireRole("External")
.AddAuthenticationSchemes("OAuthToken") .AddAuthenticationSchemes(JwtBearerDefaults.AuthenticationScheme)
); );
}); });
builder.Services.AddSingleton<JwtService>();
var app = builder.Build(); var app = builder.Build();
// Configure the HTTP request pipeline. // Configure the HTTP request pipeline.

@ -1,57 +0,0 @@
using System.Security.Claims;
using System.Security.Cryptography;
using Microsoft.IdentityModel.JsonWebTokens;
using Microsoft.IdentityModel.Tokens;
namespace OAuthServer.Services;
public class JwtService
{
private readonly RSA _rsaKey;
public JwtService()
{
_rsaKey = GetSigningKey();
}
public static RSA GetSigningKey()
{
RSA rsaKey = RSA.Create();
const string jwtKeyPath = ".aspnet/jwt-key";
string home = Environment.GetFolderPath(Environment.SpecialFolder.UserProfile);
string fullPath = Path.Combine(home, jwtKeyPath);
if (File.Exists(fullPath))
{
rsaKey.ImportRSAPrivateKey(File.ReadAllBytes(fullPath), out _);
}
else
{
string? dirName = Path.GetDirectoryName(fullPath);
if (!string.IsNullOrEmpty(dirName))
Directory.CreateDirectory(dirName);
var privateKey = rsaKey.ExportRSAPrivateKey();
File.WriteAllBytes(fullPath, privateKey);
}
return rsaKey;
}
public string GenerateToken()
{
var handler = new JsonWebTokenHandler();
var key = new RsaSecurityKey(_rsaKey);
var token = handler.CreateToken(new SecurityTokenDescriptor
{
Subject = new ClaimsIdentity(new[]
{
new Claim(JwtRegisteredClaimNames.Sub, "user1"),
new Claim("role", "External"),
new Claim("scope", "scope:1")
}),
Expires = DateTime.UtcNow.AddDays(10),
SigningCredentials = new SigningCredentials(key, SecurityAlgorithms.RsaSha256)
});
return token;
}
}
Loading…
Cancel
Save