在setup.cs文件中找到方法
public void ConfigureServices(IServiceCollection services)
在方法中加入认证
services.AddAuthentication(authenticationOptions => authenticationOptions.DefaultScheme = "Cookies")
.AddCookie(options =>
{
options.LoginPath = "/Home/Index/";
options.Cookie.HttpOnly = true;
options.ExpireTimeSpan = TimeSpan.FromHours(1);
}).AddJwtBearer(options =>
{
options.Authority = "ExampleIssuer";
options.Audience = "ExampleAudience";
options.RequireHttpsMetadata = false;
options.IncludeErrorDetails = true;
options.TokenValidationParameters = tokenValidationParameters;
options.Events = new JwtBearerEvents
{
OnAuthenticationFailed = c =>
{
c.NoResult();
c.Response.StatusCode = 404;
c.Response.ContentType = "text/plain";
return c.Response.WriteAsync(c.Exception.ToString());
}
};
});
默认情况下使用cookie 验证,如果只是对外的接口,使用token认证,那么需要在controller加入attribute
[Authorize(AuthenticationSchemes = JwtBearerDefaults.AuthenticationScheme)]
[Route("api/[controller]")]
[ApiController]
指定controller使用Bearer来做身份认证。
一个contoller内的方法要分别使用Cookie和Bearer来认证的话,需要拆分开。否则只能有一种身份认证生效,调用另一种认证的接口会返回401。认证失败。
网友评论