在模块类中,添加以下行:
//使用以下命名空间
using Volo.Abp.AspNetCore.Mvc;
//模块类
[DependsOn(typeof(AbpAspNetCoreMvcModule))]
public class MyApplicationModule : AbpModule
{
//身份验证配置
public override void ConfigureServices(ServiceConfigurationContext context)
{
Configure(options =>
{
options.ConventionalControllers.Create(typeof(MyApplicationModule).Assembly);
});
Configure(options =>
{
options.AuthenticationSchemeName = "Bearer";
options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
options.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
});
context.Services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
.AddJwtBearer(options =>
{
options.Authority = "https://localhost:5001";
options.Audience = "MyApiClientId";
options.RequireHttpsMetadata = false;
options.TokenValidationParameters = new TokenValidationParameters
{
NameClaimType = "name",
RoleClaimType = "role"
};
});
}
}
在此示例中,配置了JwtBearer身份验证,并将其添加到了应用程序依赖关系中。
可以在控制器中的POST方法中获取令牌字符串,如下所示:
[HttpPost]
public async Task Post(CreatePostInput input)
{
//从HTTP头获取令牌
var accessToken = Request.Headers["Authorization"].ToString().Substring("Bearer ".Length).Trim();
//获取JWT实例
var handler = new JwtSecurityTokenHandler();
var jwt = await handler.ReadJwtTokenAsync(accessToken);
//访问声明
var userId