首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >使用ClientId和ClientSecret实现Web API授权

使用ClientId和ClientSecret实现Web API授权
EN

Stack Overflow用户
提问于 2014-06-16 12:43:12
回答 1查看 10K关注 0票数 5

我在我的web api授权中使用OWIN/Katana中间件。

流程。

我正在向发出请求的客户端发出acess_tokenrefresh_token

access_token的生命周期很短,而refresh_token的生命周期很长。

通常,如果access_token过期,它将使用refresh_token请求另一个access_token。

现在,我的问题是。由于我的refresh_token具有很长的寿命,看起来它违背了短暂的access_token.Let的目的,即如果refresh_token被攻破,黑客仍然可以获得access_token,对吧?

我查看了谷歌和微软的OAuth实现,除了refresh_token之外,他们似乎还需要提供这个额外的参数。这是client_idclient_secret.它似乎是在他们登录API的开发人员页面时生成的。

现在,我如何在我的项目中实现它呢?我正在考虑覆盖令牌创建,并使令牌散列基于ClientIdClientSecret

我使用的是最新web api的基本OWIN/Katana身份验证,我不打算使用Thinktecture等其他授权服务器。我只想使用ASP.NET Web API2默认提供的基本API

Startup.OAuth.cs

public partial class Startup
{
   static Startup()
   {
      PublicClientId = "self";
      UserManagerFactory = () => new UserManager<IdentityUser>(new AppUserStore());
      var tokenExpiry = Convert.ToInt32(System.Configuration.ConfigurationManager.AppSettings["ApiTokenExpiry"]);

      OAuthOptions = new OAuthAuthorizationServerOptions
      {
          TokenEndpointPath = new PathString("/Token"),
          Provider = new ApplicationOAuthProvider(PublicClientId, UserManagerFactory),
          AuthorizeEndpointPath = new PathString("/api/Account/ExternalLogin"),
          AccessTokenExpireTimeSpan = TimeSpan.FromMinutes(tokenExpiry),
          AllowInsecureHttp = true,
          RefreshTokenProvider = new AuthenticationTokenProvider
          {
               OnCreate = CreateRefreshToken,
               OnReceive = ReceiveRefreshToken,
          }
      };
   }

   private static void CreateRefreshToken(AuthenticationTokenCreateContext context)
   {
       var tokenExpiry = Convert.ToInt32(System.Configuration.ConfigurationManager.AppSettings["ApiTokenExpiry"]);
       var refreshTokenExpiry = Convert.ToInt32(System.Configuration.ConfigurationManager.AppSettings["ApiRefreshTokenExpiry"]);

       var refreshTokenProperties = new AuthenticationProperties(context.Ticket.Properties.Dictionary)
       {
           IssuedUtc = context.Ticket.Properties.IssuedUtc,
           ExpiresUtc = DateTime.UtcNow.AddMinutes(tokenExpiry + refreshTokenExpiry) // add 3 minutes to the access token expiry
       };

       var refreshTokenTicket = new AuthenticationTicket(context.Ticket.Identity, refreshTokenProperties);

       OAuthOptions.RefreshTokenFormat.Protect(refreshTokenTicket);
       context.SetToken(context.SerializeTicket());
   }

   private static void ReceiveRefreshToken(AuthenticationTokenReceiveContext context)
   {
       context.DeserializeTicket(context.Token);
   }
}

ApplicationOAuthProvider.cs

public class ApplicationOAuthProvider : OAuthAuthorizationServerProvider
{
    private readonly string _publicClientId;
    private readonly Func<UserManager<IdentityUser>> _userManagerFactory;

    public ApplicationOAuthProvider(string publicClientId, Func<UserManager<IdentityUser>> userManagerFactory)
    {
        if (publicClientId == null)
        {
            throw new ArgumentNullException("publicClientId");
        }

        if (userManagerFactory == null)
        {
            throw new ArgumentNullException("userManagerFactory");
        }

        _publicClientId = publicClientId;
        _userManagerFactory = userManagerFactory;
    }

    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.");
                 return;
             }

             ClaimsIdentity oAuthIdentity = await userManager.CreateIdentityAsync(user,
                    context.Options.AuthenticationType);
             ClaimsIdentity cookiesIdentity = await userManager.CreateIdentityAsync(user,
                    CookieAuthenticationDefaults.AuthenticationType);
             AuthenticationProperties properties = CreateProperties(user.UserName);
             AuthenticationTicket ticket = new AuthenticationTicket(oAuthIdentity, properties);

             context.Validated(ticket);
             context.Request.Context.Authentication.SignIn(cookiesIdentity);
         }
    }
}
EN

回答 1

Stack Overflow用户

发布于 2014-07-16 13:16:06

总结--

项目导航到https://console.developers.google.com/

  • Select a

  • 。如果你没有,创建一个。在左侧栏的API'S

AUTH下,选择CREDENTIALS

  • You clientID

  • clientID

clientSecret。如果您没有看到这些,请单击create new client ID并完成该操作。然后应显示您的clientID和clientSecret。

如果您仍然不确定,请参阅此链接:https://developers.google.com/accounts/docs/OAuth2Login#getcredentials

它描述了如何同时获取clientID和clientSecret。

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/24236765

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档