private void ProcessProviderResult() { // Process the result from an auth provider in the request ProviderName = OpenAuth.GetProviderNameFromCurrentRequest(); if (String.IsNullOrEmpty(ProviderName)) { Response.Redirect(FormsAuthentication.LoginUrl); } // Build the redirect url for OpenAuth verification var redirectUrl = "~/Account/RegisterExternalLogin"; var returnUrl = Request.QueryString["ReturnUrl"]; if (!String.IsNullOrEmpty(returnUrl)) { redirectUrl += "?ReturnUrl=" + HttpUtility.UrlEncode(returnUrl); } // Verify the OpenAuth payload var authResult = OpenAuth.VerifyAuthentication(redirectUrl); ProviderDisplayName = OpenAuth.GetProviderDisplayName(ProviderName); if (!authResult.IsSuccessful) { Title = "External login failed"; userNameForm.Visible = false; ModelState.AddModelError("Provider", String.Format("External login {0} failed.", ProviderDisplayName)); // To view this error, enable page tracing in web.config (<system.web><trace enabled="true"/></system.web>) and visit ~/Trace.axd Trace.Warn("OpenAuth", String.Format("There was an error verifying authentication with {0})", ProviderDisplayName), authResult.Error); return; } // User has logged in with provider successfully // Check if user is already registered locally if (OpenAuth.Login(authResult.Provider, authResult.ProviderUserId, createPersistentCookie: false)) { RedirectToReturnUrl(); } // Store the provider details in ViewState ProviderName = authResult.Provider; ProviderUserId = authResult.ProviderUserId; ProviderUserName = authResult.UserName; // Strip the query string from action Form.Action = ResolveUrl(redirectUrl); if (User.Identity.IsAuthenticated) { // User is already authenticated, add the external login and redirect to return url OpenAuth.AddAccountToExistingUser(ProviderName, ProviderUserId, ProviderUserName, User.Identity.Name); RedirectToReturnUrl(); } else { // User is new, ask for their desired membership name userName.Text = authResult.UserName; } }
private void ProcessProviderResult() { // Procesar el resultado de un proveedor de autenticación en la solicitud ProviderName = OpenAuth.GetProviderNameFromCurrentRequest(); if (String.IsNullOrEmpty(ProviderName)) { Response.Redirect(FormsAuthentication.LoginUrl); } // Crear la dirección URL de redirección para la comprobación de OpenAuth var redirectUrl = "~/Account/RegisterExternalLogin.aspx"; var returnUrl = Request.QueryString["ReturnUrl"]; if (!String.IsNullOrEmpty(returnUrl)) { redirectUrl += "?ReturnUrl=" + HttpUtility.UrlEncode(returnUrl); } // Comprobar la carga de OpenAuth var authResult = OpenAuth.VerifyAuthentication(redirectUrl); ProviderDisplayName = OpenAuth.GetProviderDisplayName(ProviderName); if (!authResult.IsSuccessful) { Title = "Error de inicio de sesión externo"; userNameForm.Visible = false; ModelState.AddModelError("Provider", String.Format("Error de inicio de sesión externo {0}.", ProviderDisplayName)); // Para ver este error, habilite el seguimiento de página en web.config (<system.web><trace enabled="true"/></system.web>) y visite ~/Trace.axd Trace.Warn("OpenAuth", String.Format("Error al comprobar la autenticación con {0})", ProviderDisplayName), authResult.Error); return; } // El usuario ha iniciado sesión con el proveedor correctamente // Comprobar si el usuario ya está registrado localmente if (OpenAuth.Login(authResult.Provider, authResult.ProviderUserId, createPersistentCookie: false)) { RedirectToReturnUrl(); } // Almacenar los detalles del proveedor en ViewState ProviderName = authResult.Provider; ProviderUserId = authResult.ProviderUserId; ProviderUserName = authResult.UserName; // Seccionar la cadena de consulta desde la acción Form.Action = ResolveUrl(redirectUrl); if (User.Identity.IsAuthenticated) { // El usuario ya se ha autenticado, agregue el inicio de sesión externo y redirija para volver a la dirección URL OpenAuth.AddAccountToExistingUser(ProviderName, ProviderUserId, ProviderUserName, User.Identity.Name); RedirectToReturnUrl(); } else { // El usuario es nuevo, solicitar nombres de pertenencia deseados userName.Text = authResult.UserName; } }
private void ProcessProviderResult() { // 处理请求中的身份验证提供程序返回的结果 ProviderName = OpenAuth.GetProviderNameFromCurrentRequest(); if (String.IsNullOrEmpty(ProviderName)) { Response.Redirect(FormsAuthentication.LoginUrl); } // 生成重定向 URL 以进行 OpenAuth 验证 var redirectUrl = "~/Account/RegisterExternalLogin.aspx"; var returnUrl = Request.QueryString["ReturnUrl"]; if (!String.IsNullOrEmpty(returnUrl)) { redirectUrl += "?ReturnUrl=" + HttpUtility.UrlEncode(returnUrl); } // 验证 OpenAuth 负载 var authResult = OpenAuth.VerifyAuthentication(redirectUrl); ProviderDisplayName = OpenAuth.GetProviderDisplayName(ProviderName); if (!authResult.IsSuccessful) { Title = "外部登录失败"; userNameForm.Visible = false; ModelState.AddModelError("Provider", String.Format("外部登录 {0} 失败。", ProviderDisplayName)); // 若要查看此错误,请在 web.config 中启用页跟踪(<system.web><trace enabled="true"/></system.web>),然后访问 ~/Trace.axd Trace.Warn("OpenAuth", String.Format("使用 {0}) 验证身份验证时出错", ProviderDisplayName), authResult.Error); return; } // 用户已成功地使用提供程序登录 // 检查用户是否已在本地注册 if (OpenAuth.Login(authResult.Provider, authResult.ProviderUserId, createPersistentCookie: false)) { RedirectToReturnUrl(); } // 在 ViewState 中存储提供程序详细信息 ProviderName = authResult.Provider; ProviderUserId = authResult.ProviderUserId; ProviderUserName = authResult.UserName; // 从操作中去除查询字符串 Form.Action = ResolveUrl(redirectUrl); if (User.Identity.IsAuthenticated) { // 用户已进行身份验证,请添加外部登录并重定向到返回 URL OpenAuth.AddAccountToExistingUser(ProviderName, ProviderUserId, ProviderUserName, User.Identity.Name); RedirectToReturnUrl(); } else { // 这是新用户,请要求该用户提供所需的成员名称 userName.Text = authResult.UserName; } }
public IHttpActionResult ExternalLoginCallback(string code, string state) { string ProviderName = OpenAuth.GetProviderNameFromCurrentRequest(); string username = ""; string returnURI = ""; // For future user when we integrate with other oauth2 applications if (ProviderName == null || ProviderName == "") { var nvs = Request.GetQueryNameValuePairs(); string stateParam = nvs.LastOrDefault(d => d.Key == "state").Value; if (state != null) { // We need some variables from our state parameter. NameValueCollection provideritem = HttpUtility.ParseQueryString(stateParam); if (provideritem["__provider__"] != null) { ProviderName = provideritem["__provider__"]; } if (provideritem["username"] != null) { username = provideritem["username"]; // Check to make sure username exists in database. if (!_accountRepository.Exists(d => d.UserName == username)) { return(Unauthorized()); } } // No username was provided. else { return(Unauthorized()); } if (provideritem["returnURI"] != null) { returnURI = provideritem["returnURI"]; } } else { return(BadRequest()); } } else { var nvs = Request.GetQueryNameValuePairs(); string stateParam = nvs.LastOrDefault(d => d.Key == "state").Value; if (state != null) { // We need some variables from our state parameter. NameValueCollection provideritem = HttpUtility.ParseQueryString(stateParam); if (provideritem["username"] != null) { username = provideritem["username"]; // Check to make sure username exists in database. if (!_accountRepository.Exists(d => d.UserName == username)) { return(Unauthorized()); } } // No username was provided. else { return(Unauthorized()); } if (provideritem["returnURI"] != null) { returnURI = provideritem["returnURI"]; } } else { return(BadRequest()); } } // Rewrite the request to include the requested headers and info for exchanging // the authorization code for a LinkedIn access token LinkedInOAuth2Client.RewriteRequest(); // Now that the request has been rewritten, make the call and include the same callback uri provided earlier var authResult = OpenAuth.VerifyAuthentication(_externalCallBack); // For future user when we integrate with other oauth2 applications string providerDisplayName = OpenAuth.GetProviderDisplayName(ProviderName); //If the verification process failed if (!authResult.IsSuccessful) { return(Unauthorized()); } else { //Get provider user details string providerUserId = authResult.ProviderUserId; string providerUserName = authResult.UserName; string firstName = null; string lastName = null; string accessToken = null; string email = null; if (email == null && authResult.ExtraData.ContainsKey("email-address")) { email = authResult.ExtraData["email-address"]; } if (firstName == null && authResult.ExtraData.ContainsKey("first-name")) { firstName = authResult.ExtraData["first-name"]; } if (lastName == null && authResult.ExtraData.ContainsKey("last-name")) { lastName = authResult.ExtraData["last-name"]; } if (accessToken == null && authResult.ExtraData.ContainsKey("accesstoken")) { accessToken = authResult.ExtraData["accesstoken"]; } var userInfo = new List <object>(); userInfo.Add(new { ProviderDisplayName = providerDisplayName, ProviderUserId = providerUserId, FirstName = firstName, LastName = lastName, Email = email, AccessToken = accessToken }); try { // If the given user already has a LinkedIn access token if (_linkedInAccessTokenRepository.Exists(d => d.UserName == username, d => d.Account)) { LinkedInAccessToken token = _linkedInAccessTokenRepository.GetSingle(d => d.UserName == username, d => d.Account); token.Expired = false; token.TokenCreation = DateTime.UtcNow; token.Value = accessToken; _linkedInAccessTokenRepository.Update(token); } else { LinkedInAccessToken token = new LinkedInAccessToken() { UserName = username, TokenCreation = DateTime.UtcNow, Value = accessToken }; _linkedInAccessTokenRepository.Insert(token); } } catch (Exception) { return(InternalServerError()); } if (returnURI != "null") { // Try the given redirectUri try { return(Redirect(returnURI + "?linkedin=success")); } // If it fails, go with the default catch (Exception) { return(Redirect("http://localhost:8080/Home?linkedin=success")); } } return(Redirect("http://localhost:8080/Home?linkedin=success")); } }
private void ProcessProviderResult() { // Traiter le résultat à partir d'un fournisseur d'authentification de la demande ProviderName = OpenAuth.GetProviderNameFromCurrentRequest(); if (String.IsNullOrEmpty(ProviderName)) { Response.Redirect(FormsAuthentication.LoginUrl); } // Générer l'URL de redirection pour la vérification OpenAuth var redirectUrl = "~/Account/RegisterExternalLogin"; var returnUrl = Request.QueryString["ReturnUrl"]; if (!String.IsNullOrEmpty(returnUrl)) { redirectUrl += "?ReturnUrl=" + HttpUtility.UrlEncode(returnUrl); } // Vérifier la charge utile OpenAuth var authResult = OpenAuth.VerifyAuthentication(redirectUrl); ProviderDisplayName = OpenAuth.GetProviderDisplayName(ProviderName); if (!authResult.IsSuccessful) { Title = "Échec de la connexion externe"; userNameForm.Visible = false; ModelState.AddModelError("Provider", String.Format("Échec de la connexion externe {0}.", ProviderDisplayName)); // Pour afficher cette erreur, activer le traçage des pages dans web.config (<system.web><trace enabled="true"/></system.web>) et consulter ~/Trace.axd Trace.Warn("OpenAuth", String.Format("Une erreur est survenue lors de la vérification de l'authentification avec {0})", ProviderDisplayName), authResult.Error); return; } // L'utilisateur s'est bien connecté au fournisseur // Vérifier si l'utilisateur est déjà inscrit localement if (OpenAuth.Login(authResult.Provider, authResult.ProviderUserId, createPersistentCookie: false)) { RedirectToReturnUrl(); } // Stocker les détails du fournisseur dans ViewState ProviderName = authResult.Provider; ProviderUserId = authResult.ProviderUserId; ProviderUserName = authResult.UserName; // Enlever la chaîne de requête de l'action Form.Action = ResolveUrl(redirectUrl); if (User.Identity.IsAuthenticated) { // L'utilisateur est déjà authentifié, ajouter la connexion externe et rediriger vers l'URL de renvoi OpenAuth.AddAccountToExistingUser(ProviderName, ProviderUserId, ProviderUserName, User.Identity.Name); RedirectToReturnUrl(); } else { // Il s'agit d'un nouvel utilisateur, demander quel est le nom de membre souhaité userName.Text = authResult.UserName; } }
private void ProcessProviderResult() { // Elaborare il risultato fornito da un provider di autenticazione nella richiesta ProviderName = OpenAuth.GetProviderNameFromCurrentRequest(); if (String.IsNullOrEmpty(ProviderName)) { Response.Redirect(FormsAuthentication.LoginUrl); } ProviderDisplayName = OpenAuth.GetProviderDisplayName(ProviderName); // Generare l'URL di reindirizzamento per la verifica OpenAuth var redirectUrl = "~/Account/RegisterExternalLogin"; var returnUrl = Request.QueryString["ReturnUrl"]; if (!String.IsNullOrEmpty(returnUrl)) { redirectUrl += "?ReturnUrl=" + HttpUtility.UrlEncode(returnUrl); } // Verificare il payload OpenAuth var authResult = OpenAuth.VerifyAuthentication(redirectUrl); if (!authResult.IsSuccessful) { Title = "Accesso esterno non riuscito"; userNameForm.Visible = false; ModelState.AddModelError("Provider", String.Format("Accesso esterno {0} non riuscito.", ProviderDisplayName)); // Per visualizzare questo errore, abilitare la traccia delle pagine in web.config (<system.web><trace enabled="true"/></system.web>) e visitare ~/Trace.axd Trace.Warn("OpenAuth", String.Format("Si è verificato un errore durante la verifica dell'autenticazione con {0})", ProviderDisplayName), authResult.Error); return; } // L'utente ha eseguito l'accesso con il provider // Verificare se l'utente è già registrato nel computer locale if (OpenAuth.Login(authResult.Provider, authResult.ProviderUserId, createPersistentCookie: false)) { RedirectToReturnUrl(); } // Archiviare i dati del provider in ViewState ProviderName = authResult.Provider; ProviderUserId = authResult.ProviderUserId; ProviderUserName = authResult.UserName; // Rimuovere la stringa di query dall'azione Form.Action = ResolveUrl(redirectUrl); if (User.Identity.IsAuthenticated) { // L'utente è già autenticato, aggiungere l'account di accesso esterno ed eseguire il reindirizzamento all'URL restituito OpenAuth.AddAccountToExistingUser(ProviderName, ProviderUserId, ProviderUserName, User.Identity.Name); RedirectToReturnUrl(); } else { // L'utente è nuovo, chiedere di specificare il nome di appartenenza desiderato userName.Text = authResult.UserName; } }
private void ProcessProviderResult() { // Обработка результата от поставщика проверки подлинности в запросе ProviderName = OpenAuth.GetProviderNameFromCurrentRequest(); if (String.IsNullOrEmpty(ProviderName)) { Response.Redirect(FormsAuthentication.LoginUrl); } // Построение URL-адреса перенаправления для проверки OpenAuth var redirectUrl = "~/Account/RegisterExternalLogin"; var returnUrl = Request.QueryString["ReturnUrl"]; if (!String.IsNullOrEmpty(returnUrl)) { redirectUrl += "?ReturnUrl=" + HttpUtility.UrlEncode(returnUrl); } // Проверка данных OpenAuth var authResult = OpenAuth.VerifyAuthentication(redirectUrl); ProviderDisplayName = OpenAuth.GetProviderDisplayName(ProviderName); if (!authResult.IsSuccessful) { Title = "Ошибка внешней учетной записи"; userNameForm.Visible = false; ModelState.AddModelError("Provider", String.Format("Ошибка внешней учетной записи {0}.", ProviderDisplayName)); // Чтобы просмотреть ошибку, включите трассировку страниц в файле web.config (<system.web><trace enabled="true"/></system.web>) и откройте адрес ~/Trace.axd Trace.Warn("OpenAuth", String.Format("Ошибка при проверке подлинности через {0})", ProviderDisplayName), authResult.Error); return; } // Пользователь успешно вошел через поставщика // Проверка того, не зарегистрирован ли пользователь локально if (OpenAuth.Login(authResult.Provider, authResult.ProviderUserId, createPersistentCookie: false)) { RedirectToReturnUrl(); } // Сохранение сведений о поставщике в ViewState ProviderName = authResult.Provider; ProviderUserId = authResult.ProviderUserId; ProviderUserName = authResult.UserName; // Извлечь строку запроса из действия Form.Action = ResolveUrl(redirectUrl); if (User.Identity.IsAuthenticated) { // Пользователь проверен, добавляем внешнюю учетную запись и переходим на URL-адрес возврата OpenAuth.AddAccountToExistingUser(ProviderName, ProviderUserId, ProviderUserName, User.Identity.Name); RedirectToReturnUrl(); } else { // Новый пользователь, запрашиваем желаемое имя участника userName.Text = authResult.UserName; } }
private void ProcessProviderResult() { // 要求の認証プロバイダーからの結果を処理します ProviderName = OpenAuth.GetProviderNameFromCurrentRequest(); if (String.IsNullOrEmpty(ProviderName)) { Response.Redirect(FormsAuthentication.LoginUrl); } // OpenAuth 検証のリダイレクト URL をバインドします var redirectUrl = "~/Account/RegisterExternalLogin"; var returnUrl = Request.QueryString["ReturnUrl"]; if (!String.IsNullOrEmpty(returnUrl)) { redirectUrl += "?ReturnUrl=" + HttpUtility.UrlEncode(returnUrl); } // OpenAuth ペイロードを検証します var authResult = OpenAuth.VerifyAuthentication(redirectUrl); ProviderDisplayName = OpenAuth.GetProviderDisplayName(ProviderName); if (!authResult.IsSuccessful) { Title = "外部ログインが失敗しました"; userNameForm.Visible = false; ModelState.AddModelError("Provider", String.Format("外部ログイン {0} が失敗しました。", ProviderDisplayName)); // このエラーを表示するには、web.config (<system.web><trace enabled="true"/></system.web>) でページ トレースを有効にし、~/Trace.axd にアクセスします Trace.Warn("OpenAuth", String.Format("{0} での認証の検証でエラーが発生しました)", ProviderDisplayName), authResult.Error); return; } // ユーザーはプロバイダーを使用して正常にログインしました // ユーザーが既にローカルで登録されているかどうかを確認します if (OpenAuth.Login(authResult.Provider, authResult.ProviderUserId, createPersistentCookie: false)) { RedirectToReturnUrl(); } // プロバイダーの詳細情報を ViewState に格納します ProviderName = authResult.Provider; ProviderUserId = authResult.ProviderUserId; ProviderUserName = authResult.UserName; // アクションからクエリ文字列を削除します Form.Action = ResolveUrl(redirectUrl); if (User.Identity.IsAuthenticated) { // ユーザーは既に認証されています、戻り先 URL に外部ログインとリダイレクトを追加します OpenAuth.AddAccountToExistingUser(ProviderName, ProviderUserId, ProviderUserName, User.Identity.Name); RedirectToReturnUrl(); } else { // ユーザーは新規ユーザーです、ユーザーが希望するメンバーシップ名をたずねます userName.Text = authResult.UserName; } }
private void ProcessProviderResult() { // 處理要求中驗證提供者所提供的結果 ProviderName = OpenAuth.GetProviderNameFromCurrentRequest(); if (String.IsNullOrEmpty(ProviderName)) { Response.Redirect(FormsAuthentication.LoginUrl); } // 建立重新導向 URL 以便進行 OpenAuth 驗證 var redirectUrl = "~/Account/RegisterExternalLogin"; var returnUrl = Request.QueryString["ReturnUrl"]; if (!String.IsNullOrEmpty(returnUrl)) { redirectUrl += "?ReturnUrl=" + HttpUtility.UrlEncode(returnUrl); } //驗證 OpenAuth 裝載 var authResult = OpenAuth.VerifyAuthentication(redirectUrl); ProviderDisplayName = OpenAuth.GetProviderDisplayName(ProviderName); if (!authResult.IsSuccessful) { Title = "外部登入失敗"; userNameForm.Visible = false; ModelState.AddModelError("Provider", String.Format("外部登入 {0} 失敗。", ProviderDisplayName)); // 若要檢視此錯誤,請在 web.config (<system.web><trace enabled="true"/></system.web>) 中啟用頁面追蹤並造訪 ~/Trace.axd Trace.Warn("OpenAuth", String.Format("使用 {0}) 確認驗證時發生錯誤", ProviderDisplayName), authResult.Error); return; } // 使用者已成功透過提供者登入 // 檢查使用者是否已在本機註冊 if (OpenAuth.Login(authResult.Provider, authResult.ProviderUserId, createPersistentCookie: false)) { RedirectToReturnUrl(); } // 在 ViewState 中儲存提供者詳細資料 ProviderName = authResult.Provider; ProviderUserId = authResult.ProviderUserId; ProviderUserName = authResult.UserName; // 使查詢字串脫離動作 Form.Action = ResolveUrl(redirectUrl); if (User.Identity.IsAuthenticated) { // 使用者已經過驗證,新增外部登入並重新導向以傳回 url OpenAuth.AddAccountToExistingUser(ProviderName, ProviderUserId, ProviderUserName, User.Identity.Name); RedirectToReturnUrl(); } else { // 使用者是新的,詢問其所需的成員資格名稱 userName.Text = authResult.UserName; } }
// GET: /api/auth/{provider} public HttpResponseMessage Get(string provider) { HttpResponseMessage response; var result = OpenAuth.VerifyAuthentication(VirtualPathUtility.ToAbsolute("~/api/auth/" + provider)); if (!result.IsSuccessful) { response = this.Request.CreateResponse(HttpStatusCode.Redirect); response.Headers.Location = new Uri(VirtualPathUtility.ToAbsolute("~/login?auth=failed"), UriKind.Relative); return(response); } var openAuthAccount = this.db.UserOpenAuthAccounts.SingleOrDefault(a => a.ProviderName == result.Provider && a.ProviderUserID == result.ProviderUserId); if (openAuthAccount != null) { var manager = new OpenAuthSecurityManager(new HttpContextWrapper(HttpContext.Current), OpenAuth.AuthenticationClients.GetByProviderName(result.Provider), new OpenAuthDataProvider(this.db)); if (manager.Login(result.ProviderUserId, createPersistentCookie: true)) { openAuthAccount.LastUsedDate = DateTime.UtcNow; this.db.SaveChanges(); response = this.Request.CreateResponse(HttpStatusCode.Redirect); response.Headers.Location = new Uri(VirtualPathUtility.ToAbsolute("~/"), UriKind.Relative); return(response); } } if (this.User.Identity.IsAuthenticated) { var user = this.db.Users.SingleOrDefault(u => u.UserName == this.User.Identity.Name); if (user == null) { throw new InvalidOperationException(string.Format("Cannot find a user with username '{0}'.", this.User.Identity.Name)); } var dateNow = DateTime.UtcNow; this.db.UserOpenAuthAccounts.Add(new UserOpenAuthAccount { UserID = user.UserID, ProviderName = result.Provider, ProviderUserID = result.ProviderUserId, ProviderUserName = result.UserName, LastUsedDate = dateNow }); user.LastLoginDate = dateNow; user.LastActivityDate = dateNow; this.db.SaveChanges(); response = this.Request.CreateResponse(HttpStatusCode.Redirect); response.Headers.Location = new Uri(VirtualPathUtility.ToAbsolute("~/"), UriKind.Relative); return(response); } // User is new, ask for their desired membership name var loginData = CryptoUtility.Serialize("oauth", result.Provider, result.ProviderUserId, result.UserName); var url = "~/login?providerName=" + OpenAuth.GetProviderDisplayName(result.Provider) + "&userName="******"@") ? result.UserName.Substring(0, result.UserName.IndexOf("@")) : result.UserName) + "&email=" + (result.UserName.Contains("@") ? result.UserName : string.Empty) + "&externalLoginData=" + loginData; response = this.Request.CreateResponse(HttpStatusCode.Redirect); response.Headers.Location = new Uri(VirtualPathUtility.ToAbsolute(url), UriKind.Relative); return(response); }