Код: Выделить всё
public class ApiAuthenticationMiddleware
{
private readonly RequestDelegate _next;
private readonly UserManager _userManager;
private readonly SignInManager _signInManager;
public ApiAuthenticationMiddleware(RequestDelegate next,
SignInManager signInManager,
UserManager usermanager)
{
_next = next;
_signInManager = signInManager;
_userManager = usermanager;
}
public async Task Invoke(HttpContext context)
{
if (!context.Request.Query.ContainsKey("password") || !context.Request.Query.ContainsKey("email"))
{
context.Response.StatusCode = 401; //UnAuthorized
await context.Response.WriteAsync("Invalid User Key");
return;
}
var email = context.Request.Query["email"];
var password = context.Request.Query["password"];
var result = await _signInManager.PasswordSignInAsync(email, password, false, lockoutOnFailure: false);
if (result.Succeeded)
{
await _next.Invoke(context);
}
else if (//some more checks)
context.Response.StatusCode = 401; //UnAuthorized
await context.Response.WriteAsync("Invalid User Key");
return;
}
}
}
Мой соответствующий код в методе настройки в файле start.cs
Код: Выделить всё
public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
{
app.UseIdentity();
app.UseWhen(x => (x.Request.Path.StartsWithSegments("/api", StringComparison.OrdinalIgnoreCase)),
builder =>
{
builder.UseMiddleware();
});
app.UseStaticFiles();
app.UseMvc(routes =>
{
routes.MapRoute(
name: "default",
template: "{controller=Home}/{action=Index}/{id?}");
});
}
Обновить
Попробовав много вещей, я обнаружил, что когда удалил:
Код: Выделить всё
context.Response.StatusCode = 401; //UnAuthorized
Код: Выделить всё
await context.Response.WriteAsync("Invalid User Key");
Подробнее здесь: https://stackoverflow.com/questions/457 ... ank-result
Мобильная версия