It is probably a form post rather than a get. You will need to parse the body.
HttpListener in WinUI app doesn't catch params in link
bexolder
41
Reputation points
Hi! I try to get authorization code for Microsoft, using authorization via browser. I use HttpListener for catching redirect with code, but it's catch only redirect without parameters. In browser I saw redirect with code.
My code:
private string localhostCodeKey = "{0}/#code";
public const string RedirectScript = "<html><script type='text/javascript'>function redirect() {document.location.href = '/token?url_with_fragment=' + encodeURIComponent(document.location.href); }</script><body onload='redirect()'/></html>";
NameValueCollection queryParams;
string code = string.Empty;
if (args.RedirectUri.Contains("localhost"))
{
codeKey = string.Format(localhostCodeKey, args.RedirectUri);
}
else
{
codeKey = string.Format(codeKey, args.RedirectUri);
}
string scope = AuthUtilities.FormatMicrosoftScope(args.ScopeType, args.CustomScopes);
scope = HttpUtility.UrlEncode(scope);
string signInUri = $"{Constants.MsAuthUri}" +
$"?client_id={args.ClientId}" +
"&response_type=code" +
$"&redirect_uri={args.RedirectUri}" +
"&response_mode=fragment" +
$"&scope={scope}";
if (httpListener.IsListening)
{
httpListener?.Stop();
}
httpListener = new HttpListener();
httpListener.Prefixes.Add(args.RedirectUri + "/");
httpListener.Start();
Launcher.LaunchUriAsync(new Uri(signInUri));
var context = await httpListener.GetContextAsync();
var codeResponse = context.Response;
var buffer = Encoding.UTF8.GetBytes(Constants.RedirectScript);
codeResponse.ContentLength64 = buffer.Length;
var responseOutput = codeResponse.OutputStream;
Task responseTask = responseOutput.WriteAsync(buffer, 0, buffer.Length).ContinueWith((task) =>
{
responseOutput.Close();
httpListener.Stop();
});
queryParams = HttpUtility.ParseQueryString(context.Request.Url.AbsoluteUri);
code = queryParams[codeKey];```
`context.Request.Url.AbsoluteUri` contains only redirect uri. Similar code works fine with Google auth, I don't know what I am doing wrong.