In Logincontroller:
Third Party Login
Public ActionResult LogOn () { string liveurl = string. Format ( "HTTPS://LOGIN.LIVE.COM/OAUTH20_AUTHORIZE.SRF?CLIENT_ID={0}&SCOPE=WL. EMAILS&RESPONSE_TYPE=CODE&REDIRECT_URI={1}&LOCALE={2} ", this . ClientId, this . Oauthlogoncallbackurl, this . Locale); return this. Redirect (Liveurl); }
Login successful, get authorization
Public async task<actionresult> Logoncallback () {String code = this. request.querystring["Code"]; if (string. IsNullOrEmpty (code)) return Redirecttoaction ("Index", "Login"); String Tokenurl = String. Format ("https://login.live.com/oauth20_token.srf?client_id={0}&redirect_uri={1}&client_secret= {2}&code={3}&grant_type=authorization_code&locale={4} ", this. ClientId, this. Oauthlogoncallbackurl, this. Clientsecret, code, this. Locale); String liveId = String. Empty; try {liveId = await requestliveidbytoken (await Requesttoken (Tokenurl)); } catch (Exception e) {_logger. Fatal ("Unable to obtain LiveID Token", e); var result = new Viewmodels.loginresult { Success = False, ErrorMessage = "Unable to connect to login service, please try again later." " }; Return View ("Index", result); } if (!string. IsNullOrEmpty (liveId)) {var usersvc = _usersvc; if (Usersvc.currentuser = = null) {UserInfo user = Usersvc.getuserbyemail (liveId); if (user! = null && user. isenable) {return this. Dologin (user); } else {var result = new Viewmodels.loginresult {Success = false}; if (user! = null &&!user. isenable) {result. ErrorMessage = "User is forbidden to login!" "; } else {result. ErrOrmessage = "User does not exist!" "; } return View ("Index", result); }} return this. Dologin (Usersvc.currentuser); } return this. Redirecttoaction ("Index", "Login"); }
[Nonaction] Private Async task<string> requesttoken (string url) {var request = Web Request.create (URL); using (var response = await request. Getresponseasync ()) {using (var sr = new StreamReader (response). GetResponseStream ())) {var json = Sr. ReadToEnd (); Return Jsonconvert.deserializeanonymoustype (JSON, new {Access_token = ""}). Access_token; }}} [Nonaction] private Async task<string> Requestliveidbytoken (String token) {if (string. IsNullOrEmpty (token)) return string. Empty; var request = WebRequest.Create (string. Format ("https://apis.live.net/v5.0/me?access_token={0}", token)); using (var response = await request. Getresponseasync ()) {using (var sr = new StreamReader (response). GetResponseStream ())) { String json = Sr. ReadToEnd (); var Userjson = Jsonconvert.deserializeanonymoustype (JSON, new {emails = new {account = ""}}); return userJson.emails.account; } } }
Logout Login
Public ActionResult LogOff () {this . Prelogout (); String liveurl = string. Format ( "HTTPS://LOGIN.LIVE.COM/OAUTH20_LOGOUT.SRF?CLIENT_ID={0}&SCOPE=WL. EMAILS&RESPONSE_TYPE=CODE&REDIRECT_URI={1}&LOCALE={2} ", this . ClientId, this . Oauthlogoncallbackurl, this . Locale); return this. Redirect (Liveurl); }
OAuth's MVC implementation (Microsoft)