Skip to content

Commit

Permalink
Test : add jwt api
Browse files Browse the repository at this point in the history
  • Loading branch information
shps951023 committed May 28, 2024
1 parent 5fc7efd commit 6a9ec69
Show file tree
Hide file tree
Showing 12 changed files with 280 additions and 2 deletions.
5 changes: 3 additions & 2 deletions README.zh-CN.md
Original file line number Diff line number Diff line change
Expand Up @@ -55,10 +55,11 @@ MiniAuth 一个轻量 ASP.NET Core Identity Web 后台管理插件

### 特点

- 兼容 : Based on JWT, Cookie, Session 只要符合 .NET identity 规格都能使用
- 兼容 : Based on JWT, Cookie, Session 只要符合 .NET identity 规格都支持
- 简单 : 拔插设计,API、MVC、Razor Page 等,都能开箱即用
- 多平台 : 支持 Linux, macOS 环境
- 支持多数据库 : 符合 Identity EF Core 规格的数据库都能使用
- 支持多数据库 : 符合 Identity EF Core 规格的数据库都支持
- 渐进、非侵入式 : 预设不会影响现有数据库结构,如有类似组织、部门需求在渐进添加


### 安装
Expand Down
1 change: 1 addition & 0 deletions README.zh-Hant.md
Original file line number Diff line number Diff line change
Expand Up @@ -52,6 +52,7 @@ MiniAuth 一個輕量 ASP.NET Core Identity Web 後台管理插件
- 多平台 : 支持 Linux, macOS
- 支持多資料庫 : 符合 Identity EF Core 規格的資料庫都能使用


### 安裝

[NuGet](https://www.nuget.org/packages/MiniAuth) 安裝套件
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
{
"version": 1,
"isRoot": true,
"tools": {
"dotnet-ef": {
"version": "8.0.5",
"commands": [
"dotnet-ef"
]
}
}
}
25 changes: 25 additions & 0 deletions tests/TestJWTApi/TestJWTApi.sln
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@

Microsoft Visual Studio Solution File, Format Version 12.00
# Visual Studio Version 17
VisualStudioVersion = 17.8.34330.188
MinimumVisualStudioVersion = 10.0.40219.1
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "TestJWTApi", "TestJWTApi\TestJWTApi.csproj", "{C644AE74-FED9-4C63-9C81-D1CE8DE4CD78}"
EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
Debug|Any CPU = Debug|Any CPU
Release|Any CPU = Release|Any CPU
EndGlobalSection
GlobalSection(ProjectConfigurationPlatforms) = postSolution
{C644AE74-FED9-4C63-9C81-D1CE8DE4CD78}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{C644AE74-FED9-4C63-9C81-D1CE8DE4CD78}.Debug|Any CPU.Build.0 = Debug|Any CPU
{C644AE74-FED9-4C63-9C81-D1CE8DE4CD78}.Release|Any CPU.ActiveCfg = Release|Any CPU
{C644AE74-FED9-4C63-9C81-D1CE8DE4CD78}.Release|Any CPU.Build.0 = Release|Any CPU
EndGlobalSection
GlobalSection(SolutionProperties) = preSolution
HideSolutionNode = FALSE
EndGlobalSection
GlobalSection(ExtensibilityGlobals) = postSolution
SolutionGuid = {F4EF91A3-92FD-45A0-AA57-8FD95B64F34C}
EndGlobalSection
EndGlobal
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
using Microsoft.AspNetCore.Mvc;

namespace TestJWTApi.Controllers
{
[ApiController]
[Route("[controller]")]
public class WeatherForecastController : ControllerBase
{
private static readonly string[] Summaries = new[]
{
"Freezing", "Bracing", "Chilly", "Cool", "Mild", "Warm", "Balmy", "Hot", "Sweltering", "Scorching"
};

private readonly ILogger<WeatherForecastController> _logger;

public WeatherForecastController(ILogger<WeatherForecastController> logger)
{
_logger = logger;
}

[HttpGet]
public IEnumerable<WeatherForecast> Get()
{
return Enumerable.Range(1, 5).Select(index => new WeatherForecast
{
Date = DateOnly.FromDateTime(DateTime.Now.AddDays(index)),
TemperatureC = Random.Shared.Next(-20, 55),
Summary = Summaries[Random.Shared.Next(Summaries.Length)]
})
.ToArray();
}
}
}
113 changes: 113 additions & 0 deletions tests/TestJWTApi/TestJWTApi/Program.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,113 @@
using Microsoft.AspNetCore.Authentication.JwtBearer;
using Microsoft.AspNetCore.Identity;
using Microsoft.AspNetCore.Identity.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore;
using Microsoft.IdentityModel.Tokens;
using Microsoft.OpenApi.Models;
using System.Text;

namespace TestJWTApi
{
public class Program
{
public static void Main(string[] args)
{
var builder = WebApplication.CreateBuilder(args);

// Add services to the container.

builder.Services.AddControllers();
ConfigureServices(builder.Services);
var app = builder.Build();
Configure(app);
app.Run();
}

public static void ConfigureServices(IServiceCollection services)
{
// Add Identity
var connectionString = "Data Source=miniauth_identity.db";
services.AddDbContext<IdentityDbContext>(options =>
{
options.UseSqlite(connectionString);
});
//services.AddIdentity<IdentityUser, IdentityRole>()
// .AddEntityFrameworkStores<IdentityDbContext>()
// .AddDefaultTokenProviders();



//services.AddEndpointsApiExplorer();

// Configure JWT authentication
services.AddAuthentication(options =>
{
options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
options.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
}).AddJwtBearer(options =>
{
options.TokenValidationParameters = new TokenValidationParameters
{
ValidateIssuer = true,
ValidateAudience = true,
ValidateLifetime = true,
ValidateIssuerSigningKey = true,
ValidIssuer = "Issuer",// Configuration["Jwt:Issuer"],
ValidAudience = "Issuer",// Configuration["Jwt:Issuer"],
IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(
"jwtkey"//Configuration["Jwt:Key"]
))
};
});

services.AddIdentityApiEndpoints<IdentityUser>()
.AddEntityFrameworkStores<IdentityDbContext>();

// Add Swagger
services.AddSwaggerGen(c =>
{
c.SwaggerDoc("v1", new OpenApiInfo { Title = "Your API", Version = "v1" });
// Include the JWT bearer token in the request header
c.AddSecurityDefinition("Bearer", new OpenApiSecurityScheme
{
Description = "JWT Authorization header using the Bearer scheme",
Type = SecuritySchemeType.Http,
Scheme = "bearer"
});
c.AddSecurityRequirement(new OpenApiSecurityRequirement
{
{
new OpenApiSecurityScheme
{
Reference = new OpenApiReference
{
Type = ReferenceType.SecurityScheme,
Id = "Bearer"
}
},
new string[] { }
}
});
});
}

public static void Configure(IApplicationBuilder app)
{
// Use authentication
app.UseAuthentication();

// Use Swagger UI
app.UseSwagger();
app.UseSwaggerUI(c =>
{
c.SwaggerEndpoint("/swagger/v1/swagger.json", "Your API v1");
c.RoutePrefix = string.Empty; // Serve the Swagger UI at the root URL
});

// Other middleware configurations
}

}
}
41 changes: 41 additions & 0 deletions tests/TestJWTApi/TestJWTApi/Properties/launchSettings.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,41 @@
{
"$schema": "http://json.schemastore.org/launchsettings.json",
"iisSettings": {
"windowsAuthentication": false,
"anonymousAuthentication": true,
"iisExpress": {
"applicationUrl": "http://localhost:50460",
"sslPort": 44379
}
},
"profiles": {
"http": {
"commandName": "Project",
"dotnetRunMessages": true,
"launchBrowser": true,
"launchUrl": "weatherforecast",
"applicationUrl": "http://localhost:5059",
"environmentVariables": {
"ASPNETCORE_ENVIRONMENT": "Development"
}
},
"https": {
"commandName": "Project",
"dotnetRunMessages": true,
"launchBrowser": true,
"launchUrl": "weatherforecast",
"applicationUrl": "https://localhost:7157;http://localhost:5059",
"environmentVariables": {
"ASPNETCORE_ENVIRONMENT": "Development"
}
},
"IIS Express": {
"commandName": "IISExpress",
"launchBrowser": true,
"launchUrl": "weatherforecast",
"environmentVariables": {
"ASPNETCORE_ENVIRONMENT": "Development"
}
}
}
}
16 changes: 16 additions & 0 deletions tests/TestJWTApi/TestJWTApi/TestJWTApi.csproj
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
<Project Sdk="Microsoft.NET.Sdk.Web">

<PropertyGroup>
<TargetFramework>net8.0</TargetFramework>
<Nullable>enable</Nullable>
<ImplicitUsings>enable</ImplicitUsings>
<InvariantGlobalization>true</InvariantGlobalization>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="Microsoft.AspNetCore.Authentication.JwtBearer" Version="8.0.0" />
<PackageReference Include="Microsoft.AspNetCore.Identity.EntityFrameworkCore" Version="8.0.0" />
<PackageReference Include="Microsoft.EntityFrameworkCore.Sqlite" Version="8.0.0" />
<PackageReference Include="Microsoft.AspNetCore.OpenApi" Version="8.0.0" />
<PackageReference Include="Swashbuckle.AspNetCore" Version="6.4.0" />
</ItemGroup>
</Project>
6 changes: 6 additions & 0 deletions tests/TestJWTApi/TestJWTApi/TestJWTApi.http
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
@TestJWTApi_HostAddress = http://localhost:5059

GET {{TestJWTApi_HostAddress}}/weatherforecast/
Accept: application/json

###
13 changes: 13 additions & 0 deletions tests/TestJWTApi/TestJWTApi/WeatherForecast.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
namespace TestJWTApi
{
public class WeatherForecast
{
public DateOnly Date { get; set; }

public int TemperatureC { get; set; }

public int TemperatureF => 32 + (int)(TemperatureC / 0.5556);

public string? Summary { get; set; }
}
}
8 changes: 8 additions & 0 deletions tests/TestJWTApi/TestJWTApi/appsettings.Development.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
{
"Logging": {
"LogLevel": {
"Default": "Information",
"Microsoft.AspNetCore": "Warning"
}
}
}
9 changes: 9 additions & 0 deletions tests/TestJWTApi/TestJWTApi/appsettings.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
{
"Logging": {
"LogLevel": {
"Default": "Information",
"Microsoft.AspNetCore": "Warning"
}
},
"AllowedHosts": "*"
}

0 comments on commit 6a9ec69

Please sign in to comment.