4

我正在尝试将 oauth 身份验证从 MVC 4 项目集成到 Microsoft(实时服务)。AuthConfig.cs 中的以下行已取消注释:

OAuthWebSecurity.RegisterMicrosoftClient(
            clientId: "XXX",
            clientSecret: "XXX");

而且,该应用程序已在https://manage.dev.live.com上设置

后来,当调用 OAuthWebSecurity.VerifyAuthentication 时,我返回了成功状态,但电子邮件字段不在返回的数据中。

如何请求从 Microsoft 帐户再次发出的 VerifyAuthentication 调用返回电子邮件?

谢谢。

4

1 回答 1

0

首先,您应该实现一个实现“IAuthenticationClient”接口的“MicrosoftScopedClient”类,它应该实现两种接口方法:

public class MicrosoftScopedClient : IAuthenticationClient { //在 Web.Config 文件中定义以下三个键并在代码中使用,它将保持代码的一致性。私有字符串clientId;私有字符串clientSecret;私有字符串范围;

private const string baseUrl = "https://login.live.com/oauth20_authorize.srf";
private const string tokenUrl = "https://login.live.com/oauth20_token.srf";

public void RequestAuthentication(HttpContextBase context, Uri returnUrl)
{
    //Getting values of clientId, clientSecret and scope from Web.Config file

    clientId=System.Configuration.ConfigurationManager.AppSettings["msClientId"].ToString();
    clientSecret=System.Configuration.ConfigurationManager.AppSettings["msClientSecret"].ToString();
    scope=System.Configuration.ConfigurationManager.AppSettings["msScope"].ToString();

    string url = baseUrl + "?client_id=" + clientId + "&redirect_uri=" + HttpUtility.UrlEncode(returnUrl.ToString()) + "&scope=" + HttpUtility.UrlEncode(scope) + "&response_type=code";

    //this will authenticate the user and register(only if user visited first time).
    context.Response.Redirect(url);     
}


public AuthenticationResult VerifyAuthentication(HttpContextBase context)
{
    string code = context.Request.QueryString["code"];

    string rawUrl = context.Request.Url.ToString();

    //removing code portion
    rawUrl = Regex.Replace(rawUrl, "&code=[^&]*", "");

    IDictionary<string, string> userData = GetUserData(code, rawUrl);

    if (userData == null)
        return new AuthenticationResult(false, ProviderName, null, null, null);

    string id = userData["id"];
    string username = userData["email"];    // here you'll get email id of user
    userData.Remove("id");
    userData.Remove("email");

    AuthenticationResult result = new AuthenticationResult(true, ProviderName, id, username, userData);
    return result;
}

}

////// 最后,您需要在 AuthConfig.cs 中注册所有内容,并通过我们的应用程序与 Microsoft 进行交互。OAuthWebSecurity.RegisterClient(new MicrosoftScopedClient(System.Configuration.ConfigurationManager.AppSettings["msClientId"].ToString(), System.Configuration.ConfigurationManager.AppSettings["msClientSecret"].ToString(), "wl.basic wl.emails") , "微软", null);

于 2014-08-27T13:57:33.357 回答