Ответ 1
Вот как мы переопределяем OwinMiddleware... сначала мы создали собственное промежуточное программное обеспечение поверх Owin... Я думаю, что у нас была аналогичная проблема, как и вы.
Сначала нужно создать константу:
public class Constants
{
public const string OwinChallengeFlag = "X-Challenge";
}
И мы переопределяем OwinMiddleware
public class AuthenticationMiddleware : OwinMiddleware
{
public AuthenticationMiddleware(OwinMiddleware next) : base(next) { }
public override async Task Invoke(IOwinContext context)
{
await Next.Invoke(context);
if (context.Response.StatusCode == 400 && context.Response.Headers.ContainsKey(Constants.OwinChallengeFlag))
{
var headerValues = context.Response.Headers.GetValues(Constants.OwinChallengeFlag);
context.Response.StatusCode = Convert.ToInt16(headerValues.FirstOrDefault());
context.Response.Headers.Remove(Constants.OwinChallengeFlag);
}
}
}
В файле startup.Auth мы допустили переопределение команд Invoke Owin
public void ConfigureAuth(IAppBuilder app)
....
app.Use<AuthenticationMiddleware>(); //Allows override of Invoke OWIN commands
....
}
И в ApplicationOAuthProvider мы изменили GrantResourceOwnerCredentials.
public override async Task GrantResourceOwnerCredentials(OAuthGrantResourceOwnerCredentialsContext context)
{
using (UserManager<IdentityUser> userManager = _userManagerFactory())
{
IdentityUser user = await userManager.FindAsync(context.UserName, context.Password);
if (user == null)
{
context.SetError("invalid_grant", "The user name or password is incorrect.");
context.Response.Headers.Add(Constants.OwinChallengeFlag, new[] { ((int)HttpStatusCode.Unauthorized).ToString() }); //Little trick to get this to throw 401, refer to AuthenticationMiddleware for more
//return;
}
....