【问题标题】:How to get a oauth access token created in owin API?如何获取在 owin API 中创建的 oauth 访问令牌?
【发布时间】:2015-06-15 18:33:09
【问题描述】:

我需要提取生成的令牌并将其存储在数据库中。
OAuth 2.0 中是否有任何方法可以在发送响应之前获取生成的令牌?
或者有没有办法分析owin api发送的身份验证响应?

【问题讨论】:

    标签: c# asp.net oauth-2.0 asp.net-web-api owin


    【解决方案1】:

    如果您使用的是 Microsoft.Owin.Security.OAuth 2.1.0,那么您必须使用 Nuget 包管理器将其更新到 3.0.0(顺便说一句,我使用的是 3.1.0 并且工作正常)。 TokenEndpointResponse 和 OAuthTokenEndpointResponseContext 在 2.0 中不可用。然后使用这个函数,你会在上下文中获得价值。

    public override Task TokenEndpointResponse(OAuthTokenEndpointResponseContext context)
     {
       string token = context.AccessToken;
       return base.TokenEndpointResponse(context);
     }
    

    【讨论】:

      【解决方案2】:

      注意到还没有人回答这个问题,我自己也在寻找答案!

      终于想通了,所以这是我对 StackOverflow 的第一个贡献!

      我正在为我的 OWIN 中间件使用自定义类 (SimpleAuthProvider):

      OAuthAuthorizationServerOptions oAuthAuthorizationServerOptions = new OAuthAuthorizationServerOptions();
      oAuthAuthorizationServerOptions.TokenEndpointPath = new PathString("/api/token");
      oAuthAuthorizationServerOptions.Provider = new SimpleAuthProvider();
      

      请注意我在项目中声明的这个类:

      public class SimpleAuthProvider:OAuthAuthorizationServerProvider
      

      Microsoft.Owin.Security.OAuth 的一部分!我假设您使用的是相同的方法,但该方法在 OAuth 实现中可能是相似的。

      要获取令牌并将其存储在数据库中,请覆盖以下内容:

          public override Task TokenEndpointResponse(OAuthTokenEndpointResponseContext ctx) {
            //...get _customer database context (in my case, this happens earlier)
            _customer.LastIssuedToken = ctx.AccessToken;
            _db.SaveChanges();
            return base.TokenEndpointResponse(ctx);
          }
      

      【讨论】:

      • 谢谢邓拉维。 TokenEndpointResponse 方法在 OAuth 2 中不可用,它来自 OAuth 3。
      • 我查看了我正在使用的程序集,它是 Microsoft.Owin.Security.OAuth.dll,v3.0.1.0。所以你是对的。通过 Nuget 升级不是一种选择吗?
      • 感谢您的回答,这就是我要找的:)
      • oauth2.0 有吗?
      猜你喜欢
      • 2015-07-21
      • 1970-01-01
      • 2021-01-10
      • 1970-01-01
      • 1970-01-01
      • 2018-02-17
      • 2012-02-12
      • 2012-08-03
      • 1970-01-01
      相关资源
      最近更新 更多