345 lines
12 KiB
C#
345 lines
12 KiB
C#
|
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<74><68>Ȩ<EFBFBD>˵<EFBFBD>
|
|||
|
TokenUrl = new Uri("http://localhost:32769/connect/token"), // OAuth<74><68><EFBFBD>ƶ˵<C6B6>
|
|||
|
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; // Ĭ<><C4AC>ʹ<EFBFBD><CAB9> Cookie <20><><EFBFBD><EFBFBD><EFBFBD><EFBFBD>֤
|
|||
|
//options.DefaultChallengeScheme = OpenIddictDefaults.AuthenticationScheme; // Ĭ<><C4AC><EFBFBD><EFBFBD>ս<EFBFBD><D5BD><EFBFBD><EFBFBD>
|
|||
|
})
|
|||
|
.AddCookie(options =>
|
|||
|
{
|
|||
|
options.LoginPath = "/Account/Login"; // <20><><EFBFBD>õ<EFBFBD>¼·<C2BC><C2B7>
|
|||
|
options.LogoutPath = "/Account/Logout"; // <20><><EFBFBD>õdz<C3B5>·<EFBFBD><C2B7>
|
|||
|
options.Cookie.HttpOnly = true; // <20><><EFBFBD><EFBFBD> Cookie <20><> HttpOnly <20><><EFBFBD><EFBFBD>
|
|||
|
options.Cookie.SecurePolicy = CookieSecurePolicy.SameAsRequest; // <20><><EFBFBD><EFBFBD> Cookie <20>İ<EFBFBD>ȫ<EFBFBD><C8AB><EFBFBD><EFBFBD>
|
|||
|
}).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);
|
|||
|
|
|||
|
// <20><><EFBFBD><EFBFBD>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[]{ }
|
|||
|
}
|
|||
|
});
|
|||
|
// <20><><EFBFBD><EFBFBD> OAuth <20><>֤֧<D6A4><D6A7>
|
|||
|
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<74><68>Ȩ<EFBFBD>˵<EFBFBD>
|
|||
|
TokenUrl = new Uri("http://localhost:32769/connect/token"), // OAuth<74><68><EFBFBD>ƶ˵<C6B6>
|
|||
|
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 <20><>֤
|
|||
|
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 <20><>֤<EFBFBD><D6A4><EFBFBD><EFBFBD>
|
|||
|
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 =>
|
|||
|
{
|
|||
|
// <20><><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD>Է<EFBFBD><D4B7><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD>ͷ<EFBFBD><CDB7><EFBFBD><EFBFBD>ʹ<EFBFBD><CAB9><EFBFBD>ĸ<EFBFBD><C4B8><EFBFBD><EFBFBD>巽<EFBFBD><E5B7BD>
|
|||
|
options.ForwardDefaultSelector = context =>
|
|||
|
{
|
|||
|
// <20><><EFBFBD><EFBFBD>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";
|
|||
|
}
|
|||
|
|
|||
|
// <20><><EFBFBD><EFBFBD>cookie
|
|||
|
if (context.Request.Cookies.ContainsKey("AuthCookie"))
|
|||
|
return CookieAuthenticationDefaults.AuthenticationScheme;
|
|||
|
|
|||
|
// Ĭ<>Ϸ<EFBFBD><CFB7><EFBFBD>JWT<57><54><EFBFBD>ɸ<EFBFBD><C9B8><EFBFBD><EFBFBD><EFBFBD>Ҫ<EFBFBD>ģ<DEB8>
|
|||
|
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,//<2F>Ƿ<EFBFBD><C7B7><EFBFBD>֤SecurityKey
|
|||
|
ValidateIssuer = true, //<2F>Ƿ<EFBFBD><C7B7><EFBFBD>֤Issuer
|
|||
|
ValidateAudience = true, //<2F>Ƿ<EFBFBD><C7B7><EFBFBD>֤Audience
|
|||
|
ValidateLifetime = true, //<2F>Ƿ<EFBFBD><C7B7><EFBFBD>֤ʧЧʱ<D0A7><CAB1>
|
|||
|
ClockSkew = TimeSpan.FromSeconds(30),//<2F><><EFBFBD><EFBFBD>ʱ<EFBFBD><CAB1><EFBFBD>ݴ<EFBFBD>ֵ
|
|||
|
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 =>
|
|||
|
{
|
|||
|
// <20><><EFBFBD><EFBFBD><EFBFBD>ﴦ<EFBFBD><EFB4A6> OAuth <20><><EFBFBD>ص<EFBFBD><D8B5><EFBFBD><EFBFBD>ݣ<EFBFBD><DDA3><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD>ȡ<EFBFBD>û<EFBFBD><C3BB><EFBFBD>Ϣ<EFBFBD><CFA2>
|
|||
|
|
|||
|
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);
|
|||
|
}
|