UWP应用中如何获取Imgur OAuth2令牌及设置重定向URL
Great question—since Imgur has deprecated the other OAuth2 flows, setting up the implicit grant (Token response type) for UWP requires a couple of key steps around redirect URIs and handling the activation callback. Let's break this down step by step:
Step 1: Configure the Redirect URI in Imgur's Developer Console
First, you need to tell Imgur where to send users after they authorize your app:
- Log into the Imgur Developer Portal and navigate to your app's settings.
- In the Redirect URL field, enter a custom URI scheme for your UWP app (e.g.,
myimguruwp://callback). This scheme needs to be unique to your app to avoid conflicts with other applications. - Save your changes—this URI must exactly match what you use in your UWP code later.
Step 2: Register the Custom URI Scheme in Your UWP Project
Next, you need to register that same URI scheme with your UWP app so Windows knows to launch your app when Imgur redirects to it:
- Open your UWP project's
Package.appxmanifestfile. - Switch to the Declarations tab.
- From the available declarations list, select Protocol and click Add.
- In the Name field, enter the custom scheme part of your redirect URI (e.g.,
myimguruwp—leave off the://callbackpart here). - Save the manifest.
Step 3: Generate the Authorization URL & Launch the Browser
With the redirect URI set up, use the Imgur.API library to generate the authorization URL and launch it in the user's default browser:
using Imgur.API; using Imgur.API.Authentication; using Imgur.API.Enums; using Windows.System; // Initialize the Imgur client with your credentials var client = new ImgurClient("YOUR_CLIENT_ID", "YOUR_CLIENT_SECRET"); // Generate the authorization URL with Token response type, matching redirect URI, and required scopes var authUrl = client.OAuth2.GetAuthorizationUrl( OAuth2ResponseType.Token, "myimguruwp://callback", // Must match the URI in Imgur's console "public write" // Adjust scopes based on your app's needs ); // Launch the URL in the user's browser await Launcher.LaunchUriAsync(new Uri(authUrl));
Replace YOUR_CLIENT_ID and YOUR_CLIENT_SECRET with your actual Imgur app credentials.
Step 4: Handle the Redirect & Extract the Token
When the user completes authorization, Imgur will redirect to your custom URI, which activates your UWP app. You need to capture this activation and parse the token from the URI's fragment:
- Open
App.xaml.csand override theOnActivatedmethod to handle protocol activation:
using Windows.ApplicationModel.Activation; using Windows.UI.Xaml; using Windows.UI.Xaml.Controls; using System.Linq; protected override void OnActivated(IActivatedEventArgs args) { if (args.Kind == ActivationKind.Protocol) { var protocolArgs = args as ProtocolActivatedEventArgs; var callbackUri = protocolArgs.Uri; // Parse the token parameters from the URI's fragment (after the #) var fragment = callbackUri.Fragment.TrimStart('#'); var tokenParams = fragment.Split('&') .Select(param => param.Split('=')) .ToDictionary(kv => kv[0], kv => kv[1]); if (tokenParams.TryGetValue("access_token", out var accessToken)) { // Extract additional token details if needed var expiresIn = int.Parse(tokenParams["expires_in"]); var tokenType = tokenParams["token_type"]; // Securely store the token (use PasswordVault instead of LocalSettings for sensitive data!) var vault = new Windows.Security.Credentials.PasswordVault(); vault.Add(new Windows.Security.Credentials.PasswordCredential( "ImgurAuth", "AccessToken", accessToken )); // Navigate to your main page or a post-auth page Frame rootFrame = Window.Current.Content as Frame; if (rootFrame == null) { rootFrame = new Frame(); Window.Current.Content = rootFrame; } rootFrame.Navigate(typeof(MainPage)); Window.Current.Activate(); } } }
Important Notes
- Token Expiry: The implicit grant flow does not return a refresh token, so when the access token expires (after ~1 month by default), the user will need to re-authorize your app.
- Security: Never hardcode your client secret in the app if you can avoid it—though for UWP, it's a bit tricky, but you can use secure storage mechanisms like
PasswordVaultfor tokens. - Scope Matching: Ensure the scopes you request in
GetAuthorizationUrlalign with what your app actually needs (e.g.,publicfor read-only access,writefor uploading content).
内容的提问来源于stack exchange,提问作者NanoPish

