【问题标题】:OWIN Oauth differentiate expired and invalid tokenOWIN Oauth 区分过期和无效令牌
【发布时间】:2016-01-11 00:01:41
【问题描述】:

我在我的 ASP.NET MVC 应用程序中使用 OWIN Oauth 来为移动应用程序提供访问令牌。以下是 OAuth 的设置:

        app.UseOAuthAuthorizationServer(new OAuthAuthorizationServerOptions
        {
            TokenEndpointPath = new PathString("/api/authenticate/login"),
            Provider = dependencyContainer.GetService<IOAuthAuthorizationServerProvider>(),
            RefreshTokenProvider = dependencyContainer.GetService<IAuthenticationTokenProvider>(),
            AccessTokenExpireTimeSpan = TimeSpan.FromMinutes(applicationSettings.AccessTokenLifeTimeInMinutes),
            AllowInsecureHttp = true
        });

        app.UseOAuthBearerAuthentication(new OAuthBearerAuthenticationOptions());

如上所示,我还有自定义提供程序和自定义刷新令牌提供程序。一切正常,当来自移动设备的请求过期或无效时,我使用自定义 AuthorizeAttribute 来返回带有消息“未授权”的 json

public class ApiAuthorizeAttribute : AuthorizeAttribute
{
    protected override void HandleUnauthorizedRequest(AuthorizationContext filterContext)
    {
        filterContext.Result = new JsonResult
        {
            Data = new
            {
                success = false,
                error = "Unauthorized"
            },
            JsonRequestBehavior = JsonRequestBehavior.AllowGet
        };
    }
}

但是在一种情况下,移动应用程序需要区分来自服务器的响应有两种情况:访问令牌已过期,或访问令牌无效(例如,在中间修改)。我不确定如何实现该要求。我尝试创建一个自定义访问令牌提供程序,继承自 AuthenticationTokenProvider,在上面的 UseOAuthAuthorizationServer() 中注册它,但是在服务器时未调用 Receive() 和 ReceiveAsync()从手机接收访问令牌

【问题讨论】:

    标签: asp.net oauth owin access-token


    【解决方案1】:

    解决了这个问题。我创建自定义访问令牌提供程序的方法有效。最初我使用 UseOAuthAuthorizationServer() 注册它,但应该使用 UseOAuthBearerAuthentication() 注册它

    这是我的自定义类,以防有人需要:

    public class CustomAccessTokenProvider : AuthenticationTokenProvider
    {
        public override void Receive(AuthenticationTokenReceiveContext context)
        {
            context.DeserializeTicket(context.Token);
            var expired = context.Ticket.Properties.ExpiresUtc < DateTime.UtcNow;
            if (expired)
            {
                //If current token is expired, set a custom response header
                context.Response.Headers.Add("X-AccessTokenExpired", new string[] { "1" });
            }
    
            base.Receive(context);
        }
    }
    

    设置OWIN OAuth时注册:

    app.UseOAuthBearerAuthentication(new OAuthBearerAuthenticationOptions
                {
                    AccessTokenProvider = new CustomAccessTokenProvider()
                });
    

    【讨论】:

    • @BuiQuangHuy 是的,在 CustomAccessTokenProvider 中你可以访问 context.Response 所以你可以对响应流做任何你想做的事情
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-04-23
    • 2014-09-18
    • 1970-01-01
    • 2015-08-29
    • 2016-11-29
    相关资源
    最近更新 更多