我的asp.net API 2有时会返回错误:该请求的授权被拒绝。奇怪的是,API在大多数情况下都可以正常工作,但是此错误发生在随机时间和随机场景以及随机端点上。
我的前端应用程序同时发出2个请求,第一个请求正常,第二个错误401,因此我可以假定令牌未过期?
我的配置如下:
// Configure the db context and user manager to use a single instance per request
app.CreatePerOwinContext(ApplicationDbContext.Create);
app.CreatePerOwinContext<ApplicationUserManager>(ApplicationUserManager.Create);
// Enable the application to use a cookie to store information for the signed in user
// and to use a cookie to temporarily store information about a user logging in with a third party login provider
app.UseCookieAuthentication(new CookieAuthenticationOptions());
app.UseExternalSignInCookie(DefaultAuthenticationTypes.ExternalCookie);
// Configure the application for OAuth based flow
PublicClientId = "self";
OAuthOptions = new OAuthAuthorizationServerOptions
{
TokenEndpointPath = new PathString("/Token"),
Provider = new ApplicationOAuthProvider(PublicClientId, null, null),
AuthorizeEndpointPath = new PathString("/api/Account/ExternalLogin"),
AccessTokenExpireTimeSpan = TimeSpan.FromMinutes(Convert.ToDouble(ConfigurationManager.AppSettings["AccessTokenExpireMinutes"])),
// In production mode set AllowInsecureHttp = false
AllowInsecureHttp = true,
RefreshTokenProvider = new ApplicationRefreshTokenProvider(),
};
// Enable the application to use bearer tokens to authenticate users
app.UseOAuthBearerTokens(OAuthOptions);
我的AuthenticationTokenProvider:
public class ApplicationRefreshTokenProvider : AuthenticationTokenProvider
{
/// <summary>
/// The create.
/// </summary>
/// <param name="context">
/// The context.
/// </param>
public override void Create(AuthenticationTokenCreateContext context)
{
// Expiration time in seconds
int expire = Convert.ToInt32(ConfigurationManager.AppSettings["RefreshAccessTokenExpireMinutes"]);
context.Ticket.Properties.ExpiresUtc = new DateTimeOffset(DateTime.Now.AddMinutes(expire));
context.SetToken(context.SerializeTicket());
}
/// <summary>
/// The receive.
/// </summary>
/// <param name="context">
/// The context.
/// </param>
public override void Receive(AuthenticationTokenReceiveContext context)
{
context.DeserializeTicket(context.Token);
}
}
我认为它与配置无关,因为这种行为是突然发生的,没有任何原因,并且无需更改身份验证实现。有什么主意我该如何调试或找出问题所在?
我在日志中找不到任何有用的信息,很难模拟错误。