使用ClientId和ClientSecret进行Web API授权

Lin*_*ela 5 asp.net asp.net-web-api owin katana asp.net-mvc-5

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

流动.

我发布acess_tokenrefresh_token请求的客户端.

access_token有短暂的寿命,而refresh_token早已到期.

像往常一样,如果access_token到期,它将使用refresh_token请求另一个access_token.

现在,我的问题.由于我的refresh_token有很长的生命周期,看起来它失败了短命的access_token的目的.让我们说如果refresh_token被泄露,黑客仍然可以得到access_token,对吧?

我查看了谷歌和微软的OAuth实现,看起来他们还有这个额外的参数,你需要提供除了refresh_token.这就是client_idclient_secret.看起来它们是在API的开发者页面上登录时生成的.

现在,我如何在我的项目中实现它?我想要覆盖令牌创建并使令牌哈希基于ClientIdClientSecret.

我正在使用最新的web api的基本OWIN/Katana身份验证,我不打算使用像Thinktecture这样的其他授权服务器.我只想使用ASP.NET Web API 2默认提供的基本功能

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);
   }
}
Run Code Online (Sandbox Code Playgroud)

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);
         }
    }
}
Run Code Online (Sandbox Code Playgroud)

Fra*_*bem -2

概括 -

  1. 导航至https://console.developers.google.com/
  2. 选择一个项目。如果您没有,请创建一个。
  3. 在左侧栏的 API'S 和 AUTH 下,选择 CREDENTIALS
  4. 您应该看到您的 clientID 和 clientSecret。如果您没有看到这些,请单击创建新的客户端 ID 并完成该操作。然后应该会显示您的 clientID 和 clientSecret。

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

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