Rietveld Code Review Tool
Help | Bug tracker | Discussion group | Source code | Sign in
(25)

Delta Between Two Patch Sets: Src/GoogleApis.Auth/OAuth2/UserCredential.cs

Issue 13972043: Issue 351: Reimplement OAuth2 (Step 3 - Tests, Flows and Credential) (Closed) Base URL: https://google-api-dotnet-client.googlecode.com/hg/
Left Patch Set: Jon Skeet review Created 10 years, 9 months ago
Right Patch Set: minor Created 10 years, 9 months ago
Left:
Right:
Use n/p to move between diff chunks; N/P to move between comments. Please Sign in to add in-line comments.
Jump to:
Right: Side by side diff | Download
« no previous file with change/comment | « Src/GoogleApis.Auth/OAuth2/TokenRequestExtenstions.cs ('k') | Src/GoogleApis.Auth/Properties/AssemblyInfo.cs » ('j') | no next file with change/comment »
Toggle Intra-line Diffs ('i') | Expand Comments ('e') | Collapse Comments ('c') | Show Comments Hide Comments ('s')
LEFTRIGHT
(no file at all)
1 /*
2 Copyright 2013 Google Inc
3
4 Licensed under the Apache License, Version 2.0 (the "License");
5 you may not use this file except in compliance with the License.
6 You may obtain a copy of the License at
7
8 http://www.apache.org/licenses/LICENSE-2.0
9
10 Unless required by applicable law or agreed to in writing, software
11 distributed under the License is distributed on an "AS IS" BASIS,
12 WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 See the License for the specific language governing permissions and
14 limitations under the License.
15 */
16
17 using System;
18 using System.Net;
19 using System.Net.Http;
20 using System.Threading;
21 using System.Threading.Tasks;
22
23 using Google.Apis.Auth.OAuth2.Responses;
24 using Google.Apis.Http;
25 using Google.Apis.Logging;
26
27 namespace Google.Apis.Auth.OAuth2
28 {
29 /// <summary>
30 /// OAuth 2.0 credential for accessing protected resources using an access t oken, as well as optionally refreshing·
31 /// the access token when it expires using a refresh token.
32 /// </summary>
33 public class UserCredential : IHttpExecuteInterceptor, IHttpUnsuccessfulResp onseHandler,
34 IConfigurableHttpClientInitializer
35 {
36 private static readonly ILogger Logger = ApplicationContext.Logger.ForTy pe<UserCredential>();
37
38 private TokenResponse token;
39 private object lockObject = new object();
40
41 public TokenResponse Token
42 {
43 get
44 {
45 lock (lockObject)
46 {
47 return token;
48 }
49 }
50 private set
51 {
52 lock (lockObject)
53 {
54 token = value;
55 }
56 }
57 }
58
59 private readonly IAuthorizationCodeFlow flow;
60 private readonly string userId;
61
62 /// <summary>Constructs a new credential instance.</summary>
63 /// <param name="flow">Authorization code flow</param>
64 /// <param name="userId">User identifier</param>
65 /// <param name="token">An initial token for the user</param>
66 public UserCredential(IAuthorizationCodeFlow flow, string userId, TokenR esponse token)
67 {
68 this.flow = flow;
69 this.userId = userId;
70 this.token = token;
71 }
72
73 /// <summary>
74 /// Default implementation is to try to refresh the access token if ther e is no access token or if we are 1·
75 /// minute away from expiration. If token server is unavailable, it will try to use the access token even if·
76 /// has expired. If successful, it will call <seealso cref="IAccessMetho d.Intercept"/>.
77 /// </summary>
78 public async Task InterceptAsync(HttpRequestMessage request, Cancellatio nToken taskCancellationToken)
79 {
80 if (Token.IsExpired(flow.Clock))
81 {
82 Logger.Debug("Token has expired, trying to refresh it.");
83 if (!await RefreshTokenAsync(taskCancellationToken).ConfigureAwa it(false))
84 {
85 throw new InvalidOperationException("The access token has ex pired but we can't refresh it");
86 }
87 }
88
89 flow.AccessMethod.Intercept(request, Token.AccessToken);
90 }
91
92 /// <summary>
93 /// Refreshes the token by calling to <seealso cref="IAuthorizationCodeF low.RefreshTokenAsync"/>. Then it·
94 /// updates the <see cref="TokenResponse"/> with the new token instance.
95 /// </summary>
96 /// <param name="taskCancellationToken">Cancellation token to cancel an operation</param>
97 /// <returns><c>true</c> if the token was refreshed</returns>
98 private async Task<bool> RefreshTokenAsync(CancellationToken taskCancell ationToken)
99 {
100 if (Token.RefreshToken == null)
101 {
102 Logger.Warning("Refresh token is null, can't refresh the token!" );
103 return false;
104 }
105
106 // It's possible that two concurrent calls will be made to refresh t he token, in that case the last one·
107 // will win.
108 var newToken = await flow.RefreshTokenAsync(userId, Token.RefreshTok en, taskCancellationToken)
109 .ConfigureAwait(false);
110
111 Logger.Info("Access token was refreshed successfully");
112
113 if (newToken.RefreshToken == null)
114 {
115 newToken.RefreshToken = Token.RefreshToken;
116 }
117
118 Token = newToken;
119 return true;
120 }
121
122 public async Task<bool> HandleResponseAsync(HandleUnsuccessfulResponseAr gs args)
123 {
124 // TODO(peleyal): check WWW-Authenticate header
125 if (args.Response.StatusCode == HttpStatusCode.Unauthorized)
126 {
127 return !Object.Equals(Token.AccessToken, flow.AccessMethod.GetAc cessToken(args.Request))
128 || await RefreshTokenAsync(args.CancellationToken).Configure Await(false);
129 }
130
131 return false;
132 }
133
134 public void Initialize(ConfigurableHttpClient httpClient)
135 {
136 httpClient.MessageHandler.ExecuteInterceptors.Add(this);
137 httpClient.MessageHandler.UnsuccessfulResponseHandlers.Add(this);
138 }
139 }
140 }
LEFTRIGHT

Powered by Google App Engine
RSS Feeds Recent Issues | This issue
This is Rietveld f62528b