/// <summary>
        /// Exchange an authorization code for OAuth 2.0 credentials.
        /// </summary>
        /// <param name="authorizationCode">Authorization code to exchange for OAuth 2.0 credentials.</param>
        /// <param name="refreshToken"></param>
        /// <param name="callbackUrl"></param>
        /// <returns>OAuth 2.0 credentials.</returns>
        public static IAuthorizationState ExchangeCode([NotNull] String authorizationCode, string refreshToken,
                                                       [NotNull] string callbackUrl)
        {
            if (authorizationCode == null)
            {
                throw new ArgumentNullException("authorizationCode");
            }
            if (callbackUrl == null)
            {
                throw new ArgumentNullException("callbackUrl");
            }

            var provider = new NativeApplicationClient(
                GoogleAuthenticationServer.Description, "647667148.apps.googleusercontent.com", "SHvBqFmGtXq5bTPqY242oNvB");
            IAuthorizationState state = new AuthorizationState();

            state.Callback     = new Uri(callbackUrl);
            state.RefreshToken = refreshToken;
            try
            {
                state = provider.ProcessUserAuthorization(authorizationCode, state);
                provider.RequestUserAuthorization();
                return(state);
            }
            catch (ProtocolException)
            {
                throw new Exception(null);
            }
        }
        /// <summary>
        /// Creates the URL which should be used by the user to request the initial
        /// authorization. Uses the default Out-of-band-URI as a callback.
        /// </summary>
        /// <param name="scope">Set of requested scopes</param>
        /// <returns>URI pointing to the authorization server</returns>
        public Uri RequestUserAuthorization(IEnumerable <string> scope)
        {
            var state = new AuthorizationState(scope);

            state.Callback = new Uri(OutOfBandCallbackUrl);
            return(RequestUserAuthorization(state, false, null));
        }
        //  [Authorize]
        public ActionResult AlhambraCallback()
        {
            //System.Web.HttpContext.Current.Application["Authorization"]  = (AuthorizationState) client.ProcessUserAuthorization(this.Request);
            AuthorizationState auth = (AuthorizationState)client.ProcessUserAuthorization(this.Request);

            System.Web.HttpContext.Current.Application["Authorization"] = auth;


            // CurrentAuthorizationState = auth;

            //string code = Request.QueryString["code"];
            //System.Web.HttpContext.Current.Application.Add("Code",Request.QueryString["code"]);

            //string accessToken = Request.QueryString["access_token"];
            //authorizationState = client.ProcessUserAuthorization(this.Request);

            var httpClient = new HttpClient();

            httpClient.DefaultRequestHeaders.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue("Bearer", auth.AccessToken);

            // var tokenInfoUrl =  CLIENT_ADDRESS + "/OAuth2/TokenInfo";

            //in the form of an actionresult instead of a function
            //because the httpclient provides the authorization header
            //by the time it performs the request

            // string tokenInfo = httpClient.GetAsync(tokenInfoUrl).Result.Content.ReadAsStringAsync().Result;

            // System.Web.HttpContext.Current.Application["Token"]= tokenInfo;


            //var tv = new AlhambraTokenValidator();
            //tv.ValidateToken(tokenInfo, "NATURE");

            // string userInfoUrl = CLIENT_ADDRESS + "/UserInfo";

            // OAuth2Graph userInfo = httpClient.GetAsync(userInfoUrl).Result.Content.ReadAsAsync<OAuth2Graph>().Result;


            // string userInfo = httpClient.GetAsync(userInfoUrl).Result.Content.ReadAsStringAsync().Result;

            OAuth2Graph userinfo = client.GetUserInfo(auth.AccessToken);
            //string result = JsonConvert.SerializeObject(userinfo);
            //return Content(result);

            string valuesOfForm = null;

            foreach (string s in Request.Form.AllKeys)
            {
                valuesOfForm = valuesOfForm + ", " + s + ":" + Request.Form[s];
            }

            return(Content("Access Token: " + auth.AccessToken +
                           "<br/>Refresh Token: " + auth.RefreshToken +
                           "<br/>Expires In: " + auth.AccessTokenExpirationUtc +
                           "<br/>Issued At: " + auth.AccessTokenIssueDateUtc +
                           "<br/>Values: " + valuesOfForm +
                           "<br/> Content Type: " + Request.ContentType +
                           "<br/>Input Stream: " + Request.InputStream.ToString()));
        }
        public AuthorizationState RefreshAuthorization(AuthorizationState current)
        {
            if (current == null)
            {
                throw new ArgumentNullException(nameof(current));
            }

            if (current.IsRefreshable)
            {
                var query = this.QueryfyDotNet.Queryfy(new
                {
                    grant_type    = "refresh_token",
                    refresh_token = current.RefreshToken,
                    client_id     = this.AuthorizationContextConfiguration.Authorization.ClientId,
                    client_secret = this.AuthorizationContextConfiguration.Authorization.ClientSecret
                });
                using (var tokenRequest = new HttpRequestMessage(HttpMethod.Post, this.AuthorizationContextConfiguration.Authorization.TokenEndPoint)
                {
                    Content = new StringContent(query.EncodedQueryString, Encoding.UTF8, "application/x-www-form-urlencoded")
                })
                {
                    return(tokenRequest.GetAuthorizationState(this.HttpClient, DateTime.UtcNow, this.AuthorizationContextConfiguration.Authorization.Scopes.GetGrantedScopes().ToList()));
                }
            }

            return(this.StartAuthorization());
        }
Beispiel #5
0
        /// <summary>
        /// Return Analytics Service object
        /// </summary>
        /// <returns>Analytics Service object</returns>
        public static AnalyticsService GetAnalyticsService()
        {
            var provider = new NativeApplicationClient(GoogleAuthenticationServer.Description);

            provider.ClientIdentifier = Settings.ClientIdentifier;
            provider.ClientSecret     = Settings.ClientSecret;

            if (string.IsNullOrWhiteSpace(provider.ClientIdentifier))
            {
                throw new Exception("Client identifier not found");
            }
            if (string.IsNullOrWhiteSpace(provider.ClientSecret))
            {
                throw new Exception("Client secret not found");
            }
            string refreshToken = Settings.RefreshToken;

            if (string.IsNullOrWhiteSpace(refreshToken))
            {
                throw new Exception("Refresh token not found");
            }

            var request       = HttpContext.Current.Request;
            var authenticator = new OAuth2Authenticator <NativeApplicationClient>(provider, (arg) =>
            {
                IAuthorizationState state = new AuthorizationState(new[] { "https://www.googleapis.com/auth/analytics.readonly" });
                state.Callback            = new Uri(string.Format("{0}://{1}{2}/GoogleAnalytics/Callback", request.Url.Scheme, request.Url.Host, request.Url.Port == 80 ? string.Empty : ":" + request.Url.Port));
                state.RefreshToken        = refreshToken;
                var result = arg.RefreshToken(state);
                return(state);
            });

            return(new AnalyticsService(authenticator));
        }
Beispiel #6
0
        private async Task RequestSpotifyAuthForUser(MBUser user, Message message, ILogger logger)
        {
            if (message.Chat.Type != ChatType.Private)
            {
                await TelegramClient.SendTextMessageAsync(
                    message.Chat.Id,
                    $"Sure thing... Sending you a message shortly to get us connected to Spotify");
            }

            var state = new AuthorizationState()
            {
                Message = message,
                UserId  = user.Id,
            };

            await TelegramClient.SendTextMessageAsync(
                user.ServiceId,
                $"OK, in order to continue, I need to connect to your Spotify so I can add you to the fun. Click the button below to get started.",
                replyMarkup : new InlineKeyboardMarkup(
                    new InlineKeyboardButton()
            {
                Text = "Connect Spotify Account",
                Url  = SpotifyService.GetAuthorizationUri(user, state, GetNetSpotifyScopesRequired(user)).ToString()
            }));
        }
Beispiel #7
0
        public void CheckForValidAccessTokenTest()
        {
            int accessTokenCounter = 1;
            var state  = new AuthorizationState();
            var client = new NativeApplicationClient(new Uri("http://example.com"));
            var auth   = new OAuth2Authenticator <NativeApplicationClient>(
                client, (clt) =>
            {
                // Load a "cached" access token.
                state.AccessToken = "token" + (accessTokenCounter++);
                return(state);
            });

            // Check that the initial state is null.
            Assert.IsNull(auth.State);

            // Check that the state was set when .LoadAccessToken() is called.
            auth.LoadAccessToken();
            Assert.AreEqual(state, auth.State);
            Assert.AreEqual("token1", auth.State.AccessToken);

            // Check that it wont be set again.
            auth.LoadAccessToken();
            Assert.AreEqual("token1", auth.State.AccessToken);

            // Check that it is set if our state gets invalid.
            state.AccessToken = null;
            auth.LoadAccessToken();
            Assert.AreEqual("token2", auth.State.AccessToken);
        }
Beispiel #8
0
        internal override bool ParseResponse(string Response)
        {
            bool Success = false;

            switch (AuthState)
            {
            case AuthorizationState.SentLogin:
                if (Response.StartsWith("331"))
                {
                    AuthState = AuthorizationState.AcceptedLogin;
                }
                else if (Response.StartsWith("230"))
                {
                    AuthState = AuthorizationState.AcceptedPassword;
                    OnUserLogin(true);
                }
                else
                {
                    AuthState = AuthorizationState.Failed;
                }
                return(AuthState != AuthorizationState.Failed);

            case AuthorizationState.SentPassword:
                Success   = Response.StartsWith("230");
                AuthState = Success ? AuthorizationState.AcceptedPassword : AuthorizationState.Failed;
                OnUserLogin(Success);
                return(Success);
            }
            return(false);
        }
        public AuthorizationState CreateNewAuthAwaiter()
        {
            var awaiter = AuthorizationState.GetNewAuth();

            AuthorizationStates.TryAdd(awaiter.State, awaiter);
            return(awaiter);
        }
Beispiel #10
0
        /// <summary>
        /// Tries to restore the <see cref="AuthorizationState"/>.
        /// </summary>
        /// <param name="authorizationState">The <see cref="AuthorizationState"/>.</param>
        /// <returns>A value indicating if the restore was successful.</returns>
        public Boolean TryRestoreAuthorization(out AuthorizationState authorizationState)
        {
            try
            {
                using (var fileStream = new FileStream(this.configuration.FileSystemAuthorizationStoreConfiguration.FilePath, FileMode.Open, FileAccess.Read, FileShare.None))
                {
                    var buffer = new Byte[fileStream.Length];
                    fileStream.Read(buffer, 0, (Int32)fileStream.Length);

                    var unprotectedData = ProtectedData.Unprotect(buffer, new Byte[0], DataProtectionScope.CurrentUser);

                    using (var memoryStream = new MemoryStream(unprotectedData))
                    {
                        authorizationState = (AuthorizationState)this.serializer.Deserialize(memoryStream);
                    }
                }

                return(true);
            }
            catch
            {
                authorizationState = null;
                return(false);
            }
        }
Beispiel #11
0
        private IAuthorizationState getAuthorisation(NativeApplicationClient client)
        {
            IAuthorizationState state = new AuthorizationState(new[] { CalendarService.Scopes.Calendar.GetStringValue() });

            state.Callback = new Uri(NativeApplicationClient.OutOfBandCallbackUrl);

            string refreshToken = LoadRefreshToken();

            if (!String.IsNullOrWhiteSpace(refreshToken))
            {
                state.RefreshToken = refreshToken;

                if (client.RefreshToken(state))
                {
                    return(state);
                }
            }

            if (!authRefreshOnly && authFunction != null)
            {
                Uri authUri = client.RequestUserAuthorization(state);

                string authResult = authFunction(authUri);

                var result = client.ProcessUserAuthorization(authResult, state);
                StoreRefreshToken(state);
                return(result);
            }
            else
            {
                return(null);
            }
        }
        public ViewResult RefreshToken(RefreshTokenViewModel model)
        {
            if (this.ModelState.IsValid)
            {
                try
                {
                    // Create the client with which we will be connecting to the server.
                    var webServerClient = new WebServerClient(this.AuthorizationServerDescription, clientIdentifier: model.ClientId, clientSecret: model.ClientSecret);

                    // Create an AuthorizationState instance with only the refresh token set. This is all that is needed for
                    // OAuth to be able to determine what token is to be refreshed
                    var authorizationState = new AuthorizationState {
                        RefreshToken = model.RefreshToken
                    };

                    // Refresh an access token (http://tools.ietf.org/html/draft-ietf-oauth-v2-31#section-6)
                    // This method will use the client identifier and client secret used when constructing the WebServerAgentClient instance
                    webServerClient.RefreshAuthorization(authorizationState);

                    this.ViewBag.AccessToken = authorizationState;
                }
                catch (Exception ex)
                {
                    this.ViewBag.Exception = ex;
                }
            }

            return(this.View(model));
        }
Beispiel #13
0
        private ActionResult InitAuth()
        {
            var state = new AuthorizationState();
            var uri   = Request.Url.AbsoluteUri;

            uri            = RemoveQueryStringFromUri(uri);
            state.Callback = new Uri(uri);
            state.Scope.Add("openid");

            var r = this.authClient.PrepareRequestUserAuthorization(state);

            Log.For(this).Trace("User has not been authorized, redirecting user to identity provider.");

            // If the user was trying to go somewhere specific, add the location/route
            // as a cookie to the authorization request so that we know where they were trying to
            // go after authorization is complete
            if (!string.IsNullOrEmpty(this.Request.Params[RETURN_URL_PARAM_NAME]))
            {
                if (this.Request.Cookies[AUTH_RETURN_URL_COOKIE_NAME] != null)
                {
                    Response.Cookies[AUTH_RETURN_URL_COOKIE_NAME].Value = this.Request.Params[RETURN_URL_PARAM_NAME];
                }
                else
                {
                    HttpCookie cookie = new HttpCookie(AUTH_RETURN_URL_COOKIE_NAME);
                    cookie.Value = this.Request.Params[RETURN_URL_PARAM_NAME];
                    // If it takes longer than a minute to redirect back to Trifolia, they will be sent to the home page
                    cookie.Expires = DateTime.Now.AddMinutes(1);
                    Response.Cookies.Add(cookie);
                }
            }

            return(r.AsActionResultMvc5());
        }
Beispiel #14
0
        /// <summary>
        /// Gets the token from the token table.
        /// </summary>
        /// <returns>
        /// Access token for Visma eAccounting API
        /// </returns>
        public IAuthorizationState GetToken()
        {
            try
            {
                // Gets the token from the token table
                var dbToken = _db.TokenTable.FirstOrDefault();

                // Turns the token into an Authorization state used to access the Visma eAccounting API
                IAuthorizationState setToken = new AuthorizationState()
                {
                    AccessToken = dbToken.AccessToken,
                    AccessTokenExpirationUtc = dbToken.AccessTokenExpirationUtc,
                    AccessTokenIssueDateUtc  = dbToken.AccessTokenIssueDateUtc,
                    RefreshToken             = dbToken.RefreshToken
                };

                return(setToken);
            }
            catch (Exception e)
            {
                // Creates a new error filer object
                var errorLog = new ErrorFiler();

                // Logs the error to the error log, with the name of the exception and where it occured
                errorLog.WriteError(e.GetType().FullName, "NasDAL, IAuthorizationState GetToken()");

                return(null);
            }
        }
        /// <summary>
        /// Returns a pre-filled OAuth 2.0 state for the authorization flow.
        /// </summary>
        /// <returns>OAuth 2.0 state.</returns>
        private IAuthorizationState GetAuthorizationState()
        {
            var authorizationState = new AuthorizationState(Config.SCOPES);

            authorizationState.Callback = new Uri(Config.REDIRECT_URI);
            return(authorizationState);
        }
        /// <inheritdoc cref="IAcmeSharpProvider"/>
        public bool ValidateChallenge()
        {
            // (6) Submit the Challenge Response to Prove Domain Ownership
            this.authState.Challenges = new AuthorizeChallenge[] { this.Challenge };

            // Submit-ACMEChallenge dns1 -ChallengeType http-01
            var authchallenge = this.AcmeClient.SubmitChallengeAnswer(this.authState, AcmeProtocol.CHALLENGE_TYPE_HTTP, true);

            // Esperar a que Let's Encrypt confirme que has superado el challange
            while ("pending".Equals(this.authState.Status, StringComparison.CurrentCultureIgnoreCase))
            {
                Thread.Sleep(3000);

                var newAuthzState = this.AcmeClient.RefreshIdentifierAuthorization(this.authState);

                if (newAuthzState.Status != "pending")
                {
                    this.authState = newAuthzState;
                }
            }

            if (this.authState.Status != "valid")
            {
                this.Logger.LogWarning(
                    true,
                    "Could not verify challenge valid status, returned status: '{0}'",
                    this.authState.Status);

                return(false);
            }

            return(true);
        }
        public void ResourceOwnerScopeOverride()
        {
            var clientRequestedScopes  = new[] { "scope1", "scope2" };
            var serverOverriddenScopes = new[] { "scope1", "differentScope" };
            var authServerMock         = CreateAuthorizationServerMock();

            authServerMock
            .Setup(a => a.CheckAuthorizeResourceOwnerCredentialGrant(ResourceOwnerUsername, ResourceOwnerPassword, It.IsAny <IAccessTokenRequest>()))
            .Returns <string, string, IAccessTokenRequest>((un, pw, req) => {
                var response = new AutomatedUserAuthorizationCheckResponse(req, true, ResourceOwnerUsername);
                response.ApprovedScope.Clear();
                response.ApprovedScope.UnionWith(serverOverriddenScopes);
                return(response);
            });
            var coordinator = new OAuth2Coordinator <WebServerClient>(
                AuthorizationServerDescription,
                authServerMock.Object,
                new WebServerClient(AuthorizationServerDescription),
                client => {
                var authState = new AuthorizationState(TestScopes)
                {
                    Callback = ClientCallback,
                };
                var result = client.ExchangeUserCredentialForToken(ResourceOwnerUsername, ResourceOwnerPassword, clientRequestedScopes);
                Assert.That(result.Scope, Is.EquivalentTo(serverOverriddenScopes));
            },
                server => {
                server.HandleTokenRequest().Respond();
            });

            coordinator.Run();
        }
        public void DecodeRefreshToken()
        {
            var refreshTokenSource = new TaskCompletionSource <string>();
            var coordinator        = new OAuth2Coordinator <WebServerClient>(
                AuthorizationServerDescription,
                AuthorizationServerMock,
                new WebServerClient(AuthorizationServerDescription),
                client => {
                try {
                    var authState = new AuthorizationState(TestScopes)
                    {
                        Callback = ClientCallback,
                    };
                    client.PrepareRequestUserAuthorization(authState).Respond();
                    var result = client.ProcessUserAuthorization();
                    Assert.That(result.AccessToken, Is.Not.Null.And.Not.Empty);
                    Assert.That(result.RefreshToken, Is.Not.Null.And.Not.Empty);
                    refreshTokenSource.SetResult(result.RefreshToken);
                } catch {
                    refreshTokenSource.TrySetCanceled();
                }
            },
                server => {
                var request = server.ReadAuthorizationRequest();
                Assert.That(request, Is.Not.Null);
                server.ApproveAuthorizationRequest(request, ResourceOwnerUsername);
                server.HandleTokenRequest().Respond();
                var authorization = server.DecodeRefreshToken(refreshTokenSource.Task.Result);
                Assert.That(authorization, Is.Not.Null);
                Assert.That(authorization.User, Is.EqualTo(ResourceOwnerUsername));
            });

            coordinator.Run();
        }
        private static IAuthorizationState GetAccessToken(string refresh)
        {
            var authorizationServer = new AuthorizationServerDescription
            {
                //AuthorizationEndpoint = new Uri(AUTHORIZATION_ENDPOINT),
                TokenEndpoint   = new Uri(TOKEN_ENDPOINT),
                ProtocolVersion = ProtocolVersion.V20,
            };

            // get a reference to the auth server
            var client = new UserAgentClient(authorizationServer, CLIENT_ID, CLIENT_SECRET);

            // now get a token
            IAuthorizationState ostate;

            if (refresh == null)
            {
                ostate = client.ExchangeUserCredentialForToken(TEST_USERNAME, TEST_PASSWORD, new[] { API_ENDPOINT });
            }
            else
            {
                // we had previously authenticated so we can use the token rather than the credentials to get a new access token
                ostate = new AuthorizationState(new[] { API_ENDPOINT });
                ostate.RefreshToken = refresh;
                client.RefreshAuthorization(ostate);
            }

            // return result
            return(ostate);
        }
        public void CreateAccessTokenSeesAuthorizingUserAuthorizationCodeGrant()
        {
            var authServerMock = CreateAuthorizationServerMock();

            authServerMock
            .Setup(a => a.IsAuthorizationValid(It.IsAny <IAuthorizationDescription>()))
            .Returns <IAuthorizationDescription>(req => {
                Assert.That(req.User, Is.EqualTo(ResourceOwnerUsername));
                return(true);
            });
            var coordinator = new OAuth2Coordinator <WebServerClient>(
                AuthorizationServerDescription,
                authServerMock.Object,
                new WebServerClient(AuthorizationServerDescription),
                client => {
                var authState = new AuthorizationState(TestScopes)
                {
                    Callback = ClientCallback,
                };
                client.PrepareRequestUserAuthorization(authState).Respond();
                var result = client.ProcessUserAuthorization();
                Assert.That(result.AccessToken, Is.Not.Null.And.Not.Empty);
                Assert.That(result.RefreshToken, Is.Not.Null.And.Not.Empty);
            },
                server => {
                var request = server.ReadAuthorizationRequest();
                Assert.That(request, Is.Not.Null);
                server.ApproveAuthorizationRequest(request, ResourceOwnerUsername);
                server.HandleTokenRequest().Respond();
            });

            coordinator.Run();
        }
        public void ClientCredentialScopeOverride()
        {
            var clientRequestedScopes  = new[] { "scope1", "scope2" };
            var serverOverriddenScopes = new[] { "scope1", "differentScope" };
            var authServerMock         = CreateAuthorizationServerMock();

            authServerMock
            .Setup(a => a.CheckAuthorizeClientCredentialsGrant(It.IsAny <IAccessTokenRequest>()))
            .Returns <IAccessTokenRequest>(req => {
                var response = new AutomatedAuthorizationCheckResponse(req, true);
                response.ApprovedScope.Clear();
                response.ApprovedScope.UnionWith(serverOverriddenScopes);
                return(response);
            });
            var coordinator = new OAuth2Coordinator <WebServerClient>(
                AuthorizationServerDescription,
                authServerMock.Object,
                new WebServerClient(AuthorizationServerDescription),
                client => {
                var authState = new AuthorizationState(TestScopes)
                {
                    Callback = ClientCallback,
                };
                var result = client.GetClientAccessToken(clientRequestedScopes);
                Assert.That(result.Scope, Is.EquivalentTo(serverOverriddenScopes));
            },
                server => {
                server.HandleTokenRequest().Respond();
            });

            coordinator.Run();
        }
        public void CreateAccessTokenSeesAuthorizingUserResourceOwnerGrant()
        {
            var authServerMock = CreateAuthorizationServerMock();

            authServerMock
            .Setup(a => a.CheckAuthorizeResourceOwnerCredentialGrant(ResourceOwnerUsername, ResourceOwnerPassword, It.IsAny <IAccessTokenRequest>()))
            .Returns <string, string, IAccessTokenRequest>((un, pw, req) => {
                var response = new AutomatedUserAuthorizationCheckResponse(req, true, ResourceOwnerUsername);
                Assert.That(req.UserName, Is.EqualTo(ResourceOwnerUsername));
                return(response);
            });
            var coordinator = new OAuth2Coordinator <WebServerClient>(
                AuthorizationServerDescription,
                authServerMock.Object,
                new WebServerClient(AuthorizationServerDescription),
                client => {
                var authState = new AuthorizationState(TestScopes)
                {
                    Callback = ClientCallback,
                };
                var result = client.ExchangeUserCredentialForToken(ResourceOwnerUsername, ResourceOwnerPassword, TestScopes);
                Assert.That(result.AccessToken, Is.Not.Null);
            },
                server => {
                server.HandleTokenRequest().Respond();
            });

            coordinator.Run();
        }
        public void CreateAccessTokenSeesAuthorizingUserClientCredentialGrant()
        {
            var authServerMock = CreateAuthorizationServerMock();

            authServerMock
            .Setup(a => a.CheckAuthorizeClientCredentialsGrant(It.IsAny <IAccessTokenRequest>()))
            .Returns <IAccessTokenRequest>(req => {
                Assert.That(req.UserName, Is.Null);
                return(new AutomatedAuthorizationCheckResponse(req, true));
            });
            var coordinator = new OAuth2Coordinator <WebServerClient>(
                AuthorizationServerDescription,
                authServerMock.Object,
                new WebServerClient(AuthorizationServerDescription),
                client => {
                var authState = new AuthorizationState(TestScopes)
                {
                    Callback = ClientCallback,
                };
                var result = client.GetClientAccessToken(TestScopes);
                Assert.That(result.AccessToken, Is.Not.Null);
            },
                server => {
                server.HandleTokenRequest().Respond();
            });

            coordinator.Run();
        }
        public async Task <ActionResult> AddEdit(Guid?id)
        {
            CompanyLocationGroupEditVm returnValue = new CompanyLocationGroupEditVm();

            if (id == null)
            {
                //create a starting point here.
                returnValue.CompanyLocationGroupUiDto = new CompanyLocationGroupUiDto();
                returnValue.CompanyLocationGroupUiDto.CompanyLocationUiDtos = new List <CompanyLocationUiDto>();
                CompanyLocationUiDto cluiDto = new CompanyLocationUiDto();
                returnValue.CompanyLocationGroupUiDto.CompanyLocationUiDtos.Add(cluiDto);
                AuthorizationState authState = AuthorizationState.NotAllowed;
                bool isCompanyOwner          = false;
                // check for some form of rights before showing the form.
                var company = _accessQueries.GetAuthorization_ForCompanyAdmin_IfCompanyIdSelectedByUserId(Guid.Parse(User.Identity.GetUserId()), false, out authState, out isCompanyOwner);
                returnValue.CompanyLocationGroupUiDto.AuthState_OnlyTrustOnGeneration = authState;
            }
            else
            {
                returnValue.CompanyLocationGroupUiDto = _companyLocationGroupQueries.GetUiDto_CompanyLocationGroupById(User.Identity.GetUserId(), (Guid)id);
            }

            if (returnValue.CompanyLocationGroupUiDto == null)
            {
                return(RedirectToAction("Index", "CompanyLocationGroups"));
            }

            return(View(returnValue));
        }
Beispiel #25
0
        public static AuthorizationState RetrieveCredentialsByAuthCode(String authCode)
        {
            AuthorizationState authState = new AuthorizationState();

            using (SqlConnection myConnection = new SqlConnection("Data Source=" + DATA_SOURCE + "; Initial Catalog=" + CATALOG + "; User ID=" + USER_ID + "; Password='******';"))
            {
                SqlCommand myCommand = new SqlCommand("GET_STORED_CREDENTIALS_BY_AUTHCODE", myConnection);
                myCommand.CommandType = CommandType.StoredProcedure;

                // db will generate auto new id
                myCommand.Parameters.AddWithValue("@AUTH_CODE", authCode);

                myConnection.Open();

                SqlDataReader reader = myCommand.ExecuteReader();

                if (reader.HasRows)
                {
                    while (reader.Read())
                    {
                        authState.AccessToken = reader["ACCESS_TOKEN"].ToString();
                        authState.AccessTokenExpirationUtc = Convert.ToDateTime(reader["ACCESS_TOKEN_EXPIRATION_UTC"]);
                        authState.AccessTokenIssueDateUtc  = Convert.ToDateTime(reader["ACCESS_TOKEN_ISSUE_UTC"]);
                        authState.RefreshToken             = reader["REFRESH_TOKEN"].ToString();
                        authState.Callback = new Uri(reader["CALLBACK"].ToString());
                    }
                }
                myConnection.Close();
            }
            return(authState);
        }
Beispiel #26
0
        public void AuthorizationCodeGrant()
        {
            var coordinator = new OAuth2Coordinator <WebServerClient>(
                AuthorizationServerDescription,
                AuthorizationServerMock,
                new WebServerClient(AuthorizationServerDescription),
                client => {
                var authState = new AuthorizationState(TestScopes)
                {
                    Callback = ClientCallback,
                };
                client.PrepareRequestUserAuthorization(authState).Respond();
                var result = client.ProcessUserAuthorization();
                Assert.That(result.AccessToken, Is.Not.Null.And.Not.Empty);
                Assert.That(result.RefreshToken, Is.Not.Null.And.Not.Empty);
            },
                server => {
                var request = server.ReadAuthorizationRequest();
                Assert.That(request, Is.Not.Null);
                server.ApproveAuthorizationRequest(request, ResourceOwnerUsername);
                server.HandleTokenRequest().Respond();
            });

            coordinator.Run();
        }
        public void SubmitChallengeAnswer()
        {
            // let's retry some times, so that if the site is load-balanced it may hit the wrong server
            int tries = 0;

            while (true)
            {
                AuthorizationState currentState = _authorizationState;
                _client.SubmitChallengeAnswer(currentState, AcmeProtocol.CHALLENGE_TYPE_HTTP, true);

                // have to loop to wait for server to stop being pending.
                while (currentState.Status == "pending")
                {
                    Log.Information("Refreshing authorization...");
                    Thread.Sleep(4000);                     // this has to be here to give ACME server a chance to think
                    AuthorizationState newAuthzState = _client.RefreshIdentifierAuthorization(currentState);
                    if (newAuthzState.Status != "pending")
                    {
                        currentState = newAuthzState;
                    }
                }

                Log.Information($"Authorization Result: {currentState.Status}");
                if (currentState.Status == "valid")
                {
                    return;
                }

                if (++tries == 3)
                {
                    throw new AuthorizationFailedException(currentState);
                }
            }
        }
Beispiel #28
0
        public void Authorize(ref IAuthorizationState authorization, string refreshToken)
        {
            if ((authorization == null))
            {
                authorization = new AuthorizationState
                {
                    Callback     = _redirectUri,
                    RefreshToken = refreshToken
                };
            }

            bool refreshFailed = false;

            if (AccessTokenHasToBeRefreshed(authorization))
            {
                try
                {
                    refreshFailed = !RefreshAuthorization(authorization);
                }
                catch (ProtocolException)
                {
                    //The refreshtoken is not valid anymore
                }
            }

            if (authorization.AccessToken == null || refreshFailed)
            {
                using (var loginDialog = new LoginForm(_redirectUri))
                {
                    loginDialog.AuthorizationUri = GetAuthorizationUri(authorization);
                    loginDialog.ShowDialog();
                    ProcessUserAuthorization(loginDialog.AuthorizationUri, authorization);
                }
            }
        }
        public void CleanUp()
        {
            _options.Clear();

            _chats.Clear();

            _secretChats.Clear();

            _users.Clear();
            _usersFull.Clear();

            _basicGroups.Clear();
            _basicGroupsFull.Clear();

            _supergroups.Clear();
            _supergroupsFull.Clear();

            _chatsMap.Clear();
            _usersMap.Clear();

            _promotedChatId = 0;

            _favoriteStickers?.Clear();
            _installedStickerSets?.Clear();
            _installedMaskSets?.Clear();

            _authorizationState = null;
            _connectionState    = null;
        }
Beispiel #30
0
        public void RefreshAccessTokenSecret(Account account)
        {
            Assert.IsNotNullOrEmpty(account.RefreshToken, "RefreshToken shouldn't be empty");
            AuthorizationState state1 = new AuthorizationState(null);

            state1.RefreshToken = (account.RefreshToken);
            AuthorizationState state = state1;

            this._provider.ClientIdentifier = (account.Application.ApplicationKey);
            this._provider.ClientSecret     = (account.Application.ApplicationSecret);
            try
            {
                TimeSpan?nullable = null;
                this._provider.RefreshToken(state, nullable);
                account.AccessTokenSecret = state.AccessToken;
                account.AccessTokenSecretExpirationDate = state.AccessTokenExpirationUtc;
                account.AccessTokenSecretIssueDate      = state.AccessTokenIssueDateUtc;
            }
            catch (WebException exception)
            {
                using (WebResponse response = exception.Response)
                {
                    using (Stream stream = response.GetResponseStream())
                    {
                        if (stream != null)
                        {
                            ExecutingContext.Current.IoC.Get <ILogManager>(new IParameter[0]).LogMessage(
                                new StreamReader(stream).ReadToEnd(),
                                Sitecore.Social.Infrastructure.Logging.LogLevel.Error, this, exception);
                        }
                    }
                }
            }
        }
    private void OnAuthorizationStateChanged(AuthorizationState state)
    {
        //Just activate right screen based on authorization state`
        switch (state)
        {
            case AuthorizationState.Authorized:
                //Show menu if user is authorized
				MainMenuRoot.CurrentScreenType = typeof (MenuScreenViewModel);
                break;
            case AuthorizationState.Unauthorized:
                //Show login screen if user is unauthorized
				MainMenuRoot.CurrentScreenType = typeof (LoginScreenViewModel);
                break;
            default:
                throw new ArgumentOutOfRangeException("state", state, null);
        }
    }
Beispiel #32
0
		void ResetAuthorization ()
		{
			auth_state = new AuthorizationState (this, false);
			proxy_auth_state = new AuthorizationState (this, true);
		}
 public override void Read(ISerializerStream stream) {
     base.Read(stream);
     this.AuthorizationState = (AuthorizationState)stream.DeserializeInt("AuthorizationState");;
 }
Beispiel #34
0
 void ResetAuthorization()
 {
     _authState = new AuthorizationState(this, false);
     _proxyAuthState = new AuthorizationState(this, true);
 }