首先,您应该实现一个实现“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);