private static async Task registerGoogleToken() { await Windows.System.Launcher.LaunchUriAsync(GoogleAuthClient.GenerateAuthURI()); var stopwatch = new Stopwatch(); stopwatch.Start(); await Task.Delay(1000); await Task.Run(() => { while (AppGlobalVariables.GoogleAuthResultUri == null || string.IsNullOrEmpty(AppGlobalVariables.GoogleAuthResultUri.AbsoluteUri)) { if (stopwatch.Elapsed > new TimeSpan(0, 5, 0)) { stopwatch.Stop(); return; } // 5 mins for auth timeout. } }); var user = await GoogleAuthClient.GetUserAndTokenFromUri(AppGlobalVariables.GoogleAuthResultUri); AccountManager.SaveUserToVault(user); AppGlobalVariables.Users.Add(user); DebugHelper.Debugger.WriteDebugLog("Successfully acquired google token."); AppGlobalVariables.GoogleAuthResultUri = null;//reset }
public virtual async Task <TokenBase> AcquireNewToken() { switch (UserType) { case UserType.Google: var newToken = await GoogleAuthClient.AcquireNewTokenWithRefreshToken(RefreshToken); AccessToken = newToken.AccessToken; TokenExpiration = TokenExpiration; newToken.RefreshToken = RefreshToken; return(newToken); case UserType.Microsoft: break; default: break; } return(null); }
public ActionResult Index() { KaribouAlpha.DAL.KaribouAlphaContext db = new DAL.KaribouAlphaContext(); GoogleAuthClient googleClient = db.GoogleAuthClients.SingleOrDefault(_google => _google.Active); if (googleClient != null) { string loginUrl = "https://accounts.google.com/o/oauth2/auth?"; string scope = "email%20profile"; StringBuilder urlBuilder = new StringBuilder(loginUrl); urlBuilder.Append("client_id=" + googleClient.ClientId); urlBuilder.Append("&redirect_uri=" + googleClient.RedirectUrl); urlBuilder.Append("&response_type=" + "code"); urlBuilder.Append("&scope=" + scope); urlBuilder.Append("&access_type=" + "offline"); urlBuilder.Append("&state=" + System.Guid.NewGuid().ToString()); return(Redirect(urlBuilder.ToString())); } ViewBag.EmailError = true; return(View("CallBack")); }
public void ConfigureOAuth(IAppBuilder app) { app.UseExternalSignInCookie(Microsoft.AspNet.Identity.DefaultAuthenticationTypes.ExternalCookie); OAuthBearerOptions = new OAuthBearerAuthenticationOptions(); OAuthAuthorizationServerOptions OAuthServerOptions = new OAuthAuthorizationServerOptions() { AllowInsecureHttp = true, TokenEndpointPath = new PathString("/token"), AuthorizeEndpointPath = new PathString("/api/Account/ExternalLogin"), AccessTokenExpireTimeSpan = TimeSpan.FromHours(24), Provider = new SimpleAuthorizationServerProvider(), RefreshTokenProvider = new SimpleRefreshTokenProvider() }; // Token Generation app.UseOAuthAuthorizationServer(OAuthServerOptions); app.UseOAuthBearerAuthentication(OAuthBearerOptions); KaribouAlpha.DAL.KaribouAlphaContext db = new DAL.KaribouAlphaContext(); LinkedInAuthClient linkedInAuthClient = db.LinkedInAuthClients.SingleOrDefault(_linked => _linked.Active); if (linkedInAuthClient != null) { ILinkedInAuthenticationProvider providerLnk = new KaribouAlpha.Authentication.LinkedInAuthenticationProvider(); LinkedInAuthenticationOptions = new LinkedInAuthenticationOptions() { ClientId = linkedInAuthClient.ClientId, ClientSecret = linkedInAuthClient.ClientSecret, Provider = providerLnk, CallbackPath = new PathString("/AuthCallBack."), Scope = { "r_basicprofile", "r_emailaddress" }, //BackchannelHttpHandler = new LinkedInBackChannelHandler() }; } //http://www.c-sharpcorner.com/article/implementing-oauth2-0-authorization-for-google-in-asp-net/ //https://developers.google.com/actions/identity/oauth2-code-flow GoogleAuthClient googleClient = db.GoogleAuthClients.SingleOrDefault(_google => _google.Active); if (googleClient != null) { GoogleAuthProvider gProvider = new GoogleAuthProvider(); googleAuthOptions = new GoogleOAuth2AuthenticationOptions() { ClientId = googleClient.ClientId, ClientSecret = googleClient.ClientSecret, Provider = gProvider }; } KaribouAlpha.Models.FaceBookClient clientFb = db.FaceBookClients.SingleOrDefault(_fb => _fb.Active); if (clientFb != null) { var fbProvider = new FacebookAuthProvider(); var facebookAuthOptions = new FacebookAuthenticationOptions() { AppId = clientFb.AppId, AppSecret = clientFb.AppSecret, Provider = fbProvider, }; app.UseFacebookAuthentication(facebookAuthOptions); } }
public async Task <ActionResult> CallBack(string state, string code) { ViewBag.EmailError = false; string path = ""; bool writeLog = false; if (System.Configuration.ConfigurationManager.AppSettings["DebugLogFile"] != null) { if (string.IsNullOrEmpty(System.Configuration.ConfigurationManager.AppSettings["DebugLogFile"].ToString()) == false) { path = System.Configuration.ConfigurationManager.AppSettings["DebugLogFile"].ToString(); writeLog = true; } } KaribouAlpha.DAL.KaribouAlphaContext db = new DAL.KaribouAlphaContext(); GoogleAuthClient googleClient = db.GoogleAuthClients.SingleOrDefault(_google => _google.Active); if (googleClient == null || (!string.IsNullOrEmpty(code) && code.ToLower() == "error")) { if (writeLog && googleClient == null) { System.IO.File.AppendAllText(path, Environment.NewLine + System.DateTime.Now.ToString() + " google client is not setup.."); } else if (writeLog) { System.IO.File.AppendAllText(path, Environment.NewLine + System.DateTime.Now.ToString() + "user may be declined code is error..."); } ViewBag.EmailError = true; return(View()); } try { if (writeLog) { System.IO.File.AppendAllText(path, Environment.NewLine + System.DateTime.Now.ToString() + "- google - start getting token from code...."); } System.Net.HttpWebRequest webRequest = (System.Net.HttpWebRequest)System.Net.WebRequest.Create("https://accounts.google.com/o/oauth2/token"); webRequest.Method = "POST"; string parameters = "code=" + code + "&client_id=" + googleClient.ClientId + "&client_secret=" + googleClient.ClientSecret + "&redirect_uri=" + googleClient.RedirectUrl + "&grant_type=authorization_code"; byte[] byteArray = Encoding.UTF8.GetBytes(parameters); webRequest.ContentType = "application/x-www-form-urlencoded"; webRequest.ContentLength = byteArray.Length; Stream postStream = webRequest.GetRequestStream(); postStream.Write(byteArray, 0, byteArray.Length); postStream.Close(); WebResponse response = webRequest.GetResponse(); postStream = response.GetResponseStream(); StreamReader reader = new StreamReader(postStream); string responseFromServer = reader.ReadToEnd(); GooglePlusAccessToken responseToken = JsonConvert.DeserializeObject <GooglePlusAccessToken>(responseFromServer); if (responseToken != null) { string accessToken = string.Empty; accessToken = responseToken.access_token; if (!string.IsNullOrEmpty(accessToken)) { Task <GoogleUserOutputData> data = GetGoogleUserInfo(accessToken); if (data != null && data.Result != null) { User user = await this._authenticationRepository.FindAsync(new Microsoft.AspNet.Identity.UserLoginInfo("Google", data.Result.id)); bool hasRegistered = user != null; bool hasCervitUser = false; long existingCervitUserId = this._authenticationRepository.FindUserExists(data.Result.email); hasCervitUser = (existingCervitUserId > 0); if (hasRegistered) { hasCervitUser = false; } ViewBag.hascervituser = hasCervitUser.ToString(); ViewBag.haslocalaccount = hasRegistered.ToString(); ViewBag.provider = "Google"; ViewBag.external_user_name = data.Result.id; ViewBag.external_access_token = accessToken; ViewBag.email = data.Result.email; } } } } catch (Exception ex) { if (writeLog) { System.IO.File.AppendAllText(path, Environment.NewLine + System.DateTime.Now.ToString() + "- google - error during getting token from code...." + ex.ToString()); } ViewBag.EmailError = true; } return(View()); }