所以我需要得到userinfo
,以便我可以检索uniqueID
对象。我找到的示例代码总是两步,发送获取代码的请求,然后使用代码和appID和appSecret来获取令牌以及userInfo对象。这个过程可以简化为一步吗?也许只是使用openID连接请求id-token,而不需要先获取代码?
protected void Page_Load(object sender, EventArgs e)
{
if (Request.Params["code"] != null)
{
var code = Request.Params["code"];
AuthenticationContext ac = new AuthenticationContext(MicrosoftAuthBaseURL);
ClientCredential clcred = new ClientCredential(MicrosoftAppId, MicrosoftAppSecret);
AuthenticationResult acResult = ac.AcquireTokenByAuthorizationCodeAsync(code, new Uri(RedirectURI), clcred).Result;
SignInUser(acResult.UserInfo.UniqueId); var accesstoken = AcquireTokenWithResource(resource: "https://graph.microsoft.com/");
Response.Write(accesstoken);
}
}
protected void Button2_Click(object sender, EventArgs e)
{
GetAuthorizationCode();
}
public void GetAuthorizationCode()
{
JObject response = new JObject();
var parameters = new Dictionary<string, string>
{
{ "response_type", "code" },
{ "client_id", "clientid" },
{ "redirect_uri", "http://localhost:8099/WebForm1.aspx" },
{ "prompt", "none"},
{ "scope", "openid"}
};
var requestUrl = string.Format("{0}/authorize?{1}", EndPointUrl, BuildQueryString(parameters));
Response.Redirect(requestUrl);
}
public string AcquireTokenWithResource(string resource)
{
var code = Request.Params["code"];
AuthenticationContext ac =
new AuthenticationContext(string.Format("https://login.microsoftonline.com/{0}", "tenantID"
));
ClientCredential clcred =
new ClientCredential("clientID", "clientSecret");
var token =
ac.AcquireTokenByAuthorizationCodeAsync(code,
new Uri("http://localhost:8099/WebForm1.aspx"), clcred,resource).Result.AccessToken;
return token;
}
private string BuildQueryString(IDictionary<string, string> parameters)
{
var list = new List<string>();
foreach (var parameter in parameters)
{
list.Add(string.Format("{0}={1}", parameter.Key, HttpUtility.UrlEncode(parameter.Value)));
}
return string.Join("&", list);
}
protected string EndPointUrl
{
get
{
return string.Format("{0}/{1}/{2}", "https://login.microsoftonline.com", "tenantID", @"oauth2/");
}
}
您可以使用id_token来获取某些用户的信息。有关详细信息,请参阅https://docs.microsoft.com/en-us/azure/active-directory/develop/id-tokens。
此外,如果你想获得id_token,你可以使用如下的API
GET https://login.microsoftonline.com/{tenant}/oauth2/v2.0/authorize?
client_id=<you app id> // Your registered Application ID
&response_type=id_tokene
&redirect_uri=<> // Your registered redirect URI, URL encoded
&response_mode=fragment // 'form_post' or 'fragment'
&scope=openid profile email // Include both 'openid' and scopes
&state=12345 // Any value, provided by your app
&nonce=678910 // Any value, provided by your app
有关详细信息,请参阅document