【发布时间】:2021-11-24 04:13:41
【问题描述】:
我正在尝试在具有 Angular 8 前端和 .Net Core 后端的应用中实现基于 JWT 的身份验证。我加了
app.UseAuthentication();
app.UseAuthorization();
和
services.AddAuthentication(opt =>
在启动类中。我使用[Authorize] 属性修饰了控制器方法。但是当我尝试在没有任何标记的情况下点击控制器方法时,它允许进入控制器方法。
启动
public class Startup
{
public Startup(IConfiguration configuration)
{
Configuration = configuration;
}
public IConfiguration Configuration { get; }
// This method gets called by the runtime. Use this method to add services to the container.
public void ConfigureServices(IServiceCollection services)
{
var jwtSettings = Configuration.GetSection("JwtSettings");
services.AddAuthentication(opt =>
{
opt.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
opt.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
}).AddJwtBearer(options =>
{
options.TokenValidationParameters = new TokenValidationParameters
{
ValidateIssuer = true,
ValidateAudience = true,
ValidateLifetime = true,
ValidateIssuerSigningKey = true,
ValidIssuer = jwtSettings.GetSection("validIssuer").Value,
ValidAudience = jwtSettings.GetSection("validAudience").Value,
IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(jwtSettings.GetSection("securityKey").Value))
};
});
services.AddSignalR();
services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1);
// In production, the Angular files will be served from this directory
services.AddSpaStaticFiles(configuration =>
{
configuration.RootPath = "ClientApp/dist";
});
// requires using Microsoft.Extensions.Options
services.Configure<DatabaseSettings>(
Configuration.GetSection(nameof(DatabaseSettings)));
services.AddSingleton<IDatabaseSettings>(sp =>
sp.GetRequiredService<IOptions<DatabaseSettings>>().Value);
services.AddSingleton<FileService>();
services.AddSingleton<InternalReportService>();
services.AddTransient<MailService>();
services.AddMvc(option => option.EnableEndpointRouting = false);
}
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
app.UseRouting();
app.UseMvc();
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
else
{
app.UseExceptionHandler("/Error");
app.UseHsts();
}
app.UseHttpsRedirection();
app.UseStaticFiles();
app.UseAuthentication();
app.UseAuthorization();
app.UseEndpoints(endpoints =>
{
endpoints.MapHub<CoreHub>("/corehub");
endpoints.MapControllerRoute("default", "{controller=Home}/{action=Index}");
});
app.UseSpa(spa =>
{
spa.Options.SourcePath = "ClientApp";
if (env.IsDevelopment())
{
spa.UseProxyToSpaDevelopmentServer("http://localhost:4200");
}
});
}
}
控制器
[Authorize]
public async Task UploadFile(IFormFile file)
{
// Do Stuff
}
【问题讨论】:
-
尝试使用这个 services.AddMvcCore() 而不是 services.AddMvc()
-
您没有共享创建 JWT 或持久化令牌的代码。
-
https://code-maze.com/authentication-aspnetcore-jwt-1/
标签: c# asp.net-core .net-core jwt asp.net-core-webapi