現象
AppServiceに公開しているVue.jsで作成したWebアプリで.NetCoreIdentityによる認証を行っているが、
認証に失敗した場合に、responseとしてnoscriptタグが記載してあるHttpが返ってくる。
(ローカルでは正しく判定される)
作りとしては単純で、vue-routerのbeforeEachでバックエンドへ認証の問い合わせを行い、失敗したらログイン画面に遷移させるというコード
index.js
router.beforeEach((to, from, next) => {
authcontroller.auth()
.then((x) => {
next()
}).catch(() => {
next({ path: '/login', query: { redirect: from.fullPath } })
})
});
Startup.cs
<noscript>
<strong>We're sorry but test doesn't work properly without JavaScript enabled. Please enable it to continue.</strong>
</noscript>
原因
どうも.NetCoreIdentityの認証に失敗した場合、デフォルトではHttpStatusCode[302(Found)]が返却されるらしい。
これをAppServiceちゃんが良しなにリダイレクトしておかしくなってるっぽい。
(なぜローカルだと発生しないのかは不明)
対策
認証失敗時のレスポンスコードを指定してやれば良い
Startup.cs
public void ConfigureServices(IServiceCollection services)
{
services
.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme)
.AddCookie(options =>{
// 認証失敗時のステータスコードを変更
options.Events.OnRedirectToLogin = context =>
{
context.Response.Headers["Location"] = context.RedirectUri;
context.Response.StatusCode = 401;
return Task.CompletedTask;
};
});
}