private async Task<TokenResponse> ProcessAuthorizationCodeRequestAsync(ValidatedTokenRequest request)
        {
            var response = new TokenResponse
            {
                AccessToken = await CreateAccessTokenAsync(request),
                AccessTokenLifetime = request.Client.AccessTokenLifetime
            };

            if (request.AuthorizationCode.IsOpenId)
            {
                var idToken = await _tokenService.CreateIdentityTokenAsync(request.AuthorizationCode.Subject, request.AuthorizationCode.Client, request.AuthorizationCode.RequestedScopes, false, request.Raw);
                var jwt = await _tokenService.CreateSecurityTokenAsync(idToken);    
                response.IdentityToken = jwt;
            }

            return response;
        }
Ejemplo n.º 2
0
 static string CallApi(TokenResponse token, string endpoint)
 {
     Console.WriteLine(token.AccessToken);
     var client = new HttpClient();
     client.SetBearerToken(token.AccessToken);
     return client.GetStringAsync(endpoint).Result;
 }
        private async Task<TokenResponse> ProcessTokenRequestAsync(ValidatedTokenRequest request)
        {
            var response = new TokenResponse
            {
                AccessToken = await CreateAccessTokenAsync(request),
                AccessTokenLifetime = request.Client.AccessTokenLifetime
            };

            return response;
        }
Ejemplo n.º 4
0
        public void TestPropertiesAndSerialisation()
        {
            TokenResponse token = new TokenResponse()
            {
                AccessToken = "token",
                ExpiresIn = 120,
                RefreshToken = "refresh",
                Territory = "gb",
                UserId = Guid.NewGuid()
            };

            JToken json = token.ToJToken();

            TokenResponse rehydrated = TokenResponse.FromJToken(json, null);

            Assert.AreEqual(token.AccessToken, rehydrated.AccessToken, "Expected AccessToken to match");
            Assert.AreEqual(token.ExpiresIn, rehydrated.ExpiresIn, "Expected ExpiresIn to match");
            Assert.AreEqual(token.RefreshToken, rehydrated.RefreshToken, "Expected RefreshToken to match");
            Assert.AreEqual(token.Territory, rehydrated.Territory, "Expected Territory to match");
            Assert.AreEqual(token.UserId, rehydrated.UserId, "Expected UserId to match");
        }
Ejemplo n.º 5
0
        private async Task <ProviderTokenResponse> CreateProviderTokenResponse(ITurnContext context, TokenResponse tokenResponse)
        {
            var adapter = context.Adapter as BotFrameworkAdapter;
            var tokens  = await adapter.GetTokenStatusAsync(context, context.Activity.From.Id);

            var match = Array.Find(tokens, t => t.ConnectionName == tokenResponse.ConnectionName);

            return(new ProviderTokenResponse
            {
                AuthenticationProvider = match.ServiceProviderDisplayName.GetAuthenticationProvider(),
                TokenResponse = tokenResponse,
            });
        }
Ejemplo n.º 6
0
 public virtual ODataBatch BuildODataBatchClient(Action <HttpRequestMessage> beforeRequest  = null,
                                                 Action <HttpResponseMessage> afterResponse = null, TokenResponse token = null, string odataRouteName = "Test")
 {
     return(new ODataBatch(BuildODataClient(beforeRequest, afterResponse, token, odataRouteName)));
 }
Ejemplo n.º 7
0
        public virtual async Task TestStringFormattersInCustomActions()
        {
            IValueChecker valueChecker = A.Fake <IValueChecker>();

            IStringCorrector stringCorrector1 = A.Fake <IStringCorrector>();

            IStringCorrector stringCorrector2 = A.Fake <IStringCorrector>();

            A.CallTo(() => stringCorrector1.CorrectString(A <string> .Ignored))
            .ReturnsLazily(correctString =>
            {
                string arg = correctString.GetArgument <string>("input");

                return("ONE" + arg);
            });

            A.CallTo(() => stringCorrector2.CorrectString(A <string> .Ignored))
            .ReturnsLazily(correctString =>
            {
                string arg = correctString.GetArgument <string>("input");

                return("TWO" + arg);
            });

            using (BitOwinTestEnvironment testEnvironment = new BitOwinTestEnvironment(new TestEnvironmentArgs
            {
                AdditionalDependencies = (manager, services) =>
                {
                    manager.RegisterInstance(valueChecker);
                    manager.RegisterInstance(stringCorrector2, overwriteExciting: false);
                    manager.RegisterInstance(stringCorrector1, overwriteExciting: false);
                }
            }))
            {
                TokenResponse token = await testEnvironment.Server.Login("ValidUserName", "ValidPassword", clientId : "TestResOwner");

                IODataClient client = testEnvironment.Server.BuildODataClient(token: token);

                await client.Controller <TestModelsController, TestModel>()
                .Action(nameof(TestModelsController.StringFormattersTests))
                .Set(new TestModelsController.StringFormattersTestsParameters
                {
                    simpleString  = "simpleString",
                    stringsArray  = new[] { "stringsArray1", "stringsArray2" },
                    stringsArray2 = new[] { "stringsArray1", "stringsArray2" },
                    entitiesArray = new[]
                    {
                        new TestModel
                        {
                            StringProperty = "StringProperty1", Id = 2, Version = 2
                        },
                        new TestModel
                        {
                            StringProperty = "StringProperty2", Id = 3, Version = 3
                        }
                    },
                    simpleDto = new TestModel {
                        StringProperty = "StringProperty", Id = 1, Version = 1
                    }
                }).ExecuteAsync();

                A.CallTo(() => valueChecker.CheckValue("ONETWOsimpleString"))
                .MustHaveHappenedOnceExactly();

                A.CallTo(() => valueChecker.CheckValue(A <List <string> > .That.Matches(strs => strs.SequenceEqual(new List <string> {
                    "ONETWOstringsArray1", "ONETWOstringsArray2"
                }))))
                .MustHaveHappenedOnceExactly();

                A.CallTo(() => valueChecker.CheckValue(A <TestModel> .That.Matches(tm => tm.StringProperty == "ONETWOStringProperty")))
                .MustHaveHappenedOnceExactly();

                A.CallTo(() => valueChecker.CheckValue(A <List <TestModel> > .That.Matches(tms => tms.First().StringProperty == "ONETWOStringProperty1" && tms.Last().StringProperty == "ONETWOStringProperty2")))
                .MustHaveHappenedOnceExactly();

                A.CallTo(() => stringCorrector1.CorrectString(A <string> .Ignored))
                .MustHaveHappenedANumberOfTimesMatching(times => times == 8);

                A.CallTo(() => stringCorrector2.CorrectString(A <string> .Ignored))
                .MustHaveHappenedANumberOfTimesMatching(times => times == 8);
            }
        }
Ejemplo n.º 8
0
        internal async Task <TokenResponseValidationResult> ValidateTokenResponseAsync(TokenResponse response, AuthorizeState state, bool requireIdentityToken = true)
        {
            _logger.LogTrace("ValidateTokenResponse");

            // token response must contain an access token
            if (response.AccessToken.IsMissing())
            {
                return(new TokenResponseValidationResult("Access token is missing on token response."));
            }

            if (requireIdentityToken)
            {
                // token response must contain an identity token (openid scope is mandatory)
                if (response.IdentityToken.IsMissing())
                {
                    return(new TokenResponseValidationResult("Identity token is missing on token response."));
                }
            }

            if (response.IdentityToken.IsPresent())
            {
                // if identity token is present, it must be valid
                var validationResult = await _tokenValidator.ValidateAsync(response.IdentityToken);

                if (validationResult.IsError)
                {
                    return(new TokenResponseValidationResult(validationResult.Error ?? "Identity token validation error"));
                }

                // validate nonce
                if (state != null)
                {
                    if (!ValidateNonce(state.Nonce, validationResult.User))
                    {
                        return(new TokenResponseValidationResult("Invalid nonce."));
                    }
                }

                // validate at_hash
                var atHash = validationResult.User.FindFirst(JwtClaimTypes.AccessTokenHash);
                if (atHash == null)
                {
                    if (_options.Policy.RequireAccessTokenHash)
                    {
                        return(new TokenResponseValidationResult("at_hash is missing."));
                    }
                }
                else
                {
                    if (!_crypto.ValidateHash(response.AccessToken, atHash.Value, validationResult.SignatureAlgorithm))
                    {
                        return(new TokenResponseValidationResult("Invalid access token hash."));
                    }
                }

                return(new TokenResponseValidationResult(validationResult));
            }

            return(new TokenResponseValidationResult((IdentityTokenValidationResult)null));
        }
        private HttpResponseMessage CreateTokenResponse(GenericXmlSecurityToken token, string scope)
        {
            var response = new TokenResponse();

            if (ConfigurationRepository.AdfsIntegration.PassThruAuthenticationToken)
            {
                response.AccessToken = token.TokenXml.OuterXml;
                response.ExpiresIn = (int)(token.ValidTo.Subtract(DateTime.UtcNow).TotalSeconds);
            }
            else
            {
                var bridge = new AdfsBridge(ConfigurationRepository);
                if (ConfigurationRepository.Keys.DecryptionCertificate != null)
                {
                    var configuration = new SecurityTokenHandlerConfiguration
                    {
                        AudienceRestriction = { AudienceMode = AudienceUriMode.Never },
                        CertificateValidationMode = X509CertificateValidationMode.None,
                        RevocationMode = X509RevocationMode.NoCheck,
                        CertificateValidator = X509CertificateValidator.None,
                        ServiceTokenResolver = SecurityTokenResolver.CreateDefaultSecurityTokenResolver(
                            new ReadOnlyCollection<SecurityToken>(new SecurityToken[] { new X509SecurityToken(ConfigurationRepository.Keys.DecryptionCertificate) }), false)
                    };
                    var handler = SecurityTokenHandlerCollection.CreateDefaultSecurityTokenHandlerCollection(configuration);
                    response = bridge.ConvertSamlToJwt(token.ToSecurityToken(handler), scope);
                }
                else
                {
                    response = bridge.ConvertSamlToJwt(token.ToSecurityToken(), scope);
                }
            }

            return Request.CreateResponse<TokenResponse>(HttpStatusCode.OK, response);
        }
Ejemplo n.º 10
0
        /// <summary>
        /// Finalises authorisation to obtain a token
        /// </summary>
        /// <param name="authorizationCode">The authorization code.</param>
        /// <param name="refreshToken">The refresh token.</param>
        /// <param name="resultCode">The result code for the process so far.</param>
        /// <returns>
        /// Whether the token was retrieved
        /// </returns>
        internal async Task<Response<AuthResultCode>> ObtainToken(string authorizationCode, string refreshToken, AuthResultCode resultCode)
        {
            // Next get a token, for now just return whether we got the authorization code...
            if (!string.IsNullOrEmpty(authorizationCode) || !string.IsNullOrEmpty(refreshToken))
            {
                ManualResetEventSlim waiter = new ManualResetEventSlim();
                Response<AuthResultCode> result = null;

                this.TokenCallInProgress = true;

                // Set up auth code and secret...
                this._tokenCommand.AuthorizationCode = authorizationCode;
                this._tokenCommand.ClientId = this._clientId;
                this._tokenCommand.ClientSecret = this._clientSecret;
                this._tokenCommand.RefreshToken = refreshToken;

                try
                {
                    var tokenResponse = await this._tokenCommand.InvokeAsync();
                    if (tokenResponse.Result != null)
                    {
                        result = new Response<AuthResultCode>(null, AuthResultCode.Success, Guid.Empty);
                        this.TokenResponse = tokenResponse.Result;
                    }
                }
                catch
                {
                    result = new Response<AuthResultCode>(null, AuthResultCode.Unknown, Guid.Empty);
                }

                this.TokenCallInProgress = false;

                return result;
            }
            else
            {
                return new Response<AuthResultCode>(null, resultCode, Guid.Empty);
            }
        }
Ejemplo n.º 11
0
    private void OnSuccessLogin(string response)
    {
        TokenResponse tokenData = JsonUtility.FromJson <TokenResponse>(response);

        this.userManager.SaveUserToken(tokenData.access_token);
    }
Ejemplo n.º 12
0
        public async Task <UserCredential> LoadUserCredentialsAsync(string key)
        {
            TokenResponse token = await _flow.LoadTokenAsync(key, CancellationToken.None) ?? throw new FileLoadException("Failed to load the user's Google access token from the data store.");

            return(new UserCredential(_flow, key, token));
        }
Ejemplo n.º 13
0
 public Tokens(TokenResponse response)
 {
     AccessToken  = response.AccessToken;
     RefreshToken = response.RefreshToken;
 }
Ejemplo n.º 14
0
        private async void LoginMethod()
        {
            this.IsRunning = true;
            this.IsEnabled = false;
            Response internet_connection = await apiService.CheckConnection();

            if (!internet_connection.IsSuccess)
            {
                this.IsRunning = false;
                this.IsEnabled = true;
                await Application.Current.MainPage.DisplayAlert(
                    Languages.ErrorTitle,
                    internet_connection.Message,
                    Languages.AcceptButton);

                return;
            }
            TokenResponse token = await apiService.GetToken(
                "https://landsapi1.azurewebsites.net",
                Email,
                Password);

            if (token == null)
            {
                this.IsRunning = false;
                this.IsEnabled = true;
                await Application.Current.MainPage.DisplayAlert(
                    Languages.ErrorTitle,
                    Languages.ErrorUhandledDescription,
                    Languages.AcceptButton);

                return;
            }

            if (token.AccessToken == null)
            {
                this.Password  = "";
                this.IsRunning = false;
                this.IsEnabled = true;
                await Application.Current.MainPage.DisplayAlert(
                    Languages.ErrorTitle,
                    token.ErrorDescription,
                    Languages.AcceptButton);

                return;
            }
            Response responseUsersList = await apiService.GetList <UserInfo>(
                "https://landsapi1.azurewebsites.net",
                "/api",
                "/Users");

            if (!responseUsersList.IsSuccess)
            {
                await Application.Current.MainPage.DisplayAlert(
                    Languages.ErrorTitle,
                    responseUsersList.Message,
                    Languages.AcceptButton);

                return;
            }
            List <UserInfo> listUsers = (List <UserInfo>)responseUsersList.Result;
            var             user      = listUsers.Where(u => u.Email == this.Email).FirstOrDefault();

            if (this.IsRemembered)
            {
                Settings.Token     = token.AccessToken;
                Settings.TokenType = token.TokenType;
                Settings.UserID    = user.UserId.ToString();
            }
            MainViewModel.GetInstance().User      = user;//user;
            MainViewModel.GetInstance().Token     = token.AccessToken;
            MainViewModel.GetInstance().TokenType = token.TokenType;
            this.IsRunning = false;
            this.IsEnabled = true;
            //var menuItem = new MenuItemViewModel()
            //{
            //    UserName = user.FirstName

            var Main = MainViewModel.GetInstance();

            Main.LoadMenuItems();
            Main.UserName    = string.Format("Hola {0}", user.FirstName);
            Main.ImageSource = user.ImageFullPath;
            if (user.ImageFullPath == "noimage")
            {
                Main.ImageSource = "cameraImage";
            }
            Main.Lands = new LandsViewModel();
            var masterPage = new MasterPage();

            MainViewModel.GetInstance().MasterPage = masterPage;
            Application.Current.MainPage = masterPage;
        }
Ejemplo n.º 15
0
 private static void SetCurrentTokens(TokenResponse tokenResponse)
 {
     tokens = tokenResponse;
 }
Ejemplo n.º 16
0
        public static void SignIn(string path)
        {
            tokenPath = path;

            string logoutUri        = OneDriveClient.GetDefaultLogoutUri();
            string authorizationUri = OneDriveClient.GetDefaultAuthorizationUri();

            AuthenticationResult        authenticationResult = null;
            BrowserAuthenticationWindow authWindow           = new BrowserAuthenticationWindow();

            authWindow.Browser.Navigated += (sender, args) =>
            {
                if (string.Equals(args.Uri.AbsolutePath, "/oauth20_logout.srf", StringComparison.OrdinalIgnoreCase))
                {
                    // The logout page has finished loading, so we can now load the login page.
                    authWindow.Browser.Navigate(authorizationUri);
                }

                // If the browser is directed to the redirect URI, the new URI will contain the access code that we can use to
                // get a token for OneDrive.
                if (string.Equals(args.Uri.AbsolutePath, "ietf:wg:oauth:2.0:oob", StringComparison.OrdinalIgnoreCase))
                {
                    // We were directed back to the redirect URI. Extract the code from the query string
                    Dictionary <string, string> queryParametes = args.Uri.GetQueryParameters();

                    authenticationResult = new AuthenticationResult()
                    {
                        Code = queryParametes["code"]
                    };

                    // All done. Close the window.
                    authWindow.Close();
                }
            };

            authWindow.Closed += (sender, args) =>
            {
                if (authenticationResult == null)
                {
                    AuthComplete.Set();
                    return;
                }

                Task.Factory.StartNew(async() =>
                {
                    TokenResponse currentToken = await OneDriveClient.GetAccessToken(authenticationResult).ConfigureAwait(false);
                    currentToken.SaveProtectedToken(tokenPath);
                    TokenSuccess = true;
                    AuthComplete.Set();
                });
            };

            authWindow.Loaded += (sender, args) =>
            {
                authWindow.Browser.Navigate(logoutUri);
                SyncPro.UI.NativeMethods.User32.SetForegroundWindow(new WindowInteropHelper(authWindow).Handle);
            };

            authWindow.ShowDialog();

            AuthComplete.WaitOne();
        }
Ejemplo n.º 17
0
        public object RefreshOauth()
        {
            var CLIENT_ID = "570313910467-h8raudku9n9n65118tqndopih9breo53.apps.googleusercontent.com";
            var CLIENT_SECRET = "T8vlM82EEb82IAtDSaey-Oet";
            ClientSecrets secrets = new ClientSecrets
            {
                ClientId = CLIENT_ID,
                ClientSecret = CLIENT_SECRET
            };

            TokenResponse token = new TokenResponse
            {
                AccessToken = "sfd",                
                RefreshToken = "1/RcTEm-ZKEtBZzS2jOVLONQcmhtEpRZ7r2zny2HjWtMY"
            };

            IAuthorizationCodeFlow flow =
                new GoogleAuthorizationCodeFlow(new GoogleAuthorizationCodeFlow.Initializer
                {
                    ClientSecrets = secrets,
                    Scopes = new string[] { DriveService.Scope.Drive }
                });

            UserCredential credential = new UserCredential(flow, "me", token);
            bool success = credential.RefreshTokenAsync(CancellationToken.None).Result;

            token = credential.Token;
            string access = token.AccessToken;

            var dbCtx = new CompassDBEntities();
            var oauthVal = new DriveOauth();
            oauthVal.Id = 1;
            var DriveAuth = dbCtx.DriveOauths.Find(oauthVal.Id);
            
            DriveAuth.AccessToken = token.AccessToken;
            DriveAuth.ExpireTime = token.ExpiresInSeconds.ToString();
            DriveAuth.IssueTime = token.Issued.ToString();
            dbCtx.SaveChanges();
            return token;
        }
Ejemplo n.º 18
0
        /// <summary>
        /// Calls create customer and checks for 401 UnAuthorized error
        /// </summary>
        /// <returns>customer Id</returns>
        public async Task <String> CreateCustomerApiCall()
        {
            try
            {
                output("Making QBO API Call.");
                Helper.InitializeContext initialize     = new Helper.InitializeContext(dictionary["accessToken"], dictionary["refreshToken"], dictionary["realmId"]);
                ServiceContext           servicecontext = initialize.InitializeQBOServiceContextUsingoAuth();
                Customer customer = QBOApp.CreateCustomer(servicecontext);
                return(customer.Id);
            }
            catch (IdsException ex)
            {
                if (ex.Message == "Unauthorized-401")
                {
                    output("Invalid/Expired Access Token.");
                    //if you get a 401 token expiry then perform token refresh
                    TokenResponse refreshAccessTokenResponse = await Helper.OAuth2Helper.refreshAccessToken(refreshToken, clientID, clientSecret, discoveryUrl);

                    if (refreshAccessTokenResponse.HttpStatusCode == HttpStatusCode.OK)
                    {
                        //save the refresh token in persistent store so that it can be used to refresh short lived access tokens
                        refreshToken = refreshAccessTokenResponse.RefreshToken;
                        if (!dictionary.ContainsKey("refreshToken"))
                        {
                            dictionary.Add("refreshToken", refreshToken);
                        }
                        else
                        {
                            dictionary["refreshToken"] = refreshToken;
                        }

                        output("Refresh token obtained.");

                        accessToken = refreshAccessTokenResponse.AccessToken;

                        output("Access token obtained.");
                        if (!dictionary.ContainsKey("accessToken"))
                        {
                            dictionary.Add("accessToken", accessToken);
                        }
                        else
                        {
                            dictionary["accessToken"] = accessToken;
                        }
                    }

                    if ((dictionary.ContainsKey("accessToken")) && (dictionary.ContainsKey("refreshToken")) && (dictionary.ContainsKey("realmId")))
                    {
                        // update data store with new access and refresh token values

                        Helper.InitializeContext initialize     = new Helper.InitializeContext(dictionary["accessToken"], dictionary["refreshToken"], dictionary["realmId"]);
                        ServiceContext           servicecontext = initialize.InitializeQBOServiceContextUsingoAuth();

                        Customer customer = QBOApp.CreateCustomer(servicecontext);
                        return(customer.Id);
                    }
                    return("Cannot make refresh access token API call");
                }
                else
                {
                    output(ex.Message);
                    return(ex.Message);
                }
            }
        }
Ejemplo n.º 19
0
        /// <summary>
        /// Processes the token post request.
        /// </summary>
        /// <param name="context">The context.</param>
        private void ProcessTokenPostRequest(HttpContext context)
        {
            TokenResponse tokenResponse = new TokenResponse();
            try
            {
                string clientId = context.Request.Form[ClientIdParam];
                string clientSecret = context.Request.Form[ClientSecretParam];
                string code = context.Request.Form[CodeParam];
                string grantType = context.Request.Form[GrantTypeParam];

                if (string.IsNullOrEmpty(grantType))
                {
                    grantType = GrantTypeAuthorizationCodeValue;
                }

                if (string.IsNullOrEmpty(clientId))
                {
                    throw new ArgumentOutOfRangeException("clientId");
                }

                if (string.IsNullOrEmpty(clientSecret))
                {
                    throw new ArgumentOutOfRangeException("clientSecret");
                }

                if (string.IsNullOrEmpty(code))
                {
                    throw new ArgumentOutOfRangeException("code");
                }

                ApplicationInfo appInfo = this.store.GetApplicationByClientId(clientId);
                if (appInfo == null)
                {
                    throw new SecurityException("Unknown client id.");
                }

                if (string.CompareOrdinal(appInfo.ClientSecret, clientSecret) != 0)
                {
                    throw new SecurityException("Invalid client secret.");
                }

                OAuth2Code parsedCode = OAuth2Code.Parse(code);
                if (!parsedCode.Validate(this.tokenSecret) ||
                    parsedCode.Expires < DateTime.UtcNow ||
                    parsedCode.ApplicationName != appInfo.Name)
                {
                    throw new SecurityException("Invalid code.");
                }

                // TODO: Implement refresh tokens.
                // TODO: Use a specific access token class.
                tokenResponse.TokenType = "Bearer";
                OAuth2Code accessToken = OAuth2Code.Generate(
                    parsedCode.AccountId,
                    parsedCode.ApplicationName,
                    DateTime.UtcNow + TokenLifetime,
                    this.tokenSecret);
                tokenResponse.AccessToken = accessToken.ToString();
                tokenResponse.ExpiresInSeconds = (int)TokenLifetime.TotalSeconds;
            }
            catch (ArgumentException argEx)
            {
                tokenResponse.Error = "invalid_request";
                tokenResponse.ErrorDescription = argEx.Message;
            }
            catch (SecurityException securityEx)
            {
                tokenResponse.Error = "invalid_client";
                tokenResponse.ErrorDescription = securityEx.Message;
            }

            context.Response.ContentType = "application/json";
            context.Response.StatusCode = tokenResponse.Error != null ?
                (int)System.Net.HttpStatusCode.BadRequest :
                (int)System.Net.HttpStatusCode.OK;
            TokenResponseSerializer.WriteObject(context.Response.OutputStream, tokenResponse);
        }
Ejemplo n.º 20
0
        private async void ContentDialog_PrimaryButtonClick(ContentDialog sender, ContentDialogButtonClickEventArgs args)
        {
            StorageFolder folder = ApplicationData.Current.LocalFolder;

            StorageFile file = await folder.GetFileAsync("token.txt");

            var tokenContent = await FileIO.ReadTextAsync(file);

            TokenResponse token = JsonConvert.DeserializeObject <TokenResponse>(tokenContent);

            // Lay thong tin ca nhan bang token.
            HttpClient client2 = new HttpClient();

            client2.DefaultRequestHeaders.Add("Authorization", "Basic " + token.token);
            var resp = client2.GetAsync("http://2-dot-backup-server-002.appspot.com/_api/v2/members/information").Result;

            Debug.WriteLine(await resp.Content.ReadAsStringAsync());
            var userInfoContent = await resp.Content.ReadAsStringAsync();

            Member userInfoJson = JsonConvert.DeserializeObject <Member>(userInfoContent);

            // do validate first.
            this.currentSong.name        = this.SongName.Text;
            this.currentSong.description = this.Description.Text;
            this.currentSong.singer      = this.Singer.Text;
            this.currentSong.author      = this.Author.Text;
            this.currentSong.thumbnail   = this.Thumbnail.Text;
            this.currentSong.link        = this.Link.Text;
            //Debug.WriteLine("Action success.");
            //currentSong.memberId = userInfoJson.id;

            string content = await API_Handle.Create_Song(this.currentSong);

            // đến đây là đã có mp3 đã lên rồi.

            //Load trang khi truy cập
            //ProgressRing.Visibility = Visibility.Visible;
            //ProgressRing.IsActive = true;
            //SongLoading.Visibility = Visibility.Visible;
            //await Task.Delay(3000);
            //ProgressRing.IsActive = false;
            //ProgressRing.Visibility = Visibility.Collapsed;
            //SongLoading.Visibility = Visibility.Collapsed;

            var dialog = new Windows.UI.Popups.MessageDialog("Upload thành công");

            dialog.Commands.Add(new Windows.UI.Popups.UICommand("OK")
            {
                Id = 1
            });
            dialog.CancelCommandIndex = 1;
            await dialog.ShowAsync();

            //reset Form Create Song
            SongName.Text    = "";
            Description.Text = "";
            Singer.Text      = "";
            Author.Text      = "";
            Thumbnail.Text   = "";
            Link.Text        = "";
        }
        public ActionResult <SignInResultModel> SignIn(
            [FromForm] string sEmail
            , [FromForm] string sPW)
        {
            //결과용
            ApiResultReady rrResult = new ApiResultReady(this);
            //로그인 처리용 모델
            SignInResultModel armResult = new SignInResultModel();

            rrResult.ResultObject = armResult;

            //API 호출 시간
            DateTime dtNow = DateTime.Now;

            //사인인 시도 기록
            GlobalSign.LogAdd_DB(
                1
                , ModelDB.UserSignLogType.SignIn
                , 0
                , string.Format("SignIn 시도 - {0}, {1}", sEmail, sPW));


            //검색된 유저
            User findUser = null;

            using (SpaNetCoreFoundationContext db1 = new SpaNetCoreFoundationContext())
            {
                //유저 검색
                findUser
                    = db1.User
                      .FirstOrDefault(m =>
                                      m.SignEmail == sEmail &&
                                      m.Password == sPW);
            }//end using db1


            if (findUser != null)
            {
                //토큰 요청
                TokenResponse tr = GlobalStatic.TokenProc.RequestTokenAsync(sEmail, sPW).Result;

                if (true == tr.IsError)
                {//에러가 있다.
                    rrResult.InfoCode = "1";
                    rrResult.Message  = "아이디나 비밀번호가 틀렸습니다.";
                }
                else
                {//에러가 없다.
                    using (SpaNetCoreFoundationContext db1 = new SpaNetCoreFoundationContext())
                    {
                        //기존 로그인한 유저 검색
                        UserSignIn[] arrSL
                            = db1.UserSignIn
                              .Where(m => m.idUser == findUser.idUser)
                              .ToArray();

                        //기존 로그인 토큰 제거
                        foreach (UserSignIn itemUSI in arrSL)
                        {
                            //리플레시 토큰 제거
                            if ((null != itemUSI.RefreshToken) &&
                                (string.Empty != itemUSI.RefreshToken))
                            {
                                TokenRevocationResponse trr
                                    = GlobalStatic.TokenProc
                                      .RevocationTokenAsync(itemUSI.RefreshToken)
                                      .Result;
                            }
                        }//end foreach itemUSI

                        //기존 로그인한 유저 정보 제거
                        db1.UserSignIn.RemoveRange(arrSL);
                        //db 적용
                        db1.SaveChanges();


                        //로그인 되어있는 유저정보 저장
                        UserSignIn slItem = new UserSignIn();
                        slItem.idUser       = findUser.idUser;
                        slItem.RefreshToken = tr.RefreshToken;
                        slItem.SignInDate   = dtNow;
                        slItem.RefreshDate  = dtNow;

                        //기존 로그인한 유저 정보 제거
                        db1.UserSignIn.Add(slItem);
                        //db 적용
                        db1.SaveChanges();

                        //로그인한 유저에게 전달할 정보
                        armResult.idUser   = findUser.idUser;
                        armResult.Email    = findUser.SignEmail;
                        armResult.ViewName = armResult.Email;

                        armResult.access_token  = tr.AccessToken;
                        armResult.refresh_token = tr.RefreshToken;

                        //성공 로그
                        //사인인 성공 기록
                        GlobalSign.LogAdd_DB(
                            1
                            , ModelDB.UserSignLogType.SignIn
                            , findUser.idUser
                            , string.Format("SignIn 성공 - {0}", sEmail));
                    }//end using db1
                }
            }
            else
            {
                rrResult.InfoCode = "1";
                rrResult.Message  = "아이디나 비밀번호가 틀렸습니다.";
            }

            return(rrResult.ToResult(armResult));
        }
Ejemplo n.º 22
0
        public async Task <IResponse <BasketResponse> > PurchaseBasketAsync(PurchaseBasketCreateOption purchaseBasketCreateOption, TokenResponse token)
        {
            Urls.BaseUrl = _settings.GetConfigSetting <string>(SettingKeys.Integration.DTCM.BaseUrl);

            IRequestCreateOptions <PurchaseBasketCreateOption> requestCreateOptions = new RequestCreateOptions <PurchaseBasketCreateOption>();

            requestCreateOptions.Content = purchaseBasketCreateOption;
            requestCreateOptions.Header  = new Dictionary <string, string>()
            {
                { "Token", $"{token.AccessToken}" }
            };
            requestCreateOptions.UserAgent = "zoonga.com (http://www.zoonga.com/)";

            IHttpResponse httpResponse = await HttpWebRequestProviders <PurchaseBasketCreateOption> .PostBearerWebRequestProvider(string.Format(Urls.PurchaseBasket, purchaseBasketCreateOption.BasketID), requestCreateOptions).ConfigureAwait(false);

            if (!string.IsNullOrWhiteSpace(httpResponse.Response))
            {
                BasketResponse basket = Mapper <BasketResponse> .MapJsonStringToObject(httpResponse.Response);

                return(GetResponse(true, basket));
            }
            else
            {
                _logger.Log(LogCategory.Error, new Exception("Failed to purchase basket", httpResponse.WebException));
            }
            return(GetResponse(false, null));
        }
Ejemplo n.º 23
0
 public BotUserCredential(IAuthorizationCodeFlow flow, User user, TokenResponse token) : base(flow, user.Id.ToString(), token)
 {
     From = user;
 }
Ejemplo n.º 24
0
        public static async Task MainAsync()
        {
            var idServerBase = "https://localhost:5001";
            var apiBase      = "https://localhost:5011";
            var disco        = await DiscoveryClient.GetAsync(idServerBase);

            if (disco.IsError)
            {
                Console.WriteLine(disco.Error);
                return;
            }

            TokenResponse tokenResponse = null;

            //Reason to use password grant vs client credentials: for password grant The access token will now contain a sub claim which uniquely identifies the user.
            //This “sub” claim can be seen by examining the content variable after the call to the API and also will be displayed on the screen by the console application.
            //The presence(or absence) of the sub claim lets the API distinguish between calls on behalf of clients and calls on behalf of users.
            Console.WriteLine("Client Credentials (c) or User Login (u)?");
            var grantType = Console.ReadLine();

            switch (grantType)
            {
            case "c":
            {
                var tokenClient = new TokenClient(disco.TokenEndpoint, "client", "clientcredentials");
                tokenResponse = await tokenClient.RequestClientCredentialsAsync("petstore");

                break;
            }

            case "u":
            {
                var tokenClient = new TokenClient(disco.TokenEndpoint, "ro.client", "resourceowner");
                Console.Write("Enter username:"******"Enter password:"******"petstore");

                break;
            }

            default:
            {
                Console.WriteLine("Unrecognized option selection. Type either \"c\" or \"u\".");
                break;
            }
            }

            if (tokenResponse.IsError)
            {
                Console.WriteLine(tokenResponse);
                return;
            }

            Console.WriteLine(tokenResponse.Json + "\n\n");

            var client = new HttpClient();

            client.SetBearerToken(tokenResponse.AccessToken);

            var response = await client.GetAsync(apiBase + "/api/identity");

            if (!response.IsSuccessStatusCode)
            {
                Console.ForegroundColor = ConsoleColor.Red;
                Console.WriteLine(response.StatusCode);
                Console.ReadKey();
            }
            else
            {
                Console.ForegroundColor = ConsoleColor.Green;
                var content = await response.Content.ReadAsStringAsync();

                Console.WriteLine(JArray.Parse(content));
                Console.ReadKey();
            }
        }
Ejemplo n.º 25
0
 public TokenResult(TokenResponse response)
 {
     _response = response;
 }
Ejemplo n.º 26
0
            private async void cmdLogin()
            {
                if (String.IsNullOrEmpty(Email))
                {
                    return;
                }


                IsRunning = true;
                IsEnabled = false;

                var conexion = this.apiService.CheckConnection();

                if (!conexion.IsSuccess)
                {
                    this.IsRunning = false;
                    this.IsEnabled = true;
                    await Application.Current.MainPage.DisplayAlert(
                        "ERROR",
                        conexion.Message,
                        "Accept");

                    return;
                }

                TokenResponse token = await this.apiService.GetToken(
                    "https://productosi220.azurewebsites.net",
                    this.Email,
                    this.Password);

                if (token == null)
                {
                    this.IsRunning = false;
                    this.IsEnabled = true;
                    await Application.Current.MainPage.DisplayAlert(
                        "ERROR",
                        "Something was wrong, please try later.",
                        "Accept");

                    return;
                }

                if (string.IsNullOrEmpty(token.AccessToken))
                {
                    this.IsRunning = false;
                    this.IsEnabled = true;
                    await Application.Current.MainPage.DisplayAlert(
                        "ERROR",
                        token.ErrorDescription,
                        "Accept");

                    this.Password = String.Empty;

                    return;
                }

                MainViewModel mainViewModel = MainViewModel.GetInstance();

                mainViewModel.Token     = token.AccessToken;
                mainViewModel.TokenType = token.TokenType;

                Application.Current.MainPage = new NavigationPage(new Notepage());
                IsRunning = false;
                IsEnabled = true;
            }
Ejemplo n.º 27
0
        private static async Task <TResponse> PostAsync <TRequest, TResponse>(Uri url, TokenResponse token, TRequest request)
        {
            using (var httpClient = new HttpClient())
            {
                httpClient.DefaultRequestHeaders.Authorization =
                    new AuthenticationHeaderValue("Bearer", token.access_token);

                var httpResponse = await httpClient.PostAsJsonAsync(url.ToString(), request);

                if (httpResponse.IsSuccessStatusCode)
                {
                    return(await httpResponse.Content.ReadAsAsync <TResponse>());
                }

                var content = await httpResponse.Content.ReadAsStringAsync();

                throw new Exception(content);
            }
        }
Ejemplo n.º 28
0
 /// <summary>Constructs a new credential instance.</summary>
 /// <param name="flow">Authorization code flow.</param>
 /// <param name="userId">User identifier.</param>
 /// <param name="token">An initial token for the user.</param>
 public UserCredential(IAuthorizationCodeFlow flow, string userId, TokenResponse token)
 {
     this.flow   = flow;
     this.userId = userId;
     this.token  = token;
 }
Ejemplo n.º 29
0
        public virtual IODataClient BuildODataClient(Action <HttpRequestMessage> beforeRequest  = null,
                                                     Action <HttpResponseMessage> afterResponse = null, TokenResponse token = null, string odataRouteName = "Test")
        {
            ODataClient client = new ODataClient(new ODataClientSettings(new Uri($"{Uri}odata/{odataRouteName}/"))
            {
                BeforeRequest = message =>
                {
                    if (token != null)
                    {
                        message.Headers.Add("Authorization",
                                            $"{token.TokenType} {token.AccessToken}");
                    }

                    beforeRequest?.Invoke(message);
                },
                AfterResponse = message =>
                {
                    afterResponse?.Invoke(message);
                },
                OnCreateMessageHandler = GetHttpMessageHandler
            });

            return(client);
        }
Ejemplo n.º 30
0
 public Task <OidcUserSession> CreateSessionAsync(DateTimeOffset validUntil, ClaimsPrincipal claimsPrincipal, TokenResponse tokenResponse, string sessionState, OpenidConnectPkceState openidClientPkceState)
 {
     return(CreateUpdateSessionAsync(validUntil, claimsPrincipal, tokenResponse, sessionState, openidClientPkceState.OidcDiscoveryUri, openidClientPkceState.ClientId));
 }
Ejemplo n.º 31
0
 public void Logout()
 {
     tokenResponse = null;
     claims        = null;
 }
Ejemplo n.º 32
0
 public Task <OidcUserSession> UpdateSessionAsync(DateTimeOffset validUntil, ClaimsPrincipal claimsPrincipal, TokenResponse tokenResponse, string sessionState, OidcUserSession userSession)
 {
     return(CreateUpdateSessionAsync(validUntil, claimsPrincipal, tokenResponse, sessionState, userSession.OidcDiscoveryUri, userSession.ClientId));
 }
Ejemplo n.º 33
0
 private Dictionary <string, JsonElement> GetFields(TokenResponse response)
 {
     return(response.Json.ToObject <Dictionary <string, JsonElement> >());
 }
Ejemplo n.º 34
0
        private async Task <OidcUserSession> CreateUpdateSessionAsync(DateTimeOffset validUntil, ClaimsPrincipal claimsPrincipal, TokenResponse tokenResponse, string sessionState, string oidcDiscoveryUri, string clientId)
        {
            var claimsIdentity = claimsPrincipal.Identities.First();
            var claimsList     = claimsIdentity.Claims.Select(c => new ClaimValue {
                Type = c.Type, Value = c.Value
            }).ToList();

            var userSession = new OidcUserSession
            {
                ValidUntil         = validUntil,
                Claims             = claimsList,
                AuthenticationType = claimsIdentity.AuthenticationType,
                IdToken            = tokenResponse.IdToken,
                AccessToken        = tokenResponse.AccessToken,
                RefreshToken       = tokenResponse.RefreshToken,
                SessionState       = sessionState,
                OidcDiscoveryUri   = oidcDiscoveryUri,
                ClientId           = clientId
            };
            await sessionStorage.SetItemAsync(userSessionKey, userSession);

            NotifyAuthenticationStateChanged(GetAuthenticationStateAsync());
            return(userSession);
        }
 /// <summary>
 ///     Converts a JWT token-response endpoint message into a Keycloak identity
 /// </summary>
 /// <param name="parameters"></param>
 /// <param name="message"></param>
 /// <returns></returns>
 public static Task<KeycloakIdentity> ConvertFromTokenResponseAsync(IKeycloakParameters parameters,
     TokenResponse message)
 {
     if (parameters == null) throw new ArgumentNullException(nameof(parameters));
     if (message == null) throw new ArgumentNullException(nameof(message));
     return ConvertFromJwtAsync(parameters, message.AccessToken, message.RefreshToken, message.IdToken);
 }
 /// <summary>Verifies that the token response contains the expected data.</summary>
 /// <param name="response">The token response</param>
 private void SubtestTokenResponse(TokenResponse response)
 {
     Assert.That(response.RefreshToken, Is.EqualTo("r"));
     Assert.That(response.ExpiresInSeconds, Is.EqualTo(100));
     Assert.That(response.Scope, Is.EqualTo("b"));
 }
        private HttpResponseMessage CreateTokenResponse(GenericXmlSecurityToken token, string scope)
        {
            var response = new TokenResponse();

            if (ConfigurationRepository.AdfsIntegration.PassThruAuthenticationToken)
            {
                response.AccessToken = token.TokenXml.OuterXml;
                response.ExpiresIn = (int)(token.ValidTo.Subtract(DateTime.UtcNow).TotalSeconds);
            }
            else
            {
                var bridge = new AdfsBridge(ConfigurationRepository);

                response = bridge.ConvertSamlToJwt(token.ToSecurityToken(), scope);
            }

            return Request.CreateResponse<TokenResponse>(HttpStatusCode.OK, response);
        }
Ejemplo n.º 38
0
 public void InvalidateToken()
 {
     _tokenResponse = null;
 }
        public ActionResult <SignInResultModel> RefreshToAccess(
            [FromForm] string sRefreshToken)
        {
            //결과용
            ApiResultReady rrResult = new ApiResultReady(this);
            //엑세스 토큰 갱신용 모델
            SignInResultModel rmResult = new SignInResultModel();

            rrResult.ResultObject = rmResult;

            //API 호출 시간
            DateTime dtNow = DateTime.Now;

            //리플레시 토큰 갱신 시도 기록
            GlobalSign.LogAdd_DB(
                1
                , ModelDB.UserSignLogType.RefreshToken
                , 0
                , string.Format("RefreshToAccess 시도 : {0}", sRefreshToken));


            //토큰 갱신 요청
            TokenResponse tr = GlobalStatic.TokenProc.RefreshTokenAsync(sRefreshToken).Result;

            //기존 로그인한 유저 검색
            UserSignIn itemUSI = null;


            if (true == tr.IsError)
            {//토큰 갱신 실패
                //DB에 있는 리플레시 토큰은 수동으로 확인해서 갱신해준다.
                //토큰 정보는 메모리에 저장되기 때문에 서버가 내려갔다 올라오면 토큰정보가 날아간다.
                //이런 예외를 처리하기위해 수동으로 리플레시 토큰을 갱신해야한다.
                using (SpaNetCoreFoundationContext db1 = new SpaNetCoreFoundationContext())
                {
                    //기존 로그인한 유저 검색
                    itemUSI
                        = db1.UserSignIn
                          .Where(m => m.RefreshToken == sRefreshToken)
                          .FirstOrDefault();

                    if (null == itemUSI)
                    {//정보 자체가 없다.
                        rrResult.InfoCode = "-101";
                        rrResult.Message  = "갱신실패 : 인증 정보가 없습니다.";
                    }
                    else if (dtNow > itemUSI.RefreshDate)
                    {//인증정보의 유효기간이 지났다.
                        rrResult.InfoCode = "-102";
                        rrResult.Message  = "갱신실패 : 인증가능 기간이 지났습니다.";
                    }
                    else
                    {//토큰이 살아있다.
                        //유저를 검색한다.
                        User findUser
                            = db1.User
                              .Where(w => w.idUser == itemUSI.idUser)
                              .FirstOrDefault();

                        //토큰을 갱신한다.
                        tr
                            = GlobalStatic.TokenProc
                              .RequestTokenAsync(findUser.SignEmail, findUser.Password)
                              .Result;
                    }
                } //end using db1
            }     //end if (true == tr.IsError)


            if (true == rrResult.IsSuccess())
            {
                if (true == tr.IsError)
                {
                    rrResult.InfoCode = "1";
                    rrResult.Message  = "토큰 갱신에 실패하였습니다.";
                }
            }


            if (true == rrResult.IsSuccess())
            {//에러가 없다.
                //유저 정보를 받는다.
                UserInfoResponse inrUser
                    = GlobalStatic.TokenProc.UserInfoAsync(tr.AccessToken).Result;

                //유저 정보 추출
                ClaimModel cm = new ClaimModel(inrUser.Claims);

                using (SpaNetCoreFoundationContext db1 = new SpaNetCoreFoundationContext())
                {
                    //기존 로그인한 유저 검색
                    itemUSI
                        = db1.UserSignIn
                          .Where(m => m.idUser == cm.id_int)
                          .FirstOrDefault();

                    if (null == itemUSI)
                    {//기존 로그인 정보가 없다,
                        //이러면 강제로 토큰이 상실된 것일 수 있다.
                        rrResult.InfoCode = "1";
                        rrResult.Message  = "토큰 갱신에 실패하였습니다.";
                    }
                    else
                    {
                        //로그인 되어있는 유저정보 수정
                        itemUSI.RefreshToken = tr.RefreshToken;
                        itemUSI.RefreshDate  = dtNow.AddDays(30);

                        //db 적용
                        db1.SaveChanges();


                        //유저에게 전달할 정보 만들기
                        rmResult.idUser   = cm.id_int;
                        rmResult.Email    = cm.email;
                        rmResult.ViewName = rmResult.Email;

                        rmResult.access_token  = tr.AccessToken;
                        rmResult.refresh_token = tr.RefreshToken;


                        //기록
                        GlobalSign.LogAdd_DB(
                            1
                            , ModelDB.UserSignLogType.RefreshToken
                            , cm.id_int
                            , string.Format("RefreshToAccess 성공 : {0}", rmResult.Email));
                    }
                }//end using db1
            }

            return(rrResult.ToResult(rmResult));
        }
Ejemplo n.º 40
0
 public UserManager(TokenResponse token) : this()
 {
     this.token = token;
 }
Ejemplo n.º 41
0
 /// <summary>
 /// Creates an AuthToken from a TokenResponse.
 /// </summary>
 /// <param name="response">The response.</param>
 /// <returns>An AuthToken</returns>
 internal static AuthToken FromTokenResponse(TokenResponse response)
 {
     if (response != null)
     {
         return new AuthToken
         {
             AccessToken = response.AccessToken,
             ExpiresUtc = response.ExpiresUtc,
             RefreshToken = response.RefreshToken,
             Territory = response.Territory,
             UserId = response.UserId
         };
     }
     else
     {
         return null;
     }
 }
        /// <summary>
        /// Parses the ExtraData collection
        /// </summary>
        private string ParseExtraData(TokenResponse<AccessToken> result, string key)
        {
            if (!result.ExtraData.Contains(key))
                return null;

            var data = result.ExtraData[key];

            if (data == null)
                return null;
            else
                return Uri.UnescapeDataString(data.FirstOrDefault());
        }
Ejemplo n.º 43
0
 public static HttpResponseMessage CreateTokenResponse(this HttpRequestMessage request, TokenResponse response)
 {
     Tracing.Information("Returning token response.");
     return request.CreateResponse(HttpStatusCode.OK, response);
 }
Ejemplo n.º 44
-1
        public async Task GetAll_ReturnUsersOrderedProduct()
        {

            var userOrderedProducts = await _unitOfWork.Orders.FindAsync(c => c.User.UserName == "user");
            var client = new RestClient("http://localhost:55258/");
            var request = new RestRequest("api/order/", Method.GET);
           
            var token = new TokenResponse("user", "123456");
            request.AddHeader("Authorization", token.TokenType + " " + token.AccessToken);
            var orderedProducts = client.Execute<List<Product>>(request) as RestResponse<List<Product>>;
            Assert.IsNotNull(orderedProducts);
            Assert.AreEqual(userOrderedProducts.Count(), orderedProducts.Data.Count);
        }