public void OnFail(bool cancelled){
			OAuthResult oauthResult = new OAuthResult (OAuthResult.ResultCode.Failed, new Exception ("NOT_FINISHED"));
			if (cancelled) {
				oauthResult = new OAuthResult (OAuthResult.ResultCode.Cancelled, new Exception ("USER_CANCELLED"));
			}
			this.tcs.TrySetResult (oauthResult);
		}
Example #2
0
        public async void OnOAuthResult(OAuthResult result)
        {
            if (!string.IsNullOrEmpty(result.Code))
            {
                var res = await _httpClient.PostAsync(TokenAuthUrl,
                                                      HttpClientUtils.BuildFormParams(
                                                          new KeyValuePair <string, string>("grant_type", "authorization_code"),
                                                          new KeyValuePair <string, string>("grant_type", "authorization_code"),
                                                          new KeyValuePair <string, string>("code", result.Code),
                                                          new KeyValuePair <string, string>("client_id", _config.ClientId),
                                                          new KeyValuePair <string, string>("client_secret", _config.ClientSecret),
                                                          new KeyValuePair <string, string>("redirect_uri", RedirectUrl)
                                                          ));


                if (res.StatusCode == HttpStatusCode.OK)
                {
                    var tokenString = await res.Content.ReadAsStringAsync();

                    var tokenInfo = tokenString.FromJson <OAuthTokenResult>();
                    _logger.LogInformation(
                        $"Spotify authentication OK, token expire {DateTime.Now.AddSeconds(tokenInfo.ExpiresIn).ToString()}");
                    _config.AccessToken  = tokenInfo.AccessToken;
                    _config.TokenType    = tokenInfo.TokenType;
                    _config.ExpireOn     = DateTime.Now.AddSeconds(tokenInfo.ExpiresIn).ToLocalTime();
                    _config.RefreshToken = tokenInfo.RefreshToken;

                    _componentsService.SaveComponentConfig(_config);

                    //	RefreshTokenJob();
                    await Start();
                }
            }
        }
Example #3
0
        public ActionResult CheckEntitlement(OAuthResult result)
        {
            //get the appId from web.config
            string appId = ConfigurationManager.AppSettings["thisAppId"] == null
                ? ""
                : ConfigurationManager.AppSettings["thisAppId"];

            bool entitled = IsEntitledUser(result.oauth_user_guid, appId);

            if (entitled)
            {
                ViewBag.Message = "you are entitled to use this app.";

                UserInfo usrInfo = new UserInfo();
                usrInfo.IsLoggedIn = true;
                usrInfo.UserType   = LoginType.AutodeskId;
                usrInfo.UserId     = result.oauth_user_guid;
                usrInfo.UserName   = result.oauth_user_name;
                return(RedirectToAction("index", "Home", usrInfo));
            }
            else
            {
                ViewBag.Message = "you are not entitled to use this app. " +
                                  "please buy it from Autodesk Exchange store.";
            }

            return(View());
        }
Example #4
0
        private static async Task SaveAuthToken(AuthState authState, OAuthResult authResult)
        {
            var    idToken       = SessionToken.ParseJwtToken(authResult.id_token);
            string username      = null;
            var    userNameClaim = idToken.Claims.FirstOrDefault(x => x.Type == "upn" || x.Type == "preferred_username");

            if (userNameClaim != null)
            {
                username = userNameClaim.Value;
            }

            using (var db = new AddInContext())
            {
                var existingToken =
                    await
                    db.SessionTokens.FirstOrDefaultAsync(
                        t => t.Provider == Settings.AzureAD2Authority && t.Id == authState.stateKey);

                if (existingToken != null)
                {
                    db.SessionTokens.Remove(existingToken);
                }

                var token = new SessionToken()
                {
                    Id          = authState.stateKey,
                    CreatedOn   = DateTime.Now,
                    AccessToken = authResult.access_token,
                    Provider    = Settings.AzureAD2Authority,
                    Username    = username,
                };
                db.SessionTokens.Add(token);
                await db.SaveChangesAsync();
            }
        }
        public ActionResult AuthenticationSucceed(OAuthResult result)
        {
            //ViewBag.userId = result.oauth_user_guid;
            //return View(result);

            return(RedirectToAction("CheckEntitlement", "License", result));
        }
Example #6
0
        public ActionResult OAuth(string provider)
        {
            var providerData = _oAuthReceiverData.FirstOrDefault(r => r.ProviderName == provider);

            if (providerData != null)
            {
                var oAuthResult = new OAuthResult();
                oAuthResult.RequestUrl = HttpContext.Request.Path + HttpContext.Request.QueryString;
                var oauthReceiver = _neonManager.Resolve(providerData.ProviderType) as IOAuthReceiver;


                if (!string.IsNullOrEmpty(HttpContext.Request.Query["code"]))
                {
                    oAuthResult.Code = HttpContext.Request.Query["code"];
                }

                if (!string.IsNullOrEmpty(HttpContext.Request.Query["token"]))
                {
                    oAuthResult.Token = HttpContext.Request.Query["token"];
                }

                if (!string.IsNullOrEmpty(HttpContext.Request.Query["status"]))
                {
                    oAuthResult.Status = HttpContext.Request.Query["status"];
                }

                oauthReceiver?.OnOAuthReceived(providerData.ProviderName, oAuthResult);
                return(Ok("ok"));
            }

            return(NotFound("oAuth Receiver not found!"));
        }
        private static async Task SaveAuthToken(AuthState authState, OAuthResult authResult)
        {
            using (var db = new AddInContext())
            {
                var existingToken =
                    await
                    db.SessionTokens.FirstOrDefaultAsync(
                        t => t.Provider == Settings.GoogleAuthority && t.Id == authState.stateKey);

                if (existingToken != null)
                {
                    db.SessionTokens.Remove(existingToken);
                }
                string username   = null;
                var    jwt        = SessionToken.ParseJwtToken(authResult.id_token);
                var    emailClaim = jwt.Claims.FirstOrDefault(c => c.Type == "email");
                if (emailClaim != null)
                {
                    username = emailClaim.Value;
                }

                var token = new SessionToken()
                {
                    Id          = authState.stateKey,
                    CreatedOn   = DateTime.Now,
                    AccessToken = authResult.access_token,
                    Provider    = Settings.GoogleAuthority,
                    Username    = username,
                };
                db.SessionTokens.Add(token);
                await db.SaveChangesAsync();
            }
        }
        private async Task <bool> GetTokenCredentials()
        {
            // var result = new EmbedConfig { Username = username, Roles = roles };
            var error = GetWebConfigErrors();

            if (error != null)
            {
                m_embedConfig.ErrorMessage = error;
                return(false);
            }

            // Authenticate using created credentials
            OAuthResult authenticationResult = null;

            try
            {
                authenticationResult = await DoAuthentication();
            }
            catch (AggregateException exc)
            {
                m_embedConfig.ErrorMessage = exc.InnerException.Message;
                return(false);
            }

            if (authenticationResult == null)
            {
                m_embedConfig.ErrorMessage = "Authentication Failed.";
                return(false);
            }

            m_tokenCredentials = new TokenCredentials(authenticationResult.AccessToken, "Bearer");
            return(true);
        }
        private static async Task SaveAuthToken(AuthState authState, OAuthResult authResult, FacebookUserProfile userProfile)
        {
            using (var db = new AddInContext())
            {
                var existingToken =
                    await
                    db.SessionTokens.FirstOrDefaultAsync(
                        t => t.Provider == Settings.FacebookAuthority && t.Id == authState.stateKey);

                if (existingToken != null)
                {
                    db.SessionTokens.Remove(existingToken);
                }

                var token = new SessionToken()
                {
                    Id          = authState.stateKey,
                    CreatedOn   = DateTime.Now,
                    AccessToken = authResult.access_token,
                    Provider    = Settings.FacebookAuthority,
                    Username    = userProfile.id,
                };
                db.SessionTokens.Add(token);
                await db.SaveChangesAsync();
            }
        }
        public async Task <ActionResult> Authorize()
        {
            var authStateString = Request.QueryString["state"];
            var authState       = JsonConvert.DeserializeObject <AuthState>(authStateString);

            try
            {
                // Get the token.
                var authCode = Request.Params["code"];
                var url      = "https://graph.facebook.com/v2.3/oauth/access_token?" +
                               $"client_id={Settings.FacebookClientId}" +
                               $"&redirect_uri={loginRedirectUri}/" +
                               $"&client_secret={Settings.FacebookClientSecret}" +
                               $"&code={authCode}";

                authState.authStatus = "failure";

                using (var client = new HttpClient())
                {
                    OAuthResult oauthResult = null;
                    //Facebook uses a GET rather than a POST
                    using (var response = await client.GetAsync(url))
                    {
                        if (response.IsSuccessStatusCode)
                        {
                            var result = await response.Content.ReadAsStringAsync();

                            oauthResult          = JsonConvert.DeserializeObject <OAuthResult>(result);
                            authState.authStatus = "success";
                        }
                    }

                    if (oauthResult != null && authState.authStatus == "success")
                    {
                        url = $"https://graph.facebook.com/v2.5/me?access_token={oauthResult.access_token}&fields=name%2Cid%2Cemail%2Cfirst_name%2Clast_name&format=json";
                        using (var response = await client.GetAsync(url))
                        {
                            if (response.IsSuccessStatusCode)
                            {
                                var result = await response.Content.ReadAsStringAsync();

                                var userData = JsonConvert.DeserializeObject <FacebookUserProfile>(result);
                                await SaveAuthToken(authState, oauthResult, userData);
                            }
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                System.Diagnostics.Trace.WriteLine(ex.ToString());
                authState.authStatus = "failure";
            }

            return(RedirectToAction(nameof(AuthorizeComplete), new { authState = JsonConvert.SerializeObject(authState) }));
        }
        public void OnFail(bool cancelled)
        {
            OAuthResult oauthResult = new OAuthResult(OAuthResult.ResultCode.FAILED, new Exception("NOT_FINISHED"));

            if (cancelled)
            {
                oauthResult = new OAuthResult(OAuthResult.ResultCode.CANCELLED, new Exception("USER_CANCELLED"));
            }
            this.tcs.TrySetResult(oauthResult);
        }
        public RedirectToRouteResult AuthCallback()
        {
            string qry  = System.Web.HttpContext.Current.Request.Url.Query;
            var    qstr = HttpUtility.ParseQueryString(qry);

            string verifier = qstr["oauth_verifier"];

            if (null == verifier || verifier.Length == 0)
            {
                return(RedirectToAction("AuthenticationFailed",
                                        new { reason = "Invalid PIN." }));
            }

            // Build the HTTP request for an access token
            var request = new RestRequest("OAuth/AccessToken", Method.POST);

            m_Client.Authenticator = OAuth1Authenticator.ForAccessToken(
                Constants.CONSUMER_KEY,
                Constants.CONSUMER_SECRET,
                m_oAuthReqToken,
                m_oAuthReqTokenSecret,
                verifier);

            // Execute the access token request
            var response = m_Client.Execute(request);

            // The request for access token is successful. Parse the response
            // and store token,token secret and session handle
            var qs = HttpUtility.ParseQueryString(response.Content);

            m_oAuthAccessToken       = qs["oauth_token"];
            m_oAuthAccessTokenSecret = qs["oauth_token_secret"];
            var x_oauth_user_name   = qs["x_oauth_user_name"];
            var x_oauth_user_guid   = qs["x_oauth_user_guid"];
            var x_scope             = qs["x_scope"];
            var xoauth_problem      = qs["xoauth_problem"];
            var oauth_error_message = qs["oauth_error_message"];

            m_sessionHandle = qs["oauth_session_handle"];

            OAuthResult result = new OAuthResult();

            result.AccessToken         = m_oAuthAccessToken;
            result.AccessTokenSecret   = m_oAuthAccessTokenSecret;
            result.oauth_user_name     = x_oauth_user_name;
            result.oauth_user_guid     = x_oauth_user_guid;
            result.scope               = x_scope;
            result.oauth_problem       = xoauth_problem;
            result.oauth_error_message = oauth_error_message;
            result.sessionHandle       = m_sessionHandle;

            return(RedirectToAction("AuthenticationSucceed", "Authenticate", result));
        }
        internal override OAuthRegisterData Execute(OAuthResult result)
        {
            var loginData = GetLoginData(result);
            var username  = result.ExtraData["name"];

            return(new OAuthRegisterData
            {
                Username = username,
                Email = result.UserName,
                ExternalLoginData = loginData
            });
        }
        internal override OAuthRegisterData Execute(OAuthResult result)
        {
            var loginData = GetLoginData(result);
            var username  = string.Format("{0} {1}", result.ExtraData["firstName"], result.ExtraData["lastName"]);

            return(new OAuthRegisterData
            {
                Username = username,
                Email = result.UserName,
                ExternalLoginData = loginData
            });
        }
        public async Task <IOAuthResult> AuthenticateUser(string username, string password)
        {
            if (username != null && password != null && username.Trim() != string.Empty && password.Trim() != string.Empty)
            {
                var client = new HttpClient();
                var url    = new UrlBuilder(ApiConstants.BaseUrl).Append(ApiConstants.ApiUrl)
                             .Append(ApiConstants.Authenticate).ToString();

                var model = new UserDto
                {
                    UserName = username,
                    Password = password
                };

                var json = JsonConvert.SerializeObject(model);

                HttpContent httpContent = new StringContent(json);

                httpContent.Headers.ContentType = new MediaTypeHeaderValue("application/json");

                var response = await client.PostAsync(url, httpContent).ConfigureAwait(false);

                if (response != null)
                {
                    if (response.IsSuccessStatusCode)
                    {
                        var result = response.Content.ReadAsStringAsync().Result;
                        try
                        {
                            var r = new OAuthResult
                            {
                                StatusCode = response.StatusCode,
                                Status     = response.Content.ToString(),
                                Token      = JsonConvert.DeserializeObject <OAuthToken>(result)
                            };

                            return(r);
                        }
                        catch
                        {
                        }
                    }
                    else
                    {
                        var error = JsonConvert.DeserializeObject <OAuthError>(response.Content.ReadAsStringAsync().Result);
                        return(new OAuthResult {
                            StatusCode = response.StatusCode, Status = error.Description, Token = null
                        });
                    }
                }
            }
            return(null);
        }
			public override void OnReceive(Context context, Intent intent)
			{
				this.parent.logger.d (OAuthClientHandlerService.LOG_TAG, "recieved event, data: " + intent.GetStringExtra ("url"), null);
				string data = intent.GetStringExtra ("url");
				if ("NOT_FINISHED".Equals (data)) {
					OAuthResult oauthResult = new OAuthResult (OAuthResult.ResultCode.Failed, new Exception ("NOT_FINISHED"));
					this.parent.tcs.TrySetResult (oauthResult);
				} else if ("CANCELLED".Equals (data)) {
					OAuthResult oauthResult = new OAuthResult (OAuthResult.ResultCode.Cancelled, new Exception ("USER_CANCELLED"));
					this.parent.tcs.TrySetResult (oauthResult);
				} else {
					this.parent.appContext.UnregisterReceiver (this.parent.receiver);
					OnSuccess (new Uri (data), this.parent.tcs);
				}
			}
Example #17
0
        public async void OnOAuthReceived(string provider, OAuthResult result)
        {
            if (!string.IsNullOrEmpty(result.Code))
            {
                var response = _remoteAuthentication.ProcessAuthorizeResponse(result.RequestUrl);

                var token = await _remoteAuthentication.GetToken(response.Code);

                var vault = LoadVault <PhilipHueVault>();
                vault.AccessToken = token;

                SaveVault(vault);

                InitToken();
            }
        }
        private async Task <UserInfo> UnsafeLoginWithXToken(string xToken)
        {
            _logger.Method().Start(xToken.LastSymbols(4));

            var xTokenData = new Dictionary <string, string>
            {
                { "grant_type", "x-token" },
                { "client_id", _clientId },
                { "client_secret", _clientSecret },
                { "access_token", xToken }
            };

            OAuthResult resultWithOauthToken = await OAuthRequest(xTokenData);

            UserInfo userInfo = await InternalGetUserInfo(resultWithOauthToken.AccessToken, xToken);

            return(userInfo.RetWithLog(_logger).Log());
        }
Example #19
0
        public OAuthResult GetOAuthResultFromRequest(string returnUrl)
        {
            AuthenticationResult result = OAuthWebSecurity.VerifyAuthentication(returnUrl);
            var oAuth = new OAuthResult();

            if (!result.IsSuccessful)
            {
                return(oAuth);
            }

            oAuth.IsValid             = true;
            oAuth.UserName            = result.UserName;
            oAuth.Provider            = result.Provider;
            oAuth.ProviderUserId      = result.ProviderUserId;
            oAuth.ProviderDisplayName = OAuthWebSecurity.GetOAuthClientData(result.Provider).DisplayName;
            oAuth.EncryptedLoginData  = EncryptProviderData(result.Provider, result.ProviderUserId);

            return(oAuth);
        }
Example #20
0
        public async Task <OAuthResult> AuthenticateAsync()
        {
            if (_cachedResult != null)
            {
                var expireDateTime  = DateTimeOffset.FromUnixTimeSeconds(_cachedResult.ExpiresOn);
                var currentDateTime = DateTimeOffset.Now.UtcDateTime;

                if (currentDateTime < expireDateTime)
                {
                    return(_cachedResult);
                }
            }

            OAuthResult authToken = await GetAuthToken();

            _cachedResult = authToken;

            return(authToken);
        }
            public override void OnReceive(Context context, Intent intent)
            {
                this.parent.logger.d(OAuthClientHandlerService.LOG_TAG, "recieved event, data: " + intent.GetStringExtra("url"), null);
                string data = intent.GetStringExtra("url");

                if ("NOT_FINISHED".Equals(data))
                {
                    OAuthResult oauthResult = new OAuthResult(OAuthResult.ResultCode.Failed, new Exception("NOT_FINISHED"));
                    this.parent.tcs.TrySetResult(oauthResult);
                }
                else if ("CANCELLED".Equals(data))
                {
                    OAuthResult oauthResult = new OAuthResult(OAuthResult.ResultCode.Cancelled, new Exception("USER_CANCELLED"));
                    this.parent.tcs.TrySetResult(oauthResult);
                }
                else
                {
                    this.parent.appContext.UnregisterReceiver(this.parent.receiver);
                    OnSuccess(new Uri(data), this.parent.tcs);
                }
            }
Example #22
0
        public OAuthResult GetOAuthResult(string encryptedLoginData)
        {
            string provider       = null;
            string providerUserId = null;
            var    oAuth          = new OAuthResult();

            if (!TryDecryptProviderData(encryptedLoginData, out provider, out providerUserId))
            {
                return(oAuth);
            }


            oAuth.IsValid             = true;
            oAuth.Provider            = provider;
            oAuth.ProviderUserId      = providerUserId;
            oAuth.UserName            = OAuthWebSecurity.GetUserName(provider, providerUserId);
            oAuth.ProviderDisplayName = OAuthWebSecurity.GetOAuthClientData(provider).DisplayName;
            oAuth.EncryptedLoginData  = encryptedLoginData;

            return(oAuth);
        }
        private async Task <UserInfo> UnsafeLogin(string userName, string password, CaptchaAnswer captchaAnswer)
        {
            _logger.Method().Start($"{userName} {captchaAnswer}");

            var passwordtData = new Dictionary <string, string>
            {
                { "grant_type", "password" },
                { "client_id", _amClientId },
                { "client_secret", _amClientSecret },
                { "username", userName },
                { "password", password }
            };

            if (captchaAnswer != null)
            {
                passwordtData["x_captcha_key"]    = captchaAnswer.Key;
                passwordtData["x_captcha_answer"] = captchaAnswer.Answer;
            }

            OAuthResult resultWithXToken = await OAuthRequest(passwordtData);

            return((await UnsafeLoginWithXToken(resultWithXToken.AccessToken)).RetWithLog(_logger).Log());
        }
Example #24
0
        public ActionResult <bool> Authorize(string provider)
        {
            var type = AssemblyUtils.ScanAllAssembliesFromAttribute(typeof(OAuthProviderAttribute)).ToList()
                       .FirstOrDefault(t =>
            {
                var attr = t.GetCustomAttribute <OAuthProviderAttribute>();

                return(attr.Name.ToLower() == provider);
            });

            //	type = AssemblyUtils.GetInterfaceOfType(type);
            var oauthResult = new OAuthResult();

            if (!string.IsNullOrEmpty(HttpContext.Request.Query["code"]))
            {
                oauthResult.Code = HttpContext.Request.Query["code"];
            }

            if (!string.IsNullOrEmpty(HttpContext.Request.Query["token"]))
            {
                oauthResult.Code = HttpContext.Request.Query["token"];
            }

            if (!string.IsNullOrEmpty(HttpContext.Request.Query["status"]))
            {
                oauthResult.Code = HttpContext.Request.Query["status"];
            }

            if (type != null)
            {
                var callback = _servicesManager.Resolve(type) as IOAuthCallback;

                callback?.OnOAuthResult(oauthResult);
            }

            return(NotFound(true));
        }
Example #25
0
 internal override OAuthRegisterData Execute(OAuthResult result)
 {
     throw new NotImplementedException();
 }
Example #26
0
 public OAuthRegisterData GetClientRegisterData(OAuthResult result)
 {
     return(_registerDataService.Execute(result.Provider, result));
 }
Example #27
0
 private OAuthRegisterData ThrowUnknownProvider(OAuthResult result)
 {
     throw new ArgumentException(string.Format("{0} is a unknown provider.", result.Provider));
 }
        public OAuthRegisterData GetClientRegisterData(OAuthResult result)
        {
            IOAuthRegisterDataService registerDataService = new OAuthRegisterDataService(_oAuthWrapper);        //not using unity because of internal type

            return(registerDataService.GetClientRegisterData(result));
        }
Example #29
0
 internal abstract OAuthRegisterData Execute(OAuthResult result);
Example #30
0
 protected string GetLoginData(OAuthResult result)
 {
     return(_oAuthWrapper.SerializeProviderUserId(result.Provider, result.ProviderUserId));
 }
Example #31
0
        static string s(OAuthResult p, string name)
        {
            var o = p.Fields.ValueOrDefault(name);

            return(o == null ? null : o.ToString());
        }
Example #32
0
        public OAuthResult GetOAuthResultFromRequest(string returnUrl)
        {
            AuthenticationResult result = OAuthWebSecurity.VerifyAuthentication(returnUrl);
            var oAuth = new OAuthResult();

            if (!result.IsSuccessful)
            {
                return oAuth;
            }

            oAuth.IsValid = true;
            oAuth.UserName = result.UserName;
            oAuth.Provider = result.Provider;
            oAuth.ProviderUserId = result.ProviderUserId;
            oAuth.ProviderDisplayName = OAuthWebSecurity.GetOAuthClientData(result.Provider).DisplayName;
            oAuth.EncryptedLoginData = EncryptProviderData(result.Provider, result.ProviderUserId);

            return oAuth;
        }
Example #33
0
        public OAuthResult GetOAuthResult(string encryptedLoginData)
        {
            string provider = null;
            string providerUserId = null;
            var oAuth = new OAuthResult();

            if (!TryDecryptProviderData(encryptedLoginData, out provider, out providerUserId))
            {
                return oAuth;
            }

            oAuth.IsValid = true;
            oAuth.Provider = provider;
            oAuth.ProviderUserId = providerUserId;
            oAuth.UserName = OAuthWebSecurity.GetUserName(provider, providerUserId);
            oAuth.ProviderDisplayName = OAuthWebSecurity.GetOAuthClientData(provider).DisplayName;
            oAuth.EncryptedLoginData = encryptedLoginData;

            return oAuth;
        }
Example #34
0
 public ActionResult AuthenticationSucceed(OAuthResult result)
 {
     ViewBag.userId = result.oauth_user_guid;
     return(View(result));
 }