在应用程序中正确设置RedirectUri,以便在OAuth2身份验证期间接收重定向。
示例代码:
// 应用程序设置
string clientId = "your_client_id";
string clientSecret = "your_client_secret";
string redirectUri = "http://your_app.com/oauth2/redirect";
// 创建认证上下文
AuthenticationContext authContext = new AuthenticationContext("https://login.microsoftonline.com/common");
// 创建代码块
CodeBlock = async () =>
{
// 通过OAuth2进行身份验证
string authUri = authContext.GetAuthorizationRequestUrlAsync(
"https://graph.microsoft.com/",
clientId,
new Uri(redirectUri),
UserIdentifier.AnyUser,
null).Result;
// 处理OAuth2回调
HttpListener http = new HttpListener();
http.Prefixes.Add(redirectUri + "/");
http.Start();
HttpListenerContext context = http.GetContext();
HttpListenerRequest request = context.Request;
HttpListenerResponse response = context.Response;
string code = request.QueryString["code"];
// 处理OAuth2回调后关闭HttpListener
response.Headers.Add("Location", "https://myapp.com/oauth2/success");
response.StatusCode = 302;
response.Close();
http.Stop();
};