WebAuthenticator, tokens, DelegatingHandler, token refresh.
OAuth2 on Android with WebAuthenticator
public async Task<string?> LoginWithGoogleAsync()
{
var authUrl = new Uri(
"https://accounts.google.com/o/oauth2/v2/auth?" +
"client_id=YOUR_ID&response_type=code&" +
"redirect_uri=myapp://callback&scope=openid profile email"
);
var result = await WebAuthenticator.Default
.AuthenticateAsync(authUrl, new Uri("myapp://callback"));
var code = result.Get("code");
return await ExchangeCodeForTokenAsync(code);
}
Auto-Attach Bearer Token
public class AuthHandler : DelegatingHandler
{
protected override async Task<HttpResponseMessage> SendAsync(
HttpRequestMessage req, CancellationToken ct)
{
var token = await SecureStorage.Default.GetAsync("access_token");
req.Headers.Authorization = new("Bearer", token);
return await base.SendAsync(req, ct);
}
}
Key Takeaways
WebAuthenticator handles the OAuth2 browser redirect on Android cleanly
Store the token in SecureStorage (Android Keystore), never plain Preferences
DelegatingHandler auto-attaches Bearer tokens to every outgoing request
Implement token refresh to keep users logged in beyond the access token expiry