private void ParseClaims(AuthenticationResult authenticationResult, OAuthAuthenticationParameters parameters) { var claims = new UserClaims(); claims.Contact = new ContactClaims(); if (authenticationResult.ExtraData.ContainsKey("username")) claims.Contact.Email = authenticationResult.ExtraData["username"]; claims.Name = new NameClaims(); if (authenticationResult.ExtraData.ContainsKey("name")) { var name = authenticationResult.ExtraData["name"]; if (!String.IsNullOrEmpty(name)) { var nameSplit = name.Split(new char[] { ' ' }, StringSplitOptions.RemoveEmptyEntries); if (nameSplit.Length >= 2) { claims.Name.First = nameSplit[0]; claims.Name.Last = nameSplit[1]; } else { claims.Name.Last = nameSplit[0]; } } } parameters.AddClaim(claims); }
public void ExternalLoginCallback_RedirectsTo_ExternalLoginConfirm_WhenUserIsNew() { // Arrange var mocks = new OAuthMocks(); var controller = GetController(mocks); var extraData = new Dictionary<string, string> {{"accesstoken", "providerAccessToken"}}; var authResult = new AuthenticationResult(true, PROVIDER, PROVIDER_USERID, USERNAME, extraData); var mxClient = new MxClient(new InMemoryOAuthTokenManager("a", "b")); mocks.Response.Setup(r => r.ApplyAppPathModifier(It.IsAny<string>())).Returns(RETURN_URL); mocks.OAuthWebSecurity.Setup(ows => ows.VerifyAuthentication(It.IsAny<string>())).Returns(authResult); mocks.OAuthWebSecurity.Setup(ows => ows.Login(PROVIDER, PROVIDER_USERID, false)).Returns(false); mocks.Identity.Setup(i => i.IsAuthenticated).Returns(false); mocks.OAuthWebSecurity.Setup(ows => ows.SerializeProviderUserId(PROVIDER, PROVIDER_USERID)).Returns(PROVIDER_USERID); mocks.OAuthWebSecurity.Setup(ows => ows.GetOAuthClientData(PROVIDER)).Returns(new AuthenticationClientData(mxClient, PROVIDER_DISPLAY_NAME, null)); // Act var result = controller.ExternalLoginCallback(RETURN_URL) as ViewResult; // Assert Assert.NotNull(result, "result"); Assert.AreEqual(result.ViewBag.ProviderDisplayName, PROVIDER_DISPLAY_NAME); var model = result.Model as RegisterExternalLoginModel; Assert.NotNull(model, "result"); Assert.AreEqual(model.UserName, authResult.UserName); Assert.AreEqual(model.ExternalLoginData, authResult.ProviderUserId); Assert.AreEqual(model.AccessToken, "providerAccessToken"); }
public static Task UpdateUserAsync(AuthenticationResult result) { var fb = GetUserFacebookClient(); return Task.Run(() => { Logger.InfoFormat("Performing update of user {0}", result.UserName); try { using (var db = new ShoppingListDbContext()) { UserProfile user = db.UserProfiles.FirstOrDefault(u => u.UserName.ToLower() == result.UserName.ToLower()); if (user != null) { dynamic picture = fb.Get("me", new { fields = "picture", type = "square" }); user.AccessToken = result.ExtraData.ReadField(Oauth.FieldNames.AccessToken); user.Name = result.ExtraData.ReadField(Oauth.FieldNames.Name); user.Gender = result.ExtraData.ReadField(Oauth.FieldNames.Gender); user.PictureUrl = picture.picture.data.url; db.SaveChanges(); } } } catch (Exception ex) { Logger.Error(String.Format("Update of user {0} failed.", result.UserName), ex); } }); }
public virtual AuthResult VerifyAuthentication(HttpContextBase context, Uri returnUrl) { // string str; //if (!this.ValidateRequestAgainstXsrfAttack(out str)) //{ // return new AuthenticationResult(false, this.authenticationProvider.ProviderName, null, null, null); //} var authenticationProvider = GetOpenAuthClient(); AuthenticationResult result = null; OAuth2Client oauth2Client = authenticationProvider as OAuth2Client; if (oauth2Client != null) { returnUrl = returnUrl.AttachQueryStringParameter("__provider__", this.MembershipConnect.Name);//.AttachQueryStringParameter("__sid__", str); try { result = oauth2Client.VerifyAuthentication(context, returnUrl); } catch (HttpException exception) { result = new AuthenticationResult(exception.GetBaseException(), oauth2Client.ProviderName); } } result = authenticationProvider.VerifyAuthentication(context); return new AuthResult(result.IsSuccessful, result.Provider, result.ProviderUserId, result.UserName, result.ExtraData, result.Error); }
private void HandleSuccessfullOAuth(AuthenticationResult authResult, System.Web.HttpContext context) { var providerName = authResult.Provider; var providerUserId = authResult.ProviderUserId; var provierUserName = authResult.UserName; var name = string.Empty; if (authResult.ExtraData.ContainsKey("name")) { name = authResult.ExtraData["name"]; } var userManager = UserManager.GetManager(); var currentUser = userManager.GetUsers().Where(user => user.UserName == providerUserId).FirstOrDefault(); if (currentUser == null) { var nameParts = name.Split(new string[] { " " }, StringSplitOptions.RemoveEmptyEntries); if (nameParts.Count() == 2) SystemManager.RunWithElevatedPrivilege(p => { CreateUser(providerUserId, nameParts[0], nameParts[1], provierUserName); }); else { SystemManager.RunWithElevatedPrivilege(p => { CreateUser(providerUserId, "", "", provierUserName); }); } currentUser = userManager.GetUsers().Where(user => user.UserName == providerUserId).FirstOrDefault(); } var vals = context.Request.RequestContext.RouteData.Values; var service = ((string)vals["Service"]).ToLower(); this.SetAuthCookie(currentUser); var reqMessage = RequestMessage.Empty; this.SendToken(context, currentUser, reqMessage, service); }
public User(AuthenticationResult result) { var nameParts = result.ExtraData["name"].Split(' '); UserName = result.UserName; FirstName = nameParts[0]; LastName = nameParts[1]; }
public AuthResult(AuthenticationResult result) { this.IsSuccessful = result.IsSuccessful; this.Provider = result.Provider; this.ProviderUserId = result.ProviderUserId; this.UserName = result.UserName; this.ExtraData = result.ExtraData; this.Error = result.Error; }
public ActionResult SignIn(SignInViewModel model) { if (model.ExternalAuth) return Redirect("~"); if (this.ModelState.IsValid == false) { return View(model); } var result = new AuthenticationResult(isSuccessful: true, provider: "local", providerUserId: model.HandleName, userName: model.HandleName, extraData: null); RegistUserAndIssueAuthCookie(result); return Redirect("~/"); }
private void RegistUserAndIssueAuthCookie(AuthenticationResult result) { var salt = ConfigurationManager.AppSettings["salt"]; var userExtraData = new UserExtraData { UserId = GetHashedText(string.Join("@", salt, result.ProviderUserId, result.Provider)), AccessToken = result.ExtraData["accesstoken"], AccessSecret = result.ExtraData["accesssecret"] }; var userInfoJson = JsonConvert.SerializeObject(userExtraData); var cookie = FormsAuthentication.GetAuthCookie(result.UserName, false); var ticket = FormsAuthentication.Decrypt(cookie.Value); ticket.GetType().InvokeMember("_UserData", BindingFlags.SetField | BindingFlags.NonPublic | BindingFlags.Instance, null, ticket, new object[] { userInfoJson }); cookie.Value = FormsAuthentication.Encrypt(ticket); Response.Cookies.Add(cookie); }
public AuthenticationResult VerifyAuthentication(HttpContextBase context) { try { var code = context.Request.QueryString["code"]; var accessToken = this.QueryAccessToken(UriUtilities.ConvertToAbsoluteUri(context.Request.RawUrl, context), code); var result = this.GetCustomerProfile(accessToken); AuthenticationResult authenticationResult = new AuthenticationResult(true, this.ProviderName, result["user_id"], result["name"], result); return authenticationResult; } catch (Exception ex) { AuthenticationResult authenticationResult = new AuthenticationResult(ex); return authenticationResult; } }
public AuthenticationResult VerifyAuthentication(HttpContextBase context) { string code = context.Request.QueryString["code"]; string rawUrl = context.Request.Url.ToString(); //From this we need to remove 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"]; userData.Remove("id"); userData.Remove("email"); AuthenticationResult result = new AuthenticationResult(true, ProviderName, id, username, userData); return result; }
public void AuthenticatedUser_And_NewProviderUserId_Should_UpdateAccount() { // Arrange var mocks = new OAuthMocks(); var controller = GetController(mocks); var authResult = new AuthenticationResult(true, PROVIDER, PROVIDER_USERID, USERNAME, null); mocks.Response.Setup(r => r.ApplyAppPathModifier(It.IsAny<string>())).Returns(RETURN_URL); mocks.OAuthWebSecurity.Setup(ows => ows.VerifyAuthentication(It.IsAny<string>())).Returns(authResult); mocks.OAuthWebSecurity.Setup(ows => ows.Login(PROVIDER, PROVIDER_USERID, false)).Returns(false); mocks.Identity.Setup(i => i.IsAuthenticated).Returns(true); mocks.Identity.Setup(i => i.Name).Returns(USERNAME); mocks.OAuthWebSecurity.Setup(ows => ows.CreateOrUpdateAccount(PROVIDER, PROVIDER_USERID, USERNAME)); // Act var result = controller.ExternalLoginCallback(RETURN_URL) as RedirectResult; // Assert Assert.NotNull(result, "result"); Assert.NotNull(result.Url, RETURN_URL); mocks.OAuthWebSecurity.Verify(ows => ows.CreateOrUpdateAccount(PROVIDER, PROVIDER_USERID, USERNAME), Times.Exactly(1)); }
/// <summary> /// Checks if user is successfully authenticated when user is redirected back to this user. /// </summary> /// <param name="returnUrl">The return Url which must match exactly the Url passed into RequestAuthentication() earlier.</param> /// <remarks> /// This returnUrl parameter only applies to OAuth2 providers. For other providers, it ignores the returnUrl parameter. /// </remarks> /// <returns> /// The result of the authentication. /// </returns> public AuthenticationResult VerifyAuthentication(string returnUrl) { StateDictionary state; if (!StateDictionary.TryParse(this.requestContext.Request.QueryString["state"], out state)) { return AuthenticationResult.Failed; } // check for XSRF attack string sessionId; bool successful = this.ValidateRequestAgainstXsrfAttack(out sessionId, state); if (!successful) { return new AuthenticationResult( isSuccessful: false, provider: this.authenticationProvider.ProviderName, providerUserId: null, userName: null, extraData: null); } // Only OAuth2 requires the return url value for the verify authenticaiton step OAuth2Client oauth2Client = this.authenticationProvider as OAuth2Client; AuthenticationResult result; if (oauth2Client != null) { // convert returnUrl to an absolute path Uri uri; if (!string.IsNullOrEmpty(returnUrl)) { uri = UriHelper.ConvertToAbsoluteUri(returnUrl, this.requestContext); } else { uri = this.requestContext.Request.GetPublicFacingUrl(); } try { result = oauth2Client.VerifyAuthentication(this.requestContext, uri); if (!result.IsSuccessful) { // if the result is a Failed result, creates a new Failed response which has providerName info. result = new AuthenticationResult( isSuccessful: false, provider: this.authenticationProvider.ProviderName, providerUserId: null, userName: null, extraData: null); } } catch (HttpException exception) { return new AuthenticationResult(exception.GetBaseException(), this.authenticationProvider.ProviderName); } } else { result = this.authenticationProvider.VerifyAuthentication(this.requestContext); } result.State = state; return result; }
public AuthenticationResult VerifyAuthentication(HttpContextBase context) { AuthenticationResult result = null; string verifier = context.Request.QueryString.Get("oauth_verifier"); Flickr instance = FlickrManager.GetInstance(_apiKey, _sharedSecret); OAuthRequestToken request = HttpContext.Current.Session.GetFromSession<OAuthRequestToken>(OAUTH_REQUEST_TOKEN); var authToken = instance.OAuthGetAccessToken(request, verifier); if (authToken != null) { FlickrManager.OAuthToken = authToken.Token; FlickrManager.OAuthTokenSecret = authToken.TokenSecret; result = new AuthenticationResult(true); } else { result = new AuthenticationResult(false); } return result; }
private void RegistUserAndIssueAuthCookie(AuthenticationResult result) { var salt = ConfigurationManager.AppSettings["SaltOfUserID"]; var user = new QuizWebApp.Models.User { UserId = GetHashedText(string.Join("@", salt, result.ProviderUserId, result.Provider)), IdProviderName = result.Provider, // terrible hack... Name = result.Provider != "github" ? result.UserName : result.ExtraData["login"] }; using (var db = new QuizWebApp.Models.QuizWebAppDb()) { if (db.Users.Find(user.UserId) == null) { db.Users.Add(user); db.SaveChanges(); } } var cookie = FormsAuthentication.GetAuthCookie(user.Name, false); var ticket = FormsAuthentication.Decrypt(cookie.Value); ticket.GetType().InvokeMember("_UserData", BindingFlags.SetField | BindingFlags.NonPublic | BindingFlags.Instance, null, ticket, new object[] { user.UserId }); cookie.Value = FormsAuthentication.Encrypt(ticket); Response.Cookies.Add(cookie); }
public AuthenticationResult VerifyAuthentication(IAuthenticationClient authenticationProvider, string returnUrl) { string parameterValue; // if (!this.ValidateRequestAgainstXsrfAttack(out parameterValue)) // { // return new AuthenticationResult(false, authenticationProvider.ProviderName, null, null, null); // } OAuth2Client oAuth2Client = authenticationProvider as OAuth2Client; if (oAuth2Client != null) { Uri uri = new Uri(returnUrl); // if (!string.IsNullOrEmpty(returnUrl)) // { // uri = UriHelper.ConvertToAbsoluteUri(returnUrl, HttpContext); // } // else // { // uri = MessagingUtilities.GetPublicFacingUrl(HttpContext.Request); // } // uri = uri.AttachQueryStringParameter("__provider__", authenticationProvider.ProviderName); // uri = uri.AttachQueryStringParameter("__sid__", parameterValue); AuthenticationResult result; try { AuthenticationResult authenticationResult = oAuth2Client.VerifyAuthentication(HttpContext, uri); if (!authenticationResult.IsSuccessful) { authenticationResult = new AuthenticationResult(false, authenticationProvider.ProviderName, null, null, null); } result = authenticationResult; return result; } catch (HttpException ex) { result = new AuthenticationResult(ex.GetBaseException(), authenticationProvider.ProviderName); return result; } return result; } return authenticationProvider.VerifyAuthentication(HttpContext); }
private void HandleFailureOAuth(AuthenticationResult authResult, System.Web.HttpContext context) { if (!String.IsNullOrWhiteSpace(context.Request.QueryString["redirect_url_failure"])) { context.Response.Redirect(context.Request.QueryString["redirect_url_failure"]); context.ApplicationInstance.CompleteRequest(); return; } }
public static bool IsAllowed(AuthenticationResult result) { return result.Provider == "google" && result.UserName.EndsWith("camiseteria.com"); }
public ActionResult ExternalLoginCallback(string returnUrl) { string code = Request.QueryString["code"]; string returnUrl1 = Url.Action("ExternalLoginCallback", new { ReturnUrl = returnUrl }); IDictionary<string, string> userData = new Facebook().GetUserData(code, HttpUtility.HtmlEncode(Url.Action("ExternalLoginCallback", "Account", null, Request.Url.Scheme, null))); //IDictionary<string, string> userData2 = new Facebook().GetUserData(code, HttpUtility.HtmlEncode("h" + System.Web.HttpContext.Current.Request.Url.ToString().Substring("h", "/Account") + returnUrl1)); AuthenticationResult result; // User selected yes on permissions, use custom login if (userData != null) { result = new AuthenticationResult(isSuccessful: true, provider: "facebook", providerUserId: userData["id"], userName: userData["username"], extraData: userData); } else // User selected no on permissions, use default login { result = OAuthWebSecurity.VerifyAuthentication(Url.Action("ExternalLoginCallback", new { ReturnUrl = returnUrl })); } //AuthenticationResult result = OAuthWebSecurity.VerifyAuthentication(Url.Action("ExternalLoginCallback", new { ReturnUrl = returnUrl })); if (!result.IsSuccessful) { return RedirectToAction("ExternalLoginFailure"); } // Login OAuthWebSecurity.Login(result.Provider, result.ProviderUserId, createPersistentCookie: false); // Store FBID in session Session["FBID"] = result.ProviderUserId; Session["LogInTime"] = DateTime.Now; return RedirectToLocal(returnUrl); }
/// <summary> /// Checks if user is successfully authenticated when user is redirected back to this user. /// </summary> /// <returns>The result of the authentication.</returns> public AuthenticationResult VerifyAuthentication() { AuthenticationResult result = this.authenticationProvider.VerifyAuthentication(this.requestContext); if (!result.IsSuccessful) { // if the result is a Failed result, creates a new Failed response which has providerName info. result = new AuthenticationResult( isSuccessful: false, provider: this.authenticationProvider.ProviderName, providerUserId: null, userName: null, extraData: null); } return result; }
private void SetLogOutUrl(AuthenticationResult result) { var postLogoutRedirectUrlRelativePath = ConfigurationManager.AppSettings["logout"]; if (postLogoutRedirectUrlRelativePath.StartsWith("~/")) { postLogoutRedirectUrlRelativePath = postLogoutRedirectUrlRelativePath.Substring(2); } string postLogOutUrl = string.Format("{0}://{1}{2}{3}", HttpContext.Request.Url.Scheme, HttpContext.Request.Url.Authority, Url.Content("~"), postLogoutRedirectUrlRelativePath); string idToken = result.ExtraData["idToken"]; Session["LogoutUrl"] = String.Format("{0}?id_token_hint={1}&post_logout_redirect_uri={2}", ConfigurationManager.AppSettings["endsession"], idToken, postLogOutUrl); }
/// <summary> /// Checks if user is successfully authenticated when user is redirected back to this user. /// </summary> /// <param name="returnUrl">The return Url which must match exactly the Url passed into RequestAuthentication() earlier.</param> /// <remarks> /// This returnUrl parameter only applies to OAuth2 providers. For other providers, it ignores the returnUrl parameter. /// </remarks> /// <returns> /// The result of the authentication. /// </returns> public AuthenticationResult VerifyAuthentication(string returnUrl) { // check for XSRF attack string sessionId; bool successful = this.ValidateRequestAgainstXsrfAttack(out sessionId); if (!successful) { return new AuthenticationResult( isSuccessful: false, provider: this.authenticationProvider.ProviderName, providerUserId: null, userName: null, extraData: null); } // Only OAuth2 requires the return url value for the verify authenticaiton step OAuth2Client oauth2Client = this.authenticationProvider as OAuth2Client; if (oauth2Client != null) { // convert returnUrl to an absolute path Uri uri; if (!string.IsNullOrEmpty(returnUrl)) { uri = UriHelper.ConvertToAbsoluteUri(returnUrl, this.requestContext); } else { uri = this.requestContext.Request.GetPublicFacingUrl(); } // attach the provider parameter so that we know which provider initiated // the login when user is redirected back to this page uri = uri.AttachQueryStringParameter(ProviderQueryStringName, this.authenticationProvider.ProviderName); // When we called RequestAuthentication(), we put the sessionId in the returnUrl query string. // Hence, we need to put it in the VerifyAuthentication url again to please FB/Microsoft account providers. uri = uri.AttachQueryStringParameter(SessionIdQueryStringName, sessionId); try { AuthenticationResult result = oauth2Client.VerifyAuthentication(this.requestContext, uri); if (!result.IsSuccessful) { // if the result is a Failed result, creates a new Failed response which has providerName info. result = new AuthenticationResult( isSuccessful: false, provider: this.authenticationProvider.ProviderName, providerUserId: null, userName: null, extraData: null); } return result; } catch (HttpException exception) { return new AuthenticationResult(exception.GetBaseException(), this.authenticationProvider.ProviderName); } } else { return this.authenticationProvider.VerifyAuthentication(this.requestContext); } }
/// <summary> /// Checks if user is successfully authenticated when user is redirected back to this user. /// </summary> /// <param name="returnUrl">The return Url which must match exactly the Url passed into RequestAuthentication() earlier.</param> /// <returns> /// The result of the authentication. /// </returns> public AuthenticationResult VerifyAuthentication(string returnUrl) { Requires.NotNullOrEmpty(returnUrl, "returnUrl"); // Only OAuth2 requires the return url value for the verify authenticaiton step OAuth2Client oauth2Client = this.authenticationProvider as OAuth2Client; if (oauth2Client != null) { // convert returnUrl to an absolute path Uri uri; if (!string.IsNullOrEmpty(returnUrl)) { uri = UriHelper.ConvertToAbsoluteUri(returnUrl, this.requestContext); } else { uri = this.requestContext.Request.GetPublicFacingUrl(); } AuthenticationResult result = oauth2Client.VerifyAuthentication(this.requestContext, uri); if (!result.IsSuccessful) { // if the result is a Failed result, creates a new Failed response which has providerName info. result = new AuthenticationResult( isSuccessful: false, provider: this.authenticationProvider.ProviderName, providerUserId: null, userName: null, extraData: null); } return result; } else { return this.VerifyAuthentication(); } }
public ActionResult FacebookLoginCallback(string returnUrl) { string code = Request.QueryString["code"]; string returnUrl1 = Url.Action("FacebookLoginCallback", new { ReturnUrl = returnUrl }); IDictionary<string, string> userData = new Facebook().GetUserData(code, HttpUtility.HtmlEncode("h" + System.Web.HttpContext.Current.Request.Url.ToString().Substring("h", "/Account") + returnUrl1)); AuthenticationResult result = new AuthenticationResult(isSuccessful: true, provider: "facebook", providerUserId: userData["id"], userName: userData["username"], extraData: userData); if (!result.IsSuccessful) { return RedirectToAction("ExternalLoginFailure"); } else { //futonFinder.Data.User Data.DomainModels.User.IssueAuthTicket(userData["email"], true); return RedirectToAction("Index", "Home"); } }
/// <summary> /// Checks if user is successfully authenticated when user is redirected back to this user. /// </summary> /// <param name="returnUrl">The return Url which must match exactly the Url passed into RequestAuthentication() earlier.</param> /// <param name="cancellationToken">The cancellation token.</param> /// <returns> /// The result of the authentication. /// </returns> /// <remarks> /// This returnUrl parameter only applies to OAuth2 providers. For other providers, it ignores the returnUrl parameter. /// </remarks> public async Task <AuthenticationResult> VerifyAuthenticationAsync(string returnUrl, CancellationToken cancellationToken = default(CancellationToken)) { // check for XSRF attack string sessionId; bool successful = this.ValidateRequestAgainstXsrfAttack(out sessionId); if (!successful) { return(new AuthenticationResult( isSuccessful: false, provider: this.authenticationProvider.ProviderName, providerUserId: null, userName: null, extraData: null)); } // Only OAuth2 requires the return url value for the verify authenticaiton step OAuth2Client oauth2Client = this.authenticationProvider as OAuth2Client; if (oauth2Client != null) { // convert returnUrl to an absolute path Uri uri; if (!string.IsNullOrEmpty(returnUrl)) { uri = UriHelper.ConvertToAbsoluteUri(returnUrl, this.requestContext); } else { uri = this.requestContext.Request.GetPublicFacingUrl(); } // attach the provider parameter so that we know which provider initiated // the login when user is redirected back to this page uri = uri.AttachQueryStringParameter(ProviderQueryStringName, this.authenticationProvider.ProviderName); // When we called RequestAuthentication(), we put the sessionId in the returnUrl query string. // Hence, we need to put it in the VerifyAuthentication url again to please FB/Microsoft account providers. uri = uri.AttachQueryStringParameter(SessionIdQueryStringName, sessionId); try { AuthenticationResult result = await oauth2Client.VerifyAuthenticationAsync(this.requestContext, uri, cancellationToken); if (!result.IsSuccessful) { // if the result is a Failed result, creates a new Failed response which has providerName info. result = new AuthenticationResult( isSuccessful: false, provider: this.authenticationProvider.ProviderName, providerUserId: null, userName: null, extraData: null); } return(result); } catch (HttpException exception) { return(new AuthenticationResult(exception.GetBaseException(), this.authenticationProvider.ProviderName)); } } else { return(await this.authenticationProvider.VerifyAuthenticationAsync(this.requestContext, cancellationToken)); } }