diff --git a/README.zh-CN.md b/README.zh-CN.md index 6b67400..b116115 100644 --- a/README.zh-CN.md +++ b/README.zh-CN.md @@ -58,7 +58,7 @@ MiniAuth 一个轻量 ASP.NET Core Identity Web 后台管理中间插件 - 兼容 : 支持 .NET identity Based on JWT, Cookie, Session 等 - 简单 : 拔插设计,API、MVC、Razor Page 等开箱即用 - 支持多数据库 : 支持 Oracle, SQL Server, MySQL 等 EF Core -- 渐进、非侵入式 : 不影响现有数据库、项目结构 +- 非侵入式 : 不影响现有数据库、项目结构 - 多平台 : 支持 Linux, macOS 环境 @@ -72,84 +72,52 @@ MiniAuth 一个轻量 ASP.NET Core Identity Web 后台管理中间插件 在 Startup 添加一行代码 `services.AddMiniAuth()` 并运行项目,例子: ```csharp - public class Program +public class Program +{ + public static void Main(string[] args) { - public static void Main(string[] args) - { - var builder = WebApplication.CreateBuilder(args); + var builder = WebApplication.CreateBuilder(args); - builder.Services.AddMiniAuth(); // <= ❗❗❗ + builder.Services.AddMiniAuth(); // <= ❗❗❗ - var app = builder.Build(); - app.Run(); - } + var app = builder.Build(); + app.Run(); } +} ``` -接着访问管理网页,链接为 `http(s)://yourhost/miniauth/index.html`,预设 admin 管理账号为 `admin@mini-software.github.io` 密码为 `E7c4f679-f379-42bf-b547-684d456bc37f` (请记得修改密码),即可管理你的 Identity 用户、角色、端点。 - -其他跟 asp.net core identity 使用方式一样,在需要权限管理的类别或方法上加上 `[Authorize]` 或是角色管控 `[Authorize(Roles = "角色")]`,假设没登入返回 401 状态, 没权限返回 403 状态。 - - - -注意: 如有自己的 identity auth 请看以下注意点 - -### 应用在现有的 identity 项目,自定义逻辑 - -把 AddMiniAuth autoUse 关闭,将 UseMiniAuth 并在泛型参数换上自己的 IdentityDBContext、用户、权限认证,放在自己的 Auth 之后,例子: -```csharp - public static void Main(string[] args) - { - var builder = WebApplication.CreateBuilder(args); - - var connectionString = builder.Configuration.GetConnectionString("DefaultConnection") ?? throw new InvalidOperationException("Connection string 'DefaultConnection' not found."); - builder.Services.AddDbContext(options => - options.UseSqlServer(connectionString)); - builder.Services.AddDatabaseDeveloperPageExceptionFilter(); - - builder.Services.AddDefaultIdentity(options => options.SignIn.RequireConfirmedAccount = true) - .AddRoles() - .AddEntityFrameworkStores(); - - builder.Services.AddControllersWithViews(); - - builder.Services.AddMiniAuth(autoUse: false); // <= ❗❗❗ +接着访问管理网页,Link 为 `http(s)://yourhost/miniauth/index.html`,预设 admin 管理账号为 `admin@mini-software.github.io` 密码为 `E7c4f679-f379-42bf-b547-684d456bc37f` (请记得修改密码),即可管理你的 Identity 用户、角色、端点。 +在需要权限管理的类别或方法上加上 `[Authorize]` 或是角色管控 `[Authorize(Roles = "角色")]`,假设没登入返回 401 状态, 没权限返回 403 状态。 - var app = builder.Build(); - - app.UseMiniAuth(); // <= ❗❗❗ - app.MapControllerRoute( - name: "default", - pattern: "{controller=Home}/{action=Index}/{id?}"); - app.MapRazorPages(); - - app.Run(); - } -``` - -能切换使用自己的用户、角色、DB、Identity 逻辑。 - +### MiniAuth Cookie Identity +MiniAuth 预设为单体 Coookie Based identity,如前后端分离项目请更换 JWT 等 Auth。 -### 使用 MiniAuth JWT Identity +### MiniAuth JWT Identity 指定 AuthenticationType 为 BearerJwt ```C# -MiniAuthOptions.AuthenticationType = MiniAuthOptions.AuthType.BearerJwt; -builder.Services.AddMiniAuth(); +var builder = WebApplication.CreateBuilder(args); +builder.Services.AddMiniAuth(options:(options) => +{ + options.AuthenticationType = MiniAuthOptions.AuthType.BearerJwt; +}); ``` 请记得自定义 JWT Security Key,如: ```C# -MiniAuthOptions.JWTKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes("6ee3edbf-488e-4484-9c2c-e3ffa6dcbc09")); -builder.Services.AddMiniAuth(); +var builder = WebApplication.CreateBuilder(args); +builder.Services.AddMiniAuth(options: (options) => +{ + options.JWTKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes("6ee3edbf-488e-4484-9c2c-e3ffa6dcbc09")); +}); ``` #### 获取用户 token 方式 @@ -235,6 +203,8 @@ Authorization:Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJuYW1lIjoiYWRtaW5AbW + + ### 设定、选项、自定义 #### 预设模式 @@ -247,22 +217,34 @@ Authorization:Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJuYW1lIjoiYWRtaW5AbW ```C# // 放在 service 注册之前 -MiniAuthOptions.LoginPath = "/Identity/Account/Login"; -MiniAuthOptions.DisableMiniAuthLogin = true; +builder.Services.AddMiniAuth(options: (options) => +{ + options.LoginPath = "/Identity/Account/Login"; + options.DisableMiniAuthLogin = true; +}); ``` #### 自定义预设的 SQLite Connection String ```C# -MiniAuthOptions.SqliteConnectionString = "Data Source=miniauth_identity.db"; +builder.Services.AddMiniAuth(options: (options) => +{ + options.SqliteConnectionString = "Data Source=miniauth_identity.db"; +}); ``` -### 更换数据库 +### 自定义数据库、用户、角色 + +MiniAuth 系统预设使用 SQLite EF Core、IdentityUser、IdentityRole开箱即用 +如果需要切换请在 `app.UseMiniAuth` 泛型指定不同的数据库、自己的用户、角色类别。 + +```C# +app.UseMiniAuth(); +``` + -MiniAuth 系统预设使用 SQLite,无需做任何设定代码 -如果需要切换请在 `app.UseMiniAuth` 泛型指定不同的数据库型别。 ### 登录、用户验证 @@ -277,10 +259,13 @@ ApiController 的 Controller 预设不会导向登录页面,而是返回 401 s ### 自定路由前缀 ``` -MiniAuthOptions.RoutePrefix = "YourName"; +builder.Services.AddMiniAuth(options: (options) => +{ + options.RoutePrefix = "YourName"; +}); ``` -预设为 `MiniAuth` +预设 RoutePrefix 为 `MiniAuth`。 @@ -355,11 +340,46 @@ builder.Services.AddDefaultIdentity(options => options.SignIn.Requ .AddEntityFrameworkStores(); ``` -### 请自行设定好 CORS +### + + +### 应用在现有的 identity 项目,自定义逻辑 +把 AddMiniAuth autoUse 关闭,将 UseMiniAuth 并在泛型参数换上自己的 IdentityDBContext、用户、权限认证,放在自己的 Auth 之后,例子: +```csharp + public static void Main(string[] args) + { + var builder = WebApplication.CreateBuilder(args); + var connectionString = builder.Configuration.GetConnectionString("DefaultConnection") ?? throw new InvalidOperationException("Connection string 'DefaultConnection' not found."); + builder.Services.AddDbContext(options => + options.UseSqlServer(connectionString)); + builder.Services.AddDatabaseDeveloperPageExceptionFilter(); + + builder.Services.AddDefaultIdentity(options => options.SignIn.RequireConfirmedAccount = true) + .AddRoles() + .AddEntityFrameworkStores(); + + builder.Services.AddControllersWithViews(); + + builder.Services.AddMiniAuth(autoUse: false); // <= ❗❗❗ + + + var app = builder.Build(); + + app.UseMiniAuth(); // <= ❗❗❗ + app.MapControllerRoute( + name: "default", + pattern: "{controller=Home}/{action=Index}/{id?}"); + app.MapRazorPages(); + + app.Run(); + } +``` + +能切换使用自己的用户、角色、DB、Identity 逻辑。 diff --git a/src/MiniAuth.IdentityAuth/MiniAuthIdentityBuilderExtensions.cs b/src/MiniAuth.IdentityAuth/MiniAuthIdentityBuilderExtensions.cs index be4c67a..82829dc 100644 --- a/src/MiniAuth.IdentityAuth/MiniAuthIdentityBuilderExtensions.cs +++ b/src/MiniAuth.IdentityAuth/MiniAuthIdentityBuilderExtensions.cs @@ -66,7 +66,7 @@ public static IApplicationBuilder UseMiniAuth { - endpoints.MapGet($"/{MiniAuthOptions.RoutePrefix}/api/getAllEndpoints", async (HttpContext context, + // setting config api + endpoints.MapPost($"/{MiniAuthOption.RoutePrefix}/api/getConfig", async (HttpContext context + , TDbContext _dbContext + ) => + { + var config = _dbContext.RoleClaims.Where(w => w.RoleId == "system").ToArray(); + var result = config.Select(s => new + { + s.ClaimType, + s.ClaimValue + }); + await OkResult(context, result.ToJson()); + }).RequireAuthorization(new AuthorizeAttribute() { Roles = "miniauth-admin" }); + + endpoints.MapGet($"/{MiniAuthOption.RoutePrefix}/api/getAllEndpoints", async (HttpContext context, TDbContext _dbContext ) => { await OkResult(context, _endpointCache.Values.OrderByDescending(o => o.Id).ToJson()); }) .RequireAuthorization(new AuthorizeAttribute() { Roles = "miniauth-admin" }); - endpoints.MapGet($"/{MiniAuthOptions.RoutePrefix}/logout", async (HttpContext context + endpoints.MapGet($"/{MiniAuthOption.RoutePrefix}/logout", async (HttpContext context , SignInManager signInManager , IOptions identityOptionsAccessor ) => { await signInManager.SignOutAsync(); - context.Response.Redirect(MiniAuthOptions.LoginPath); + context.Response.Redirect(MiniAuthOption.LoginPath); }); - if (!MiniAuthOptions.DisableMiniAuthLogin) + if (!MiniAuthOption.DisableMiniAuthLogin) { - endpoints.MapPost($"/{MiniAuthOptions.RoutePrefix}/refreshToken", async ( + endpoints.MapPost($"/{MiniAuthOption.RoutePrefix}/refreshToken", async ( [FromBody] RefreshRequest refreshRequest, [FromServices] IServiceProvider sp , HttpContext context ) => { - if (MiniAuth.MiniAuthOptions.AuthenticationType != MiniAuthOptions.AuthType.BearerJwt) + if (MiniAuth.MiniAuthOption.AuthenticationType != AuthType.BearerJwt) { context.Response.StatusCode = StatusCodes.Status401Unauthorized; return; @@ -79,7 +93,7 @@ [FromServices] IServiceProvider sp }).RequireAuthorization(new AuthorizeAttribute() { Roles = "miniauth-admin" }); - endpoints.MapPost($"/{MiniAuthOptions.RoutePrefix}/login", async ( + endpoints.MapPost($"/{MiniAuthOption.RoutePrefix}/login", async ( [FromBody] LoginRequest login , [FromServices] IServiceProvider sp , HttpContext context @@ -89,7 +103,7 @@ [FromBody] LoginRequest login TDbContext _dbContext = sp.GetRequiredService(); SignInManager signInManager = sp.GetRequiredService>(); - if (MiniAuth.MiniAuthOptions.AuthenticationType == MiniAuthOptions.AuthType.BearerJwt) + if (MiniAuth.MiniAuthOption.AuthenticationType == AuthType.BearerJwt) { var user = await _dbContext.Users.FirstOrDefaultAsync(f => f.UserName == login.username); if (!(user != null && await _userManager.CheckPasswordAsync((TIdentityUser)user, login.password))) @@ -124,7 +138,7 @@ [FromBody] LoginRequest login } - endpoints.MapGet($"/{MiniAuthOptions.RoutePrefix}/api/getRoles", async (HttpContext context + endpoints.MapGet($"/{MiniAuthOption.RoutePrefix}/api/getRoles", async (HttpContext context , TDbContext _dbContext ) => { @@ -142,7 +156,7 @@ [FromBody] LoginRequest login await OkResult(context, roles.ToJson()); }).RequireAuthorization(new AuthorizeAttribute() { Roles = "miniauth-admin" }); - endpoints.MapPost($"/{MiniAuthOptions.RoutePrefix}/api/saveRole", async (HttpContext context + endpoints.MapPost($"/{MiniAuthOption.RoutePrefix}/api/saveRole", async (HttpContext context , TDbContext _dbContext ) => { @@ -199,7 +213,7 @@ [FromBody] LoginRequest login }).RequireAuthorization(new AuthorizeAttribute() { Roles = "miniauth-admin" }); - endpoints.MapPost($"/{MiniAuthOptions.RoutePrefix}/api/deleteRole", async (HttpContext context + endpoints.MapPost($"/{MiniAuthOption.RoutePrefix}/api/deleteRole", async (HttpContext context , TDbContext _dbContext ) => { @@ -216,7 +230,7 @@ [FromBody] LoginRequest login }).RequireAuthorization(new AuthorizeAttribute() { Roles = "miniauth-admin" }); - endpoints.MapPost($"/{MiniAuthOptions.RoutePrefix}/api/getUsers", async (HttpContext context + endpoints.MapPost($"/{MiniAuthOption.RoutePrefix}/api/getUsers", async (HttpContext context , TDbContext _dbContext ) => { @@ -261,7 +275,7 @@ [FromBody] LoginRequest login await OkResult(context, new { users = userVo, totalItems }.ToJson()); }).RequireAuthorization(new AuthorizeAttribute() { Roles = "miniauth-admin" }); - endpoints.MapPost($"/{MiniAuthOptions.RoutePrefix}/api/deleteUser", async (HttpContext context + endpoints.MapPost($"/{MiniAuthOption.RoutePrefix}/api/deleteUser", async (HttpContext context , TDbContext _dbContext ) => { @@ -277,7 +291,7 @@ [FromBody] LoginRequest login await OkResult(context, "".ToJson(code: 200, message: "")); }).RequireAuthorization(new AuthorizeAttribute() { Roles = "miniauth-admin" }); - endpoints.MapPost($"/{MiniAuthOptions.RoutePrefix}/api/saveUser", async (HttpContext context + endpoints.MapPost($"/{MiniAuthOption.RoutePrefix}/api/saveUser", async (HttpContext context , TDbContext _dbContext , UserManager userManager ) => @@ -402,7 +416,7 @@ [FromBody] LoginRequest login } }).RequireAuthorization(new AuthorizeAttribute() { Roles = "miniauth-admin" }); - endpoints.MapPost($"/{MiniAuthOptions.RoutePrefix}/api/resetPassword", async (HttpContext context + endpoints.MapPost($"/{MiniAuthOption.RoutePrefix}/api/resetPassword", async (HttpContext context , TDbContext _dbContext , UserManager userManager ) => @@ -439,7 +453,7 @@ [FromBody] LoginRequest login } }).RequireAuthorization(new AuthorizeAttribute() { Roles = "miniauth-admin" }); - endpoints.MapGet($"/{MiniAuthOptions.RoutePrefix}/api/getUserInfo", async (HttpContext context + endpoints.MapGet($"/{MiniAuthOption.RoutePrefix}/api/getUserInfo", async (HttpContext context , TDbContext _dbContext ) => { @@ -497,15 +511,15 @@ private async Task JwtLoginImpl(UserManager _userManager, TDbCont claims.Add(new Claim("sub", user.Id)); var token = string.Empty; - var TokenExpiresIn = (MiniAuthOptions.TokenExpiresIn); + var TokenExpiresIn = (MiniAuthOption.TokenExpiresIn); { - var secretkey = MiniAuthOptions.JWTKey; + var secretkey = MiniAuthOption.JWTKey; var credentials = new SigningCredentials(secretkey, SecurityAlgorithms.HmacSha256); var tokenDescriptor = new SecurityTokenDescriptor() { Subject = new ClaimsIdentity(claims), Expires = DateTime.UtcNow.AddSeconds(TokenExpiresIn), - Issuer = MiniAuthOptions.Issuer, + Issuer = MiniAuthOption.Issuer, SigningCredentials = credentials }; @@ -515,13 +529,13 @@ private async Task JwtLoginImpl(UserManager _userManager, TDbCont } var refreshToekn = string.Empty; { - var refreshTokenExpiresIn = (MiniAuthOptions.TokenExpiresIn) / 2; - var secretkey = MiniAuthOptions.JWTKey; + var refreshTokenExpiresIn = (MiniAuthOption.TokenExpiresIn) / 2; + var secretkey = MiniAuthOption.JWTKey; var credentials = new SigningCredentials(secretkey, SecurityAlgorithms.HmacSha256); var tokenDescriptor = new SecurityTokenDescriptor() { Expires = DateTime.UtcNow.AddSeconds(refreshTokenExpiresIn), - Issuer = MiniAuthOptions.Issuer, + Issuer = MiniAuthOption.Issuer, Subject = new ClaimsIdentity(new Claim[] { new Claim("sub", user.Id), @@ -537,7 +551,7 @@ private async Task JwtLoginImpl(UserManager _userManager, TDbCont { tokenType = "Bearer", accessToken = token, - expiresIn = MiniAuthOptions.TokenExpiresIn, + expiresIn = MiniAuthOption.TokenExpiresIn, refreshToken = refreshToekn }; diff --git a/src/MiniAuth.IdentityAuth/MiniAuthIdentityMiddleware.cs b/src/MiniAuth.IdentityAuth/MiniAuthIdentityMiddleware.cs index f37a70a..1398713 100644 --- a/src/MiniAuth.IdentityAuth/MiniAuthIdentityMiddleware.cs +++ b/src/MiniAuth.IdentityAuth/MiniAuthIdentityMiddleware.cs @@ -18,22 +18,16 @@ public partial class MiniAuthIdentityMiddleware private const string EmbeddedFileNamespace = "MiniAuth.IdentityAuth.wwwroot"; private readonly RequestDelegate _next; private readonly ILogger _logger; - private readonly MiniAuthOptions _options; private readonly StaticFileMiddleware _staticFileMiddleware; private static bool FirstRun = true; public MiniAuthIdentityMiddleware(RequestDelegate next, ILogger logger, ILoggerFactory loggerFactory, - IWebHostEnvironment hostingEnv, - MiniAuthOptions options = null + IWebHostEnvironment hostingEnv ) { this._logger = logger; this._next = next; - if (options == null) - _options = new MiniAuthOptions(); - else - _options = options; this._staticFileMiddleware = CreateStaticFileMiddleware(next, loggerFactory, hostingEnv); ; } public async Task Invoke(HttpContext context) @@ -57,7 +51,7 @@ private StaticFileMiddleware CreateStaticFileMiddleware(RequestDelegate next, IL { var staticFileOptions = new StaticFileOptions { - RequestPath = string.IsNullOrEmpty(MiniAuthOptions.RoutePrefix) ? string.Empty : $"/{MiniAuthOptions.RoutePrefix}", + RequestPath = string.IsNullOrEmpty(MiniAuthOption.RoutePrefix) ? string.Empty : $"/{MiniAuthOption.RoutePrefix}", FileProvider = new EmbeddedFileProvider(typeof(MiniAuthIdentityMiddleware).GetTypeInfo().Assembly, "MiniAuth.Identity.wwwroot"), }; diff --git a/src/MiniAuth.IdentityAuth/MiniAuthIdentityServiceExtensions.cs b/src/MiniAuth.IdentityAuth/MiniAuthIdentityServiceExtensions.cs index 697e8b1..c909a90 100644 --- a/src/MiniAuth.IdentityAuth/MiniAuthIdentityServiceExtensions.cs +++ b/src/MiniAuth.IdentityAuth/MiniAuthIdentityServiceExtensions.cs @@ -20,29 +20,33 @@ public static class MiniAuthIdentityServiceExtensions { - private static IServiceCollection AddMiniIdentityAuth(this IServiceCollection services, bool isAutoUse) + private static IServiceCollection AddMiniIdentityAuth(this IServiceCollection services, bool isAutoUse, Action options = null) { _ = services ?? throw new ArgumentNullException(nameof(services)); - var connectionString = MiniAuthOptions.SqliteConnectionString; + var connectionString = MiniAuthOption.SqliteConnectionString; services.AddDbContext(options => { options.UseSqlite(connectionString); }); - services.AddMiniAuth(isAutoUse); + services.AddMiniAuth(isAutoUse, options: options); return services; } - public static IServiceCollection AddMiniAuth(this IServiceCollection services, bool autoUse = true) + public static IServiceCollection AddMiniAuth(this IServiceCollection services, bool autoUse = true, Action options = null) { _ = services ?? throw new ArgumentNullException(nameof(services)); - services.AddMiniIdentityAuth(autoUse); //TODO: auto use issue : https://github.com/mini-software/MiniAuth/issues/151 + services.AddMiniIdentityAuth(autoUse, options: options); //TODO: auto use issue : https://github.com/mini-software/MiniAuth/issues/151 return services; } - public static IServiceCollection AddMiniAuth(this IServiceCollection services, bool isAutoUse = true) + public static IServiceCollection AddMiniAuth(this IServiceCollection services, bool isAutoUse = true, Action options = null) where TDbContext : IdentityDbContext where TIdentityUser : IdentityUser where TIdentityRole : IdentityRole { _ = services ?? throw new ArgumentNullException(nameof(services)); + if (options != null) + { + options(new MiniAuthOptions()); + } // if not exist AddAuthorization then add default policy var existAuthorization = services.Any(o => o.ServiceType == typeof(IAuthorizationService)); @@ -56,17 +60,21 @@ public static IServiceCollection AddMiniAuth(); + + if (services.All(o => o.ServiceType != typeof(IAuthenticationService))) { Debug.WriteLine("* Use MiniAuth default AddAuthentication"); - if (MiniAuthOptions.AuthenticationType == MiniAuthOptions.AuthType.Cookie) + if (MiniAuthOption.AuthenticationType == AuthType.Cookie) { services .AddMiniAuth() .AddDefaultTokenProviders() .AddEntityFrameworkStores(); } - if (MiniAuthOptions.AuthenticationType == MiniAuthOptions.AuthType.BearerJwt) + if (MiniAuthOption.AuthenticationType == AuthType.BearerJwt) { services.AddIdentity() @@ -87,11 +95,11 @@ public static IServiceCollection AddMiniAuth { - o.LoginPath = $"/{MiniAuthOptions.RoutePrefix}/login.html"; + o.LoginPath = $"/{MiniAuthOption.RoutePrefix}/login.html"; o.Events = new CookieAuthenticationEvents { OnRedirectToLogin = ctx => diff --git a/src/MiniAuth.IdentityAuth/MiniAuthOption.cs b/src/MiniAuth.IdentityAuth/MiniAuthOption.cs new file mode 100644 index 0000000..3d6eaa3 --- /dev/null +++ b/src/MiniAuth.IdentityAuth/MiniAuthOption.cs @@ -0,0 +1,75 @@ +using Microsoft.Extensions.Configuration; +using Microsoft.IdentityModel.Tokens; +using System.Text; + +namespace MiniAuth +{ + public class MiniAuthOptions + { + public string RoutePrefix + { + set { MiniAuthOption.RoutePrefix = value; } + get { return MiniAuthOption.RoutePrefix; } + } + public string LoginPath + { + set { MiniAuthOption.LoginPath = value; } + get { return MiniAuthOption.LoginPath; } + } + public bool DisableMiniAuthLogin + { + set { MiniAuthOption.DisableMiniAuthLogin = value; } + get { return MiniAuthOption.DisableMiniAuthLogin; } + } + public AuthType AuthenticationType + { + set { MiniAuthOption.AuthenticationType = value; } + get { return MiniAuthOption.AuthenticationType; } + } + public SecurityKey JWTKey + { + set { MiniAuthOption.JWTKey = value; } + get { return MiniAuthOption.JWTKey; } + } + + /// + /// Token expires in seconds, default is 1 hour + /// + public int TokenExpiresIn + { + set { MiniAuthOption.TokenExpiresIn = value; } + get { return MiniAuthOption.TokenExpiresIn; } + } + public string Issuer + { + set { MiniAuthOption.Issuer = value; } + get { return MiniAuthOption.Issuer; } + } + public string SqliteConnectionString + { + set { MiniAuthOption.SqliteConnectionString = value; } + get { return MiniAuthOption.SqliteConnectionString; } + } + } + public enum AuthType + { + Cookie, + BearerJwt + } + internal class MiniAuthOption + + { + public static string RoutePrefix = "MiniAuth"; + public static string LoginPath = $"/{RoutePrefix}/login.html"; + public static bool DisableMiniAuthLogin = false; + + public static AuthType AuthenticationType = AuthType.Cookie; + public static SecurityKey JWTKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes("this is miniauth key for demo")); + /// + /// Token expires in seconds, default is 1 hour + /// + public static int TokenExpiresIn = 60 * 60; + public static string Issuer = $"{RoutePrefix}"; + public static string SqliteConnectionString = "Data Source=miniauth_identity.db"; + } +} diff --git a/src/MiniAuth.IdentityAuth/MiniAuthOptions.cs b/src/MiniAuth.IdentityAuth/MiniAuthOptions.cs deleted file mode 100644 index 8085657..0000000 --- a/src/MiniAuth.IdentityAuth/MiniAuthOptions.cs +++ /dev/null @@ -1,26 +0,0 @@ -using Microsoft.Extensions.Configuration; -using Microsoft.IdentityModel.Tokens; -using System.Text; - -namespace MiniAuth -{ - public class MiniAuthOptions - { - public static string RoutePrefix = "MiniAuth"; - public static string LoginPath = $"/{RoutePrefix}/login.html"; - public static bool DisableMiniAuthLogin = false; - public enum AuthType - { - Cookie, - BearerJwt - } - public static AuthType AuthenticationType = AuthType.Cookie; - public static SecurityKey JWTKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes("this is miniauth key for demo")); - /// - /// Token expires in seconds, default is 1 hour - /// - public static int TokenExpiresIn = 60*60; - public static string Issuer = $"{RoutePrefix}"; - public static string SqliteConnectionString = "Data Source=miniauth_identity.db"; - } -} diff --git a/tests/TestCustomOptions/TestCustomOptions.sln b/tests/TestCustomOptions/TestCustomOptions.sln new file mode 100644 index 0000000..c5eef39 --- /dev/null +++ b/tests/TestCustomOptions/TestCustomOptions.sln @@ -0,0 +1,31 @@ + +Microsoft Visual Studio Solution File, Format Version 12.00 +# Visual Studio Version 17 +VisualStudioVersion = 17.10.34928.147 +MinimumVisualStudioVersion = 10.0.40219.1 +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "TestCustomOptions", "TestCustomOptions\TestCustomOptions.csproj", "{04CBD6CF-CC7A-48E5-899D-97A19F64056A}" +EndProject +Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "MiniAuth.IdentityAuth", "..\..\src\MiniAuth.IdentityAuth\MiniAuth.IdentityAuth.csproj", "{50DD0991-97CB-4163-ABAC-93D761109427}" +EndProject +Global + GlobalSection(SolutionConfigurationPlatforms) = preSolution + Debug|Any CPU = Debug|Any CPU + Release|Any CPU = Release|Any CPU + EndGlobalSection + GlobalSection(ProjectConfigurationPlatforms) = postSolution + {04CBD6CF-CC7A-48E5-899D-97A19F64056A}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {04CBD6CF-CC7A-48E5-899D-97A19F64056A}.Debug|Any CPU.Build.0 = Debug|Any CPU + {04CBD6CF-CC7A-48E5-899D-97A19F64056A}.Release|Any CPU.ActiveCfg = Release|Any CPU + {04CBD6CF-CC7A-48E5-899D-97A19F64056A}.Release|Any CPU.Build.0 = Release|Any CPU + {50DD0991-97CB-4163-ABAC-93D761109427}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {50DD0991-97CB-4163-ABAC-93D761109427}.Debug|Any CPU.Build.0 = Debug|Any CPU + {50DD0991-97CB-4163-ABAC-93D761109427}.Release|Any CPU.ActiveCfg = Release|Any CPU + {50DD0991-97CB-4163-ABAC-93D761109427}.Release|Any CPU.Build.0 = Release|Any CPU + EndGlobalSection + GlobalSection(SolutionProperties) = preSolution + HideSolutionNode = FALSE + EndGlobalSection + GlobalSection(ExtensibilityGlobals) = postSolution + SolutionGuid = {1C891A51-3CBE-4191-87D9-0380ECF086E9} + EndGlobalSection +EndGlobal diff --git a/tests/TestCustomOptions/TestCustomOptions/Program.cs b/tests/TestCustomOptions/TestCustomOptions/Program.cs new file mode 100644 index 0000000..2cfadd6 --- /dev/null +++ b/tests/TestCustomOptions/TestCustomOptions/Program.cs @@ -0,0 +1,39 @@ +using Microsoft.Extensions.Options; +using Microsoft.IdentityModel.Tokens; +using MiniAuth; +using System.Text; + +namespace TestCustomOptions +{ + public class Program + { + public static void Main(string[] args) + { + var builder = WebApplication.CreateBuilder(args); + //builder.Services.AddMiniAuth(options: (options) => + //{ + // options.JWTKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes("6ee3edbf-488e-4484-9c2c-e3ffa6dcbc09")); + // options.LoginPath = "/Identity/Account/Login"; + // options.DisableMiniAuthLogin = true; + //}); + + builder.Services.AddMiniAuth(options: (options) => + { + options.RoutePrefix = "MiniAuth"; + options.LoginPath = $"/{options.RoutePrefix}/login.html"; + options.DisableMiniAuthLogin = false; + options.AuthenticationType = AuthType.BearerJwt; + options.JWTKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes("This is a secret key")); + options.TokenExpiresIn = 3600; + options.Issuer = "MiniAuth"; + options.SqliteConnectionString = "Data Source=MiniAuth.db"; + }); + + var app = builder.Build(); + + app.MapGet("/", () => "Hello World!"); + + app.Run(); + } + } +} diff --git a/tests/TestCustomOptions/TestCustomOptions/Properties/launchSettings.json b/tests/TestCustomOptions/TestCustomOptions/Properties/launchSettings.json new file mode 100644 index 0000000..2f356e0 --- /dev/null +++ b/tests/TestCustomOptions/TestCustomOptions/Properties/launchSettings.json @@ -0,0 +1,29 @@ +{ + "$schema": "http://json.schemastore.org/launchsettings.json", + "iisSettings": { + "windowsAuthentication": false, + "anonymousAuthentication": true, + "iisExpress": { + "applicationUrl": "http://localhost:56467", + "sslPort": 0 + } + }, + "profiles": { + "http": { + "commandName": "Project", + "dotnetRunMessages": true, + "launchBrowser": true, + "applicationUrl": "http://localhost:5221", + "environmentVariables": { + "ASPNETCORE_ENVIRONMENT": "Development" + } + }, + "IIS Express": { + "commandName": "IISExpress", + "launchBrowser": true, + "environmentVariables": { + "ASPNETCORE_ENVIRONMENT": "Development" + } + } + } +} diff --git a/tests/TestCustomOptions/TestCustomOptions/TestCustomOptions.csproj b/tests/TestCustomOptions/TestCustomOptions/TestCustomOptions.csproj new file mode 100644 index 0000000..1ccb627 --- /dev/null +++ b/tests/TestCustomOptions/TestCustomOptions/TestCustomOptions.csproj @@ -0,0 +1,13 @@ + + + + net8.0 + enable + enable + + + + + + + diff --git a/tests/TestCustomOptions/TestCustomOptions/appsettings.Development.json b/tests/TestCustomOptions/TestCustomOptions/appsettings.Development.json new file mode 100644 index 0000000..0c208ae --- /dev/null +++ b/tests/TestCustomOptions/TestCustomOptions/appsettings.Development.json @@ -0,0 +1,8 @@ +{ + "Logging": { + "LogLevel": { + "Default": "Information", + "Microsoft.AspNetCore": "Warning" + } + } +} diff --git a/tests/TestCustomOptions/TestCustomOptions/appsettings.json b/tests/TestCustomOptions/TestCustomOptions/appsettings.json new file mode 100644 index 0000000..10f68b8 --- /dev/null +++ b/tests/TestCustomOptions/TestCustomOptions/appsettings.json @@ -0,0 +1,9 @@ +{ + "Logging": { + "LogLevel": { + "Default": "Information", + "Microsoft.AspNetCore": "Warning" + } + }, + "AllowedHosts": "*" +}