Oauth2 Implicit Flow with single-page-app refreshing access tokens

后端 未结 4 1412
旧时难觅i
旧时难觅i 2021-02-01 03:29

I am using Thinktecture AuthorizationServer (AS) and it is working great.

I would like to write a native javascript single page app which can call a WebAPI directly, how

4条回答
  •  梦如初夏
    2021-02-01 03:48

    In Google o-Auth , the access token will only be valid for 1 hour, so you need to programmatically update your access token in each one hour, simple you can create web api to do so,you need to have a refresh token, and also that refresh token will not be expired , using c# code, I have done this.

     if (dateTimeDiff > 55)
                {
                    var request = (HttpWebRequest)WebRequest.Create("https://www.googleapis.com/oauth2/v3/token");
                    var postData = "refresh_token=your refresh token";
                    postData += "&client_id=your client id";
                    postData += "&client_secret=your client secrent";
                    postData += "&grant_type=refresh_token";
    
                    var data = Encoding.ASCII.GetBytes(postData);            
                    request.Method = "POST";
                    request.ContentType = "application/x-www-form-urlencoded";
                    request.ContentLength = data.Length;
                    request.UseDefaultCredentials = true;
    
                    using (var stream = request.GetRequestStream())
                    {
                        stream.Write(data, 0, data.Length);
                    }
                    var response = (HttpWebResponse)request.GetResponse();
                    string responseString = new StreamReader(response.GetResponseStream()).ReadToEnd();
    
                }
    

    you need to save the last updated date time of the access token somewhere(say in database), so that , whenever you have to make a request , so you can subtract that with current date time , if it is more than 60 minutes , you need to call the webapi to get new token .

提交回复
热议问题