You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

UWP应用中如何获取Imgur OAuth2令牌及设置重定向URL

Imgur OAuth2 (Token Response Type) Setup for UWP Apps

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.appxmanifest file.
  • 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 ://callback part 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:

  1. Open App.xaml.cs and override the OnActivated method 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 PasswordVault for tokens.
  • Scope Matching: Ensure the scopes you request in GetAuthorizationUrl align with what your app actually needs (e.g., public for read-only access, write for uploading content).

内容的提问来源于stack exchange,提问作者NanoPish

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.19 04:35:05