How to create Refresh Token with External Login Provider?

前端 未结 3 792
佛祖请我去吃肉
佛祖请我去吃肉 2020-12-08 11:16

I have searched over the web and could not find a solution to my problem. I am implementing OAuth in my app. I am using ASP .NET Web API 2, and Owin. The scenario is this, o

3条回答
  •  臣服心动
    2020-12-08 11:26

    Finally found the solution for my problem. First of all, if you EVER encounter any problems with OWIN and you cannot figure out what is going wrong, I advise you to simply enable symbol-debugging and debug it. A great explanation can be found here: http://www.symbolsource.org/Public/Home/VisualStudio

    My mistake simply was, that I was calculating a wrong ExiresUtc when using external login providers. So my refreshtoken basically was always expired right away....

    If you are implementing refresh tokens, then look at this gread blog article: http://bitoftech.net/2014/07/16/enable-oauth-refresh-tokens-angularjs-app-using-asp-net-web-api-2-owin/

    And to make it work with refresh tokens for external providers, you have to set the two requried parameters ("as:clientAllowedOrigin" and "as:clientRefreshTokenLifeTime") on the context so instead of

    
     var ticket = new AuthenticationTicket(oAuthIdentity, properties);
    var context = new Microsoft.Owin.Security.Infrastructure.AuthenticationTokenCreateContext(
                        Request.GetOwinContext(), 
                        Startup.OAuthOptions.AccessTokenFormat, ticket);
    
     await Startup.OAuthOptions.RefreshTokenProvider.CreateAsync(context);
     properties.Dictionary.Add("refresh_token", context.Token);
    
    

    you need to get the client first and set the context parameters

    
        // retrieve client from database
        var client = authRepository.FindClient(client_id);
        // only generate refresh token if client is registered
        if (client != null)
        {
            var ticket = new AuthenticationTicket(oAuthIdentity, properties);
            var context = new AuthenticationTokenCreateContext(Request.GetOwinContext(), AuthConfig.OAuthOptions.RefreshTokenFormat, ticket);
            // Set this two context parameters or it won't work!!
            context.OwinContext.Set("as:clientAllowedOrigin", client.AllowedOrigin);
            context.OwinContext.Set("as:clientRefreshTokenLifeTime", client.RefreshTokenLifeTime.ToString());
    
            await AuthConfig.OAuthOptions.RefreshTokenProvider.CreateAsync(context);
            properties.Dictionary.Add("refresh_token", context.Token);
        }
    
    

提交回复
热议问题