【发布时间】:2019-02-01 22:01:23
【问题描述】:
我是 .net 核心的新手,我正在尝试创建实现 jwt 以进行身份验证和授权的 web api 核心。
在 Startup 类中我是这样配置的:
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)
{
services.AddDbContext<MandarinDBContext>(options =>
options.UseSqlServer(Configuration.GetConnectionString("MyConnection")));
services.AddIdentity<User, Role>()
.AddEntityFrameworkStores<MyDBContext>()
.AddDefaultTokenProviders();
services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
.AddJwtBearer(options =>
{
options.TokenValidationParameters = new TokenValidationParameters
{
ValidateIssuer = false,
ValidateAudience = false,
ValidateLifetime = true,
ValidateIssuerSigningKey = true,
ValidIssuer = "yourdomain.com",
ValidAudience = "yourdomain.com",
IssuerSigningKey = new SymmetricSecurityKey(
Encoding.UTF8.GetBytes("My secret goes here"))
};
options.RequireHttpsMetadata = false;
});
services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1);
// Add application services.
services.AddTransient<IUserService, UserService>();
}
// 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.UseHsts();
}
app.UseHttpsRedirection();
app.UseAuthentication();
app.UseMvc();
}
}
但是当我尝试调用以下操作时:
[Authorize]
[HttpGet]
[Route("api/Tokens")]
public IActionResult TestAuthorization()
{
return Ok("You're Authorized");
}
我得到 404 未找到。如果我删除 Authorize 属性它正在工作。
你能指导我解决这个问题吗?
【问题讨论】:
-
也许这可以说明一些问题:github.com/openiddict/openiddict-core/issues/498
-
如果你有 cookie authentication 可能会将你重定向到一个 Not Found 页面,没有它你只会得到一个不错的 401 - 此请求的授权已被拒绝。跨度>
标签: c# asp.net-core jwt asp.net-core-webapi