最近在Piranha项目中为api设置了JWT。我可以点击登录端点(匿名),而无需食人鱼劫持该请求。
当我通过[Authorize]属性到达API端点(成功通过身份验证并接收到JWT之后)时,Piranha总是将其拾取。它会尝试将我重定向到CMS登录名。
由于这是API,因此无法重定向到网页。无论如何要纠正这种行为?
var appSettingsSection = config.GetSection("AppSettings");
services.Configure<AppSettings> (appSettingsSection);
// configure jwt authentication
var appSettings = appSettingsSection.Get<AppSettings> ();
var key = Encoding.UTF8.GetBytes (appSettings.Secret); // todo - UTF8 vs ASCII?!
services.AddAuthentication (x => {
x.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
x.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
})
.AddJwtBearer (x => {
x.RequireHttpsMetadata = false;
x.SaveToken = true;
x.TokenValidationParameters = new TokenValidationParameters {
ValidateIssuerSigningKey = true,
IssuerSigningKey = new SymmetricSecurityKey (key),
ValidateIssuer = false,
ValidateAudience = false
};
});
services.AddPiranhaApplication ();
services.AddPiranhaFileStorage ();
services.AddPiranhaImageSharp ();
services.AddPiranhaEF (options =>
options.UseSqlite ("Filename=./piranha.db"));
services.AddPiranhaIdentityWithSeed<IdentitySQLiteDb> (options =>
options.UseSqlite ("Filename=./piranha.db"));
}
services.AddPiranhaManager ();
services.AddPiranhaMemCache ();
services.AddMvc (config => {
config.ModelBinderProviders.Insert (0,
new Piranha.Manager.Binders.AbstractModelBinderProvider ());
}).SetCompatibilityVersion (CompatibilityVersion.Version_2_1);
---------更新--------- 在@hakan的帮助下,以下属性起作用:
[ApiController]
[Route ("api/v1/")]
[Produces("application/json")]
[Authorize(AuthenticationSchemes = JwtBearerDefaults.AuthenticationScheme)]
public class ApiController : ControllerBase {
答案 0 :(得分:1)
这里的问题实际上是ASP.NET Identity如何与JWT进行交互。在启动时,您的呼叫:
services.AddPiranhaIdentityWithSeed<IdentitySQLiteDb> (options =>
options.UseSqlite ("Filename=./piranha.db"));
这意味着安装程序使用Piranha设置的默认选项,其中某些选项实际上更适合开发(例如密码强度)。您可以在方法中提供自己的options
和cookie options
,如下所示:
services.AddPiranhaIdentityWithSeed<IdentitySQLiteDb> (options =>
options.UseSqlite ("Filename=./piranha.db"), identityOptions, cookieOptions);
使用的默认身份选项是:
// Password settings
options.Password.RequireDigit = false;
options.Password.RequiredLength = 6;
options.Password.RequireNonAlphanumeric = false;
options.Password.RequireUppercase = false;
options.Password.RequireLowercase = false;
options.Password.RequiredUniqueChars = 1;
// Lockout settings
options.Lockout.DefaultLockoutTimeSpan = TimeSpan.FromMinutes(30);
options.Lockout.MaxFailedAccessAttempts = 10;
options.Lockout.AllowedForNewUsers = true;
// User settings
options.User.RequireUniqueEmail = true;
这些是默认的cookie选项:
options.Cookie.HttpOnly = true;
options.ExpireTimeSpan = TimeSpan.FromMinutes(30);
options.LoginPath = "/manager/login";
options.AccessDeniedPath = "/manager/login";
options.SlidingExpiration = true;
最诚挚的问候
Håkan
答案 1 :(得分:1)
如果您仍想对 API 端点使用 Cookie 身份验证,下面的方法可行,但需要注意一些问题。要进行设置,请执行以下操作:
cookieOptions.Events.OnRedirectToLogin
添加自定义处理程序。注意事项:
withCredentials
参数设置为 true
,Axios 默认也不会发送带有 PUT/DELETE 请求的 cookie。identityOptions =>
{
// Password settings
identityOptions.Password.RequireDigit = false;
identityOptions.Password.RequiredLength = 6;
identityOptions.Password.RequireNonAlphanumeric = false;
identityOptions.Password.RequireUppercase = false;
identityOptions.Password.RequireLowercase = false;
identityOptions.Password.RequiredUniqueChars = 1;
// Lockout settings
identityOptions.Lockout.DefaultLockoutTimeSpan = TimeSpan.FromMinutes(30);
identityOptions.Lockout.MaxFailedAccessAttempts = 10;
identityOptions.Lockout.AllowedForNewUsers = true;
// User settings
identityOptions.User.RequireUniqueEmail = true;
},
cookieOptions =>
{
cookieOptions.Cookie.HttpOnly = true;
cookieOptions.ExpireTimeSpan = TimeSpan.FromMinutes(30);
cookieOptions.LoginPath = "/manager/login";
cookieOptions.AccessDeniedPath = "/manager/login";
cookieOptions.SlidingExpiration = true;
var defaultAction = cookieOptions.Events.OnRedirectToLogin;
cookieOptions.Events.OnRedirectToLogin = (context) =>
{
if (context.Request.Path.Value.StartsWith("/api"))
{
context.Response.StatusCode = 401;
context.Response.BodyWriter.WriteAsync(new ReadOnlyMemory<byte>(Encoding.ASCII.GetBytes("unauthorized.")));
return Task.CompletedTask;
}
else
{
return defaultAction(context);
}
};
});