私の会社にカスタム "認証"を実装する必要があります。 私は引用符で囲みます。ユーザがアプリケーションにヒットする前に技術的に認証され、そうであればuserIdがリクエストヘッダに存在するからです。クッキー認証を使用するASP.NET Core 2.0カスタムミドルウェア
私がする必要があるのは、データベースにクエリを行い、そのIDに基づいて追加のユーザー情報を取得し、アプリケーション内で簡単に使用できるようにHttpContext.Userオブジェクトを設定する方法です。
ここでは、ASP.NET Core IdentityなしでCookie認証を使用する方法について説明します。私はそのアイデアを、ユーザーのためにデータベースにクエリを行い、dbフィールドからClaimsを設定し、context.SignInAsyncを使用してCookieを作成するカスタムミドルウェアと組み合わせました。私はこのミドルウェアをapp.UseAuthentication()の前に置きます。この問題は、.Userオブジェクトが設定されていない最初の要求時に発生します.SignInメソッドはCookieを作成するだけで、.Userオブジェクトは設定しないようです。認証ミドルウェアは、最初の要求時には存在しないため、クッキーはまだ表示されません。
誰でもアイデアを提供できますか?たぶん私はそれについて間違っている、またはこのテクニックは大丈夫ですが、私はそれを動作させるために必要なものが欠けている。 Startup.csで
:
public void ConfigureServices(IServiceCollection services)
{
services.AddMvc();
services.AddAuthentication("MyAuthenticationCookie")
.AddCookie("MyAuthenticationCookie");
}
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
app.UseBrowserLink();
}
else
{
app.UseExceptionHandler("/Home/Error");
}
app.UseStaticFiles();
app.UseMyUserMiddleware();
app.UseAuthentication();
app.UseMvc(routes =>
{
routes.MapRoute(
name: "default",
template: "{controller=Home}/{action=Index}/{id?}");
});
}
カスタムミドルウェア:
public class MyUserMiddleware
{
private readonly RequestDelegate _next;
public MyUserMiddleware(RequestDelegate next)
{
_next = next;
}
public Task Invoke(HttpContext context)
{
// Sign in user if this auth cookie doesn't exist
if (context.Request.Cookies[".AspNetCore.MyAuthenticationCookie"] == null)
{
// Get user from db - not done
// Set claims from user object - put in dummy test name for now
var claims = new List<Claim>
{
new Claim(ClaimTypes.Name, "TEST"),
};
var claimsIdentity = new ClaimsIdentity(claims, "MyAuthenticationCookie");
context.SignInAsync("MyAuthenticationCookie", new ClaimsPrincipal(claimsIdentity));
}
return this._next(context);
}
}
public static class MyUserMiddlewareExtensions
{
public static IApplicationBuilder UseMyUserMiddleware(
this IApplicationBuilder builder)
{
return builder.UseMiddleware<MyUserMiddleware>();
}
}
「ユーザーは技術的に認証されてからアプリケーションにアクセスします」それはイントラネットアプリケーションのように思えます。 Windows認証を試しましたか? "userIdはリクエストヘッダーに存在します"だから、リクエストヘッダにカスタムリクエストヘッダプロパティ "x-user-id"、2があるでしょうか? whoooは何かです。 –
私はその部分の仕方を決めることはできません。 – user1560457
'Services.AddAuthentication()'と 'context.SignInAsync()'の 'MyAuthenticationCookie'を' CookieAuthenticationDefaults.AuthenticationScheme'に置き換えてみてください。そして、 '.AddCookie(options => {options.Cookie.Name =" xxxxxx ";})'にクッキーの名前を設定します。 –