tec*_*hno 8 c# jwt .net-core asp.net-core asp.net-core-webapi
我正在尝试在具有 Angular 8 前端和 .Net Core 后端的应用程序中实现基于 JWT 的身份验证。我已经添加了
app.UseAuthentication();
app.UseAuthorization();
Run Code Online (Sandbox Code Playgroud)
和
services.AddAuthentication(opt =>
Run Code Online (Sandbox Code Playgroud)
在启动类中。我使用属性装饰了控制器方法[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");
}
});
}
}
Run Code Online (Sandbox Code Playgroud)
控制器
[Authorize]
public async Task UploadFile(IFormFile file)
{
// Do Stuff
}
Run Code Online (Sandbox Code Playgroud)
好了,您已经配置了 API 的身份验证部分,现在您需要以相同的方式配置授权......
你可以这样配置:
services.AddAuthorization(options =>
{
options.AddPolicy("Default", new AuthorizationPolicyBuilder()
.AddAuthenticationSchemes(JwtBearerDefaults.AuthenticationScheme)
.RequireAuthenticatedUser()
.Build());
options.AddPolicy("Admin", new AuthorizationPolicyBuilder()
.RequireRole("Admin")
.AddAuthenticationSchemes(JwtBearerDefaults.AuthenticationScheme)
.RequireAuthenticatedUser()
.Build());
});
Run Code Online (Sandbox Code Playgroud)
然后您将能够使用该属性
[Authorize("User")]
[Authorize("Admin")]
Run Code Online (Sandbox Code Playgroud)
在您的控制器或特定端点上。
如果您希望将此默认策略应用于所有端点/控制器并仅控制 if 的“AllowAnonymous”部分,您可以执行以下操作:
services.AddMvc()
.AddMvcOptions(options =>
{
// Mark all endpoints with the default policy
options.Filters.Add(new AuthorizeFilter("Default"));
})
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
3824 次 |
| 最近记录: |