【发布时间】:2019-02-27 22:09:51
【问题描述】:
所以我需要获取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/");
}
}
【问题讨论】:
标签: asp.net azure azure-active-directory single-sign-on