Backend/C_shape/WEBAPI/JWT/JWTdemo/Program.cs

131 lines
4.2 KiB
C#
Raw Permalink Normal View History

2024-05-06 14:09:39 +08:00
using Microsoft.AspNetCore.Authentication.JwtBearer;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.DependencyInjection;
using JWTdemo.Authorization;
using JWTdemo.Helpers;
using System.Configuration;
using System.Reflection;
using JWTdemo.Services;
using Microsoft.IdentityModel.Tokens;
using System.Text;
using Microsoft.OpenApi.Models;
var builder = WebApplication.CreateBuilder(args);
builder.Services.AddCors();
builder.Services.AddControllers();
// Add services to the container.
//builder.Services.AddControllersWithViews();
//*------------------------------連線PostgreSQL資料庫-----------------------------------------------
var connectionString = "Server=localhost;UserID=postgres;Password=vip125125;Database=postgres;port=5432;";
builder.Services.AddDbContext<SqlContext>(opt => opt.UseNpgsql(connectionString));
//*---------------------------------JWT身分驗證-------------------------------------------------------
{
var services = builder.Services;
services.AddCors();
services.AddControllers();
services.Configure<AppSettings>(builder.Configuration.GetSection("AppSettings"));
var jwtSettings = builder.Configuration.GetSection("AppSettings").Get<AppSettings>();
services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
.AddJwtBearer(options =>
{
options.TokenValidationParameters = new TokenValidationParameters
{
ValidateIssuer = false,
ValidateAudience = false,
ValidateIssuerSigningKey = true,
//ValidIssuer = "your_issuer",
// ValidAudience = "your_audience",
ClockSkew = TimeSpan.Zero,
IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(jwtSettings.Secret))
};
});
services.AddSwaggerGen(c =>
{
c.SwaggerDoc("v1", new OpenApiInfo { Title = "WebApi_data_value", Version = "v1" });
// Configure Swagger to use JWT authentication
c.AddSecurityDefinition("Bearer", new OpenApiSecurityScheme
{
Description = "JWT Authorization header using the Bearer scheme",
Name = "Authorization",
In = ParameterLocation.Header,
Type = SecuritySchemeType.ApiKey,
Scheme = "Bearer"
});
// 将JWT令牌作为所有端点的要求添加到Swagger文档
c.AddSecurityRequirement(new OpenApiSecurityRequirement
{
{
new OpenApiSecurityScheme
{
Reference = new OpenApiReference
{
Type = ReferenceType.SecurityScheme,
Id = "Bearer"
}
},
new string[] { }
}
});
});
// configure DI for application services
services.AddScoped<IJwtUtils, JwtUtils>();
services.AddScoped<IUserService, UserService>();
// 注册 HttpClient 服务
services.AddHttpClient();
}
//*---------------------------創專案就有--------------------------
builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen();
//*---------------------------WebAPI註解設定--------------------------
builder.Services.AddSwaggerGen(options =>
{
var xmlFilename = $"{Assembly.GetExecutingAssembly().GetName().Name}.xml";
options.IncludeXmlComments(Path.Combine(AppContext.BaseDirectory, xmlFilename));
});
var app = builder.Build();
//*---------------------------JWT身分驗證------------------------------
{
// global cors policy
//在 ASP.NET Core 中啟用 CORS (跨原始來源要求)
// Shows UseCors with CorsPolicyBuilder.
app.UseCors(x => x
.AllowAnyOrigin()
.AllowAnyMethod()
.AllowAnyHeader());
// custom jwt auth middleware
app.UseMiddleware<JwtMiddleware>();
app.MapControllers();
}
//-------------------------Swagger初始化-------------------------------------
if (app.Environment.IsDevelopment())
{
app.UseSwagger();
app.UseSwaggerUI(c =>
{
c.SwaggerEndpoint("/swagger/v1/swagger.json", "JWTdemo"); //API註解開啟
});
}
app.UseHttpsRedirection();
app.UseAuthorization();
app.MapControllers();
app.Run();