oauth - Web API OAUTH - 区分是否识别 token 已过期或未授权

标签 oauth asp.net-web-api2 owin

我目前正在使用 Owin、Oauth、Claims 开发授权服务器。

以下是我的 Oauth 配置,我有 2 个问题

 OAuthAuthorizationServerOptions OAuthServerOptions = new OAuthAuthorizationServerOptions()
  {

     AllowInsecureHttp = true,
     TokenEndpointPath = new PathString("/token"),
     AccessTokenExpireTimeSpan = TimeSpan.FromSeconds(1000),
     Provider = new AuthorizationServerProvider()
     //RefreshTokenProvider = new SimpleRefreshTokenProvider()
  };
     app.UseOAuthAuthorizationServer(OAuthServerOptions);
     app.UseOAuthBearerAuthentication(new OAuthBearerAuthenticationOptions());

如果 token 已过期并且使用过期 token 访问的用户将获得 401(未授权) .检查使用 fiddler 。

我如何向用户发送自定义消息,说明您的 token 已过期。我需要覆盖哪个功能或模块。

我的另一个问题是下面的行有什么用?

app.UseOAuthBearerAuthentication(new OAuthBearerAuthenticationOptions());
我真的需要这个来实现吗,因为当我检查时它仍然可以在没有上述行的情况下工作。任何安全违规?

最佳答案

您不能直接自定义过期 token 的行为,但您可以使用自定义中间件来做到这一点。

首先覆盖AuthenticationTokenProvider这样您就可以在身份验证票被丢弃为过期之前拦截它。

public class CustomAuthenticationTokenProvider : AuthenticationTokenProvider
{
    public override void Receive(AuthenticationTokenReceiveContext context)
    {
        context.DeserializeTicket(context.Token);

        if (context.Ticket != null &&
            context.Ticket.Properties.ExpiresUtc.HasValue &&
            context.Ticket.Properties.ExpiresUtc.Value.LocalDateTime < DateTime.Now)
        {
            //store the expiration in the owin context so that we can read it later a middleware
            context.OwinContext.Set("custom.ExpriredToken", true);
        }
    }
}

并在 Startup 中配置它以及一个小的自定义中间件

using AppFunc = System.Func<System.Collections.Generic.IDictionary<string, object>, System.Threading.Tasks.Task>;

app.UseOAuthAuthorizationServer(OAuthServerOptions);
app.UseOAuthBearerAuthentication(new OAuthBearerAuthenticationOptions()
{
    AccessTokenProvider = new CustomAuthenticationTokenProvider()
});

//after the request has been authenticated or not
//check for our custom env setting and act accordingly
app.Use(new Func<AppFunc, AppFunc>(next => (env) =>
{
    var ctx = new OwinContext(env);
    if (ctx.Get<bool>("custom.ExpriredToken"))
    {
        //do wathever you want with the response
        ctx.Response.StatusCode = 401;
        ctx.Response.ReasonPhrase = "Token exprired";

        //terminate the request with this middleware
        return Task.FromResult(0);
    }
    else
    {
        //proceed with the rest of the middleware pipeline
        return next(env);
    }
}));

如果你注意到我在调用 UseOAuthBearerAuthentication 之后放置了自定义中间件这很重要,源于对第二个问题的回答。
OAuthBearerAuthenticationMidlleware负责认证但不负责授权。所以它只是读取 token 并填写信息,以便可以使用 IAuthenticationManager 访问它稍后在管道中。

所以是的,不管有没有它,你的所有请求都会以 401(未经授权)的形式出现,即使是那些具有有效 token 的请求。

关于oauth - Web API OAUTH - 区分是否识别 token 已过期或未授权,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32180731/

相关文章:

php - 无法使用php表单在google oauth上交换 token 的授权码

安卓:谷歌认证

oauth - Google Identity Toolkit、Google OAuth、Firebase Auth 和 Google+ 登录有什么区别

asp.net-web-api - 使用路由与查询字符串参数是错误的吗?

c# - 了解 Autofac 中间件与 ASP.NET Webforms、OWIN 和 ASP.NET Identity 的使用

c# - 究竟应该如何使用 IAppBuilder.CreatePerOwinContext<T>?

php - 如何在 PHP 中检索 SAML2 token 以从 WSO2 APIM 获取 OAuth token

javascript - Mvc WebApi OAuth token 返回

asp.net-mvc - VB.NET MVC 重载解析失败,因为没有可访问的 'Create' 接受此数量的参数

c# - Web API 响应中的自定义 404 错误消息