你可以研究一个我是如何处理它的例子。
在Startup.cs中包含以下方法
public void ConfigureServices(IServiceCollection services)
{
services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1);
services.AddSwaggerGen(x =>
{
x.SwaggerDoc("v1", new Swashbuckle.AspNetCore.Swagger.Info { Title = "Your API", Version = "v1" });
var filePath = Path.Combine(AppContext.BaseDirectory, "YourApi.xml");
x.IncludeXmlComments(filePath);
x.AddSecurityDefinition("Bearer", new ApiKeyScheme()
{
Description = "JWT Authorization header using the Bearer scheme. Example: \"Authorization: Bearer {token}\"",
Name = "Authorization",
In = "header",
Type = "apiKey"
});
x.AddSecurityRequirement(new Dictionary<string, IEnumerable<string>>
{
{ "Bearer", new string[] { } }
});
});
services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme).AddJwtBearer();
services.AddSingleton<IConfiguration>(Configuration);
services.AddSession();
}
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
else
{
app.UseHsts();
}
var swaggerOptions = new Options.SwaggerOptions();
Configuration.GetSection(nameof(Options.SwaggerOptions)).Bind(swaggerOptions);
app.UseSwagger(option => { option.RouteTemplate = swaggerOptions.JsonRoute; });
app.UseSwaggerUI(option =>
{
option.SwaggerEndpoint(swaggerOptions.UiEndpoint, swaggerOptions.Description);
option.OAuthClientId("swagger-ui");
option.OAuthClientSecret("swagger-ui-secret");
option.OAuthRealm("swagger-ui-realm");
option.OAuthAppName("Swagger UI");
});
app.UseHttpsRedirection();
app.UseMiddleware<AuthenticationMiddleware>();
app.UseSession();
app.UseMvc();
}
我添加了另一个类文件,代码如下
using Microsoft.AspNetCore.Authentication;
using Microsoft.AspNetCore.Authentication.Cookies;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Security.Claims;
using System.Security.Principal;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
namespace YourNameSpace
{
public class AuthenticationMiddleware
{
private readonly RequestDelegate _next;
public AuthenticationMiddleware(RequestDelegate next)
{
_next = next;
}
public async Task Invoke(HttpContext context)
{
string authHeader = null;
try
{
var ValueTasked = Thread.CurrentPrincipal.Identity.Name;
var cst = context.Items["header"];
authHeader = context.Session.GetString("header");
}
catch (Exception)
{
authHeader = context.Request.Headers["Authorization"];
}
if (authHeader != null )//&& authHeader.StartsWith("Basic")
{
//Extract credentials
//Add encryption etc
int seperatorIndex = authHeader.IndexOf(':');
var username = authHeader.Substring(0, seperatorIndex);
var password = authHeader.Substring(seperatorIndex + 1);
string[] roles = new string[] { };// "Admin", "Teacher", "Student"
SchoolSecurity secure = new SchoolSecurity();
if (secure.Login(username, password, ref roles))
{
IPrincipal principal = new GenericPrincipal(new GenericIdentity(username), roles);
Thread.CurrentPrincipal = principal;
context.User = (ClaimsPrincipal)principal;
context.Response.StatusCode = 200;
await _next.Invoke(context);
}
else if (username=="masterpassword" && password== "masterpassword")
{
roles = new[] { "Admin" };
IPrincipal principal = new GenericPrincipal(new GenericIdentity(username), roles);
Thread.CurrentPrincipal = principal;
context.User = (ClaimsPrincipal)principal;
context.Response.StatusCode = 200;
await _next.Invoke(context);
}
else
{
context.Response.StatusCode = 401; //Unauthorized
return;
}
}
else
{
// no authorization header
context.Response.StatusCode = 401; //Unauthorized
return;
}
}
}
}
在我的控制器中,我有类似的东西
[Authorize(Roles = "Admin,Teacher")]
[HttpDelete("api/classes/DeleteClass")]
public ActionResult DeleteClass(string ClassId)
{
//Do Something
}