using System;
using System.Collections.Generic;
using System.IO;
using UnityEngine;
using Microsoft.MixedReality.Toolkit.UI;
using TMPro;
using UniRx;
using System.Net.Http;
using System.Runtime.Serialization;
using System.Runtime.Serialization.Json;
#if WINDOWS_UWP
using System.Web;
using Windows.Security.Authentication.Web;
#endif
namespace System.Runtime.CompilerServices
{
internal static class IsExternalInit { }
}
public class OpenIDConnectTest : MonoBehaviour
{
[SerializeField] private Interactable mrtkButton;
[SerializeField] private TMP_Text resultText;
<summary>
</summary>
[SerializeField]
private string tenantId = string.Empty;
<summary>
</summary>
[SerializeField]
private string clientId = string.Empty;
<summary>
</summary>
private string redirectUri = "http://localhost:50000/";
[DataContract]
private record TokenUriResponse(
[property:DataMember] string token_type,
[property:DataMember] string scope,
[property:DataMember] string expires_in,
[property:DataMember] string ext_expires_in,
[property:DataMember] string access_token,
[property:DataMember] string id_token
);
void Start()
{
mrtkButton.OnClick.AsObservable().Subscribe(_ =>
{
#if WINDOWS_UWP
UnityEngine.WSA.Application.InvokeOnUIThread(async () =>
{
var authorizeEndPoint = $"https://login.microsoftonline.com/{tenantId}/oauth2/v2.0/authorize";
var queryParameter = HttpUtility.ParseQueryString(string.Empty);
queryParameter["client_id"] = clientId;
queryParameter["response_type"] = "code";
queryParameter["redirect_uri"] = redirectUri;
queryParameter["scope"] = "openid";
var authorizeUri = new UriBuilder(authorizeEndPoint){ Query = queryParameter.ToString() }.Uri;
Uri receivedCallbackUri;
try
{
WebAuthenticationResult result =
await WebAuthenticationBroker.AuthenticateAsync(
WebAuthenticationOptions.None,
authorizeUri,
new Uri(redirectUri));
receivedCallbackUri = new Uri(result.ResponseData);
}
catch (Exception e)
{
Console.WriteLine(e);
throw;
}
var authenticationCode = HttpUtility.ParseQueryString(receivedCallbackUri.Query).Get("code");
var tokenEndPoint = $"https://login.microsoftonline.com/{tenantId}/oauth2/v2.0/token";
var httpContent = new FormUrlEncodedContent(
new Dictionary<string, string>
{
{ "client_id", clientId },
{ "scope", "openid" },
{ "code", authenticationCode },
{ "redirect_uri", redirectUri },
{ "grant_type", "authorization_code" },
});
HttpResponseMessage tokenUriResponse;
try
{
tokenUriResponse = await new HttpClient().PostAsync(tokenEndPoint, httpContent);
}
catch (Exception e)
{
Console.WriteLine(e);
throw;
}
var tokenUriResponseJson = await tokenUriResponse.Content.ReadAsStringAsync();
var serializer = new DataContractJsonSerializer(typeof(TokenUriResponse));
var tokenUriResponseData = serializer.ReadObject(
new MemoryStream(
System.Text.Encoding.UTF8.GetBytes(tokenUriResponseJson)
)
) as TokenUriResponse;
UnityEngine.WSA.Application.InvokeOnAppThread(() =>
{
resultText.text = tokenUriResponseData.id_token;
}, false);
}, false);
#endif
})
.AddTo(this);
}
}