【发布时间】:2019-10-30 13:16:11
【问题描述】:
我在这里关注这篇文章:https://fullstackmark.com/post/13/jwt-authentication-with-aspnet-core-2-web-api-angular-5-net-core-identity-and-facebook-login,我遇到了一个障碍,我的 JWT 不记名令牌没有授权我的用户。我得到了一个有效的 JWT - 见截图:
我已经阅读了这篇文章中的所有 cmets,其他一些因各种原因得到 401,但我已经满足了所有这些问题,它们不是我的问题。
想知道另一双眼睛是否有助于发现正在发生的事情。顺便说一句,我没有将Identity 用于我的登录内容。我更喜欢为此使用自己的表结构和登录机制,但我认为这不是问题的根源。
这是我的 startup.cs 文件。有人在这里跳出来吗?不太确定下一步该去哪里。
public class Startup
{
private const string SecretKey = "iNivDmHLpUA223sqsfhqGbMRdRj1PVkH";
private readonly SymmetricSecurityKey _signingKey = new SymmetricSecurityKey(Encoding.ASCII.GetBytes(SecretKey));
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)
{
services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_2);
// In production, the Angular files will be served from this directory
services.AddSpaStaticFiles(configuration =>
{
configuration.RootPath = "ClientApp/dist";
});
services.AddDbContext<MyHomeBuilderContext>(options =>
options.UseSqlServer(Configuration.GetConnectionString("MyHomeBuilderContext"))
);
services.AddSingleton<IJwtFactory, JwtFactory>();
services.TryAddTransient<IHttpContextAccessor, HttpContextAccessor>();
// jwt wire up
// Get options from app settings
var jwtAppSettingOptions = Configuration.GetSection(nameof(JwtIssuerOptions));
// Configure JwtIssuerOptions
services.Configure<JwtIssuerOptions>(options =>
{
options.Issuer = jwtAppSettingOptions[nameof(JwtIssuerOptions.Issuer)];
options.Audience = jwtAppSettingOptions[nameof(JwtIssuerOptions.Audience)];
options.SigningCredentials = new SigningCredentials(_signingKey, SecurityAlgorithms.HmacSha256);
});
var tokenValidationParameters = new TokenValidationParameters
{
ValidateIssuer = true,
ValidIssuer = jwtAppSettingOptions[nameof(JwtIssuerOptions.Issuer)],
ValidateAudience = true,
ValidAudience = jwtAppSettingOptions[nameof(JwtIssuerOptions.Audience)],
ValidateIssuerSigningKey = true,
IssuerSigningKey = _signingKey,
RequireExpirationTime = false,
ValidateLifetime = true,
ClockSkew = TimeSpan.Zero
};
services.AddAuthentication(options =>
{
options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
options.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
}).AddJwtBearer(configureOptions =>
{
configureOptions.ClaimsIssuer = jwtAppSettingOptions[nameof(JwtIssuerOptions.Issuer)];
configureOptions.TokenValidationParameters = tokenValidationParameters;
configureOptions.SaveToken = true;
});
// api user claim policy
services.AddAuthorization(options =>
{
options.AddPolicy("ApiUser", policy => policy.RequireClaim(Constants.Strings.JwtClaimIdentifiers.Rol, Constants.Strings.JwtClaims.ApiAccess));
});
// map the email settings from appsettings.json so they can be pushed to the core project
services.Configure<EmailSettingsModel>(Configuration.GetSection("EmailSettings"))
.AddSingleton(jd => jd.GetRequiredService<IOptions<EmailSettingsModel>>().Value);
// map the push notification settings from appsettings.json so they can be pushed to the core project
services.Configure<PushSettingsModel>(Configuration.GetSection("VapidKeys"))
.AddSingleton(jd => jd.GetRequiredService<IOptions<PushSettingsModel>>().Value);
services.AddTransient<IEmailService, EmailService>();
services.AddTransient<IPushService, PushService>();
services.AddTransient<IUserRepository, UserRepositoryEFDatabase>();
services.AddTransient<IUserService, UserService>();
services.AddTransient<IAdapter<UserModel, User>, UserAdapter>();
services.AddTransient<IProjectRepository, ProjectRepositoryEFDatabase>();
services.AddTransient<IProjectService, ProjectService>();
services.AddTransient<IAdapter<ProjectModel, Project>, ProjectAdapter>();
services.AddTransient<IProjectFileBucketRepository, ProjectFileBucketRepositoryEFDatabase>();
services.AddTransient<IProjectFileBucketService, ProjectFileBucketService>();
services.AddTransient<IAdapter<ProjectFileBucketModel, ProjectFileBucket>, ProjectFileBucketAdapter>();
services.AddTransient<IProjectFileRepository, ProjectFileRepositoryEFDatabase>();
services.AddTransient<IProjectFileService, ProjectFileService>();
services.AddTransient<IAdapter<ProjectFileModel, ProjectFile>, ProjectFileAdapter>();
services.AddTransient<IDeviceRepository, DeviceRepositoryEFDatabase>();
services.AddTransient<IDeviceService, DeviceService>();
services.AddTransient<IAdapter<DeviceModel, Device>, DeviceAdapter>();
}
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
else
{
app.UseExceptionHandler("/Error");
// The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
app.UseHsts();
}
app.UseHttpsRedirection();
app.UseStaticFiles();
app.UseSpaStaticFiles();
app.UseMvc(routes =>
{
routes.MapRoute(
name: "default",
template: "{controller}/{action=Index}/{id?}");
});
app.UseAuthentication();
app.UseSpa(spa =>
{
// To learn more about options for serving an Angular SPA from ASP.NET Core,
// see https://go.microsoft.com/fwlink/?linkid=864501
spa.Options.SourcePath = "ClientApp";
if (env.IsDevelopment())
{
spa.UseAngularCliServer(npmScript: "start");
}
});
}
}
【问题讨论】:
-
什么都没有跳出来。你能发布你的令牌生成代码吗?
标签: c# jwt asp.net-core-2.0 claims-based-identity