2025-06-15 11:49:34 +08:00

345 lines
12 KiB
C#
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

using AspNetCore.Authentication.Basic;
using Microsoft.AspNetCore.Authentication.Cookies;
using Microsoft.AspNetCore.Authentication.JwtBearer;
using Microsoft.AspNetCore.Mvc.Controllers;
using Microsoft.Extensions.Options;
using Microsoft.IdentityModel.Tokens;
using Microsoft.OpenApi.Models;
using System.Security.Claims;
using System.Text;
var builder = WebApplication.CreateBuilder(args);
// Add services to the container.
builder.Services.AddControllers();
// Learn more about configuring OpenAPI at https://aka.ms/aspnet/openapi
builder.Services.AddOpenApi();
//ConfigureSwagger(builder.Services);
//ConfigureAuthentication(builder.Services);
builder.Services.AddSwaggerGen(x =>
{
x.AddSecurityDefinition("OAuth2", new OpenApiSecurityScheme
{
Description = "OAuth2 Authorization: Click the authorize button below to redirect to third-party authentication.",
Name = "Authorization",
In = ParameterLocation.Header,
BearerFormat = "JWT",
Scheme = "Bearer",
Type = SecuritySchemeType.OAuth2,
Flows = new OpenApiOAuthFlows
{
AuthorizationCode = new OpenApiOAuthFlow
{
AuthorizationUrl = new Uri("http://localhost:32769/connect/authorize"), // OAuthÊÚȨ¶Ëµã
TokenUrl = new Uri("http://localhost:32769/connect/token"), // OAuthÁîÅÆ¶Ëµã
Scopes = new Dictionary<string, string>
{
{ "Account", "User registration and login" },
{ "Email", "Email verification, send verification code" }
}
}
},
});
x.AddSecurityRequirement(new OpenApiSecurityRequirement
{
{
new OpenApiSecurityScheme
{
Reference = new OpenApiReference
{
Type = ReferenceType.SecurityScheme,
Id = "OAuth2"
}
},
new string[] { }
}
});
});
builder.Services.AddAuthentication(options =>
{
options.DefaultScheme = CookieAuthenticationDefaults.AuthenticationScheme; // ĬÈÏʹÓà Cookie Éí·ÝÑéÖ¤
//options.DefaultChallengeScheme = OpenIddictDefaults.AuthenticationScheme; // ĬÈÏÌôÕ½·½°¸
})
.AddCookie(options =>
{
options.LoginPath = "/Account/Login"; // ÅäÖõǼ·¾¶
options.LogoutPath = "/Account/Logout"; // ÅäÖõdzö·¾¶
options.Cookie.HttpOnly = true; // ÆôÓà Cookie µÄ HttpOnly ÊôÐÔ
options.Cookie.SecurePolicy = CookieSecurePolicy.SameAsRequest; // ÅäÖà Cookie µÄ°²È«²ßÂÔ
}).AddOAuth("OAuth2", x =>
{
x.SignInScheme = "cookie";
x.ClientId = "test1";
x.ClientSecret = "test1";
x.AuthorizationEndpoint = "http://localhost:5278/oauth/authorize";
x.TokenEndpoint = "http://localhost:5278/oauth/token";
x.CallbackPath = "/back/path";
});
var app = builder.Build();
// Configure the HTTP request pipeline.
if (app.Environment.IsDevelopment())
{
app.MapOpenApi();
}
app.UseSwagger();
app.UseSwaggerUI();
app.UseAuthorization();
app.MapControllers();
app.Run();
void ConfigureSwagger(IServiceCollection services)
{
services.AddSwaggerGen(x =>
{
x.SwaggerDoc("v1", new OpenApiInfo { Title = builder.Environment.ApplicationName, Version = "v1" });
//var baseDirectory = AppDomain.CurrentDomain.BaseDirectory;
//var xmlFile = AppDomain.CurrentDomain.FriendlyName + ".xml";
//var xmlPath = Path.Combine(baseDirectory, xmlFile);
//x.IncludeXmlComments(xmlPath, true);
//x.OrderActionsBy(x => x.RelativePath);
//x.CustomOperationIds(x =>
//{
// var controllerAction = x.ActionDescriptor as ControllerActionDescriptor;
// return controllerAction.ControllerName + "-" + controllerAction.ActionName;
//});
//x.IncludeXmlComments(Path.Combine(AppContext.BaseDirectory, xmlFile), true);
// Ìí¼ÓJWT
x.AddSecurityDefinition("Bearer", new Microsoft.OpenApi.Models.OpenApiSecurityScheme()
{
Description = "Enter the JWT authorization token in the request header: Bearer Token",
Name = "Authorization",
In = ParameterLocation.Header,
Type = SecuritySchemeType.ApiKey,
BearerFormat = "JWT",
Scheme = "Bearer",
});
x.AddSecurityRequirement(new Microsoft.OpenApi.Models.OpenApiSecurityRequirement()
{
{
new OpenApiSecurityScheme(){
Reference = new OpenApiReference(){
Type=ReferenceType.SecurityScheme,
Id="Bearer"
}
},new string[]{ }
}
});
// Ìí¼Ó OAuth ÈÏÖ¤Ö§³Ö
x.AddSecurityDefinition("OAuth2", new OpenApiSecurityScheme
{
Description = "OAuth2 Authorization: Click the authorize button below to redirect to third-party authentication.",
Name = "Authorization",
In = ParameterLocation.Header,
BearerFormat = "JWT",
Scheme = "Bearer",
Type = SecuritySchemeType.OAuth2,
Flows = new OpenApiOAuthFlows
{
AuthorizationCode = new OpenApiOAuthFlow
{
AuthorizationUrl = new Uri("http://localhost:32769/connect/authorize"), // OAuthÊÚȨ¶Ëµã
TokenUrl = new Uri("http://localhost:32769/connect/token"), // OAuthÁîÅÆ¶Ëµã
Scopes = new Dictionary<string, string>
{
{ "Account", "User registration and login" },
{ "Email", "Email verification, send verification code" }
}
}
},
});
x.AddSecurityRequirement(new OpenApiSecurityRequirement
{
{
new OpenApiSecurityScheme
{
Reference = new OpenApiReference
{
Type = ReferenceType.SecurityScheme,
Id = "OAuth2"
}
},
new string[] { }
}
});
// Basic ÈÏÖ¤
x.AddSecurityDefinition("Basic", new OpenApiSecurityScheme
{
Name = "Authorization",
Type = SecuritySchemeType.Http,
Scheme = "basic",
In = ParameterLocation.Header,
Description = "Basic Authentication"
});
x.AddSecurityRequirement(new OpenApiSecurityRequirement{
{
new OpenApiSecurityScheme
{
Reference = new OpenApiReference { Type = ReferenceType.SecurityScheme, Id = "Basic" }
},
Array.Empty<string>()
}
});
// Cookie ÈÏÖ¤ÅäÖÃ
x.AddSecurityDefinition("Cookie", new OpenApiSecurityScheme
{
Name = "Cookie",
Type = SecuritySchemeType.ApiKey,
In = ParameterLocation.Cookie,
Description = "Enter your session cookie"
});
x.AddSecurityRequirement(new OpenApiSecurityRequirement
{
{
new OpenApiSecurityScheme
{
Reference = new OpenApiReference
{
Type = ReferenceType.SecurityScheme,
Id = "Cookie"
}
},
new string[] { }
}
});
x.AddSecurityDefinition("ApiKey", new OpenApiSecurityScheme()
{
In = ParameterLocation.Header,
Name = "X-API-KEY",
Type = SecuritySchemeType.ApiKey,
Description = "API KEY Authentication"
});
x.AddSecurityRequirement(new OpenApiSecurityRequirement()
{
{
new OpenApiSecurityScheme
{
Reference = new OpenApiReference
{
Type = ReferenceType.SecurityScheme,
Id = "ApiKey"
}
},
new string[] { }
}
});
});
}
void ConfigureAuthentication(IServiceCollection services)
{
services.AddAuthentication(x =>
{
x.DefaultAuthenticateScheme = "MultiAuthSchemes";
x.DefaultChallengeScheme = "MultiAuthSchemes";
x.DefaultForbidScheme = "MultiAuthSchemes";
}).AddPolicyScheme("MultiAuthSchemes", "MultiAuthSchemes", options =>
{
// Õâ¸ö²ßÂÔ·½°¸»á¸ù¾ÝÇëÇóÍ·¾ö¶¨Ê¹ÓÃÄĸö¾ßÌå·½°¸
options.ForwardDefaultSelector = context =>
{
// ¼ì²éAuthorizationÍ·
string authorization = context.Request.Headers["Authorization"].FirstOrDefault();
if (!string.IsNullOrEmpty(authorization))
{
if (authorization.StartsWith("Bearer "))
return JwtBearerDefaults.AuthenticationScheme;
if (authorization.StartsWith("Basic "))
return "Basic";
}
// ¼ì²écookie
if (context.Request.Cookies.ContainsKey("AuthCookie"))
return CookieAuthenticationDefaults.AuthenticationScheme;
// ĬÈÏ·µ»ØJWT£¨¿É¸ù¾ÝÐèÒªÐ޸ģ©
return JwtBearerDefaults.AuthenticationScheme;
};
})
.AddJwtBearer(x =>
{
x.RequireHttpsMetadata = false;
x.SaveToken = true;
x.TokenValidationParameters = new Microsoft.IdentityModel.Tokens.TokenValidationParameters()
{
IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes("12345678123456781234567812345678")),
ValidIssuer = "token.Issuer",
ValidAudience =" token.Audience",
ValidateIssuerSigningKey = true,//ÊÇ·ñÑéÖ¤SecurityKey
ValidateIssuer = true, //ÊÇ·ñÑéÖ¤Issuer
ValidateAudience = true, //ÊÇ·ñÑéÖ¤Audience
ValidateLifetime = true, //ÊÇ·ñÑé֤ʧЧʱ¼ä
ClockSkew = TimeSpan.FromSeconds(30),//¹ýÆÚʱ¼äÈÝ´íÖµ
RequireExpirationTime = true
};
})
.AddOAuth("OAuth", x =>
{
x.ClientId = "Yu_App";
x.ClientSecret = "123456";
x.CallbackPath = "/signin-oauth";
x.AuthorizationEndpoint = "1";
x.TokenEndpoint = "1";
x.Scope.Add("");
x.SaveTokens = true;
x.Events = new Microsoft.AspNetCore.Authentication.OAuth.OAuthEvents()
{
OnCreatingTicket = context =>
{
// ÔÚÕâÀï´¦Àí OAuth ·µ»ØµÄÊý¾Ý£¬ÀýÈçÌáÈ¡Óû§ÐÅÏ¢µÈ
var identity = context.Principal.Identity;
var tokens = context.AccessToken;
var claimsIdentity = context.Principal.Identity as ClaimsIdentity;
claimsIdentity?.AddClaim(new Claim("access_token", context.AccessToken));
return Task.CompletedTask;
}
};
}).AddCookie()
.AddBasic("Basic", x =>
{
x.Realm = "CloudTrade";
x.ClaimsIssuer = "admin";
x.SuppressWWWAuthenticateHeader = false;
x.Events = new BasicEvents()
{
OnValidateCredentials = context =>
{
if (context.Username == "admin" && context.Password == "admin")
{
var claims = new[] {
new Claim(ClaimTypes.Name,context.Username)
};
context.Principal = new ClaimsPrincipal(new ClaimsIdentity(claims, context.Scheme.Name));
context.Success();
}
return Task.CompletedTask;
}
};
})
;
// services.AddAuthentication("ApiKey").AddScheme<AuthenticationSchemeOptions,>
// services.AddAuthentication("Basic").AddScheme<AuthenticationSchemeOptions, BasicAuthenticationHandler>("Basic", null);
}