public HttpResponseMessage Post(TokenRequest request)
        {
            Tracing.Start("OIDC Token Endpoint");

            ValidatedRequest validatedRequest;

            try
            {
                var validator = new TokenRequestValidator(Clients, Grants);
                validatedRequest = validator.Validate(request, ClaimsPrincipal.Current);
            }
            catch (TokenRequestValidationException ex)
            {
                Tracing.Error("Aborting OIDC token request");
                return Request.CreateOAuthErrorResponse(ex.OAuthError);
            }

            // switch over the grant type
            if (validatedRequest.GrantType.Equals(OAuth2Constants.GrantTypes.AuthorizationCode))
            {
                return ProcessAuthorizationCodeRequest(validatedRequest);
            }
            if (string.Equals(validatedRequest.GrantType, OAuth2Constants.GrantTypes.RefreshToken))
            {
                return ProcessRefreshTokenRequest(validatedRequest);
            }

            Tracing.Error("unsupported grant type: " + request.Grant_Type);
            return Request.CreateOAuthErrorResponse(OAuth2Constants.Errors.UnsupportedGrantType);
        }
示例#2
0
        public override TokenResponse callTokenEndpoint(TokenRequest req)
        {
            TokenResponse tr = base.callTokenEndpoint(req);

            CST_Ops.recordme(new OpenIDConnectNameSpace.AuthorizationServerImpl(), req, tr, typeof(OpenIDProvider).GetMethod("TokenEndpoint"), "live.com", false, false);

            return tr;
        }
        public async Task<string> GetTokenAsync()
        {
            var request = new TokenRequest
            {
                RequestBody = new TokenRequest.Body { App = application, Login = login, Pass = password, }
            };

            var response = hitboxApi.SendAsync(request);

            return (await response).AuthToken;
        }
示例#4
0
        /// <summary>
        /// Creates a unique access token that is stored for the duration of the session.
        /// </summary>
        /// <remarks>you must call Logout() to destroy the access token, even if Login() was never called...
        /// Note: Login() is only relevant if you have methods that use the Validate.UserCredentials option.</remarks>
        public TokenResponse GetToken(TokenRequest request)
        {
            var response = new TokenResponse { CorrelationId = request.RequestId };

            if (!ValidRequest(request, response, Validate.ClientTag))
                return response;

            // issue a session-based access token
            _accessToken = Guid.NewGuid().ToString();// Console.WriteLine("Access Token granted: " + _accessToken);

            response.AccessToken = _accessToken;
            return response;
        }
        /// <summary>
        /// GetToken must be the first call into web service. 
        /// This is irrespective of whether user is logging in or not.
        /// </summary>
        /// <returns>Unique access token that is valid for the duration of the session.</returns>
        public string GetToken()
        {
            TokenRequest request = new TokenRequest();
            request.RequestId = NewRequestId;
            request.ClientTag = ClientTag;

            TokenResponse response = ActionServiceClient.GetToken(request);

            if (request.RequestId != response.CorrelationId)
                throw new ApplicationException("GetToken: RequestId and CorrelationId do not match.");

            return response.AccessToken;
        }
 /// <summary>
 /// The entry point into the program
 /// </summary>
 /// <param name="args">Not used</param>
 public static void Main(string[] args)
 {
     try
     {
         TokenRequest requestor = new TokenRequest(clientId, clientSecret);
         String token = requestor.Execute();
         Console.WriteLine("Your token is: " + token);
     }
     catch(Exception e)
     {
         Console.WriteLine(e.Message);
         throw;
     }
 }
 private string GetNewToken()
 {
     TokenRequest token_request = new TokenRequest(username_, pwhash_);
     TokenResponse token_response = JSONClient.GetJSONResponse<TokenResponse>(kTokenRequestUrl, token_request);
     switch(token_response.code)
     {
         case 0:
             token_ = token_response.token;
             Console.WriteLine("Successfully requested access token: {0}", token_);
             last_updated_ = DateTime.Now;
             token_manager_ = this;
             return token_;
         case 3000:
             throw new ServerDownException(token_response.response_code, token_response.message);
         default:
             throw new Exception("Unrecognized error - bad password? response_code:" + token_response.response_code +
                 " message: " + token_response.message + " code: " + token_response.code);
     }
 }
示例#8
0
        /// <summary>
        /// Static constructor
        /// </summary>
        static Model()
        {
            Service = new ActionServiceClient();

            // Gets client tag from app.config configuration file
            ClientTag = ConfigurationManager.AppSettings.Get("ClientTag");

            // Retrieve AccessToken as first step
            TokenRequest request = new TokenRequest();
            request.RequestId = NewRequestId;
            request.ClientTag = ClientTag;

            TokenResponse response = null;
            SafeProxy.DoAction<ActionServiceClient>(Service, client =>
                { response = client.GetToken(request); });

            // Store access token for subsequent service calls.
            AccessToken = response.AccessToken;
        }
        public async Task <IActionResult> CreateToken(CreateTokenViewModel model)
        {
            if (!ModelState.IsValid)
            {
                return(View(model));
            }
            model.Label = model.Label ?? String.Empty;
            var userId = GetUserId();

            if (userId == null)
            {
                return(Challenge(AuthenticationSchemes.Cookie));
            }

            var store   = CurrentStore;
            var storeId = CurrentStore?.Id;

            if (storeId == null)
            {
                storeId = model.StoreId;
                store   = await _Repo.FindStore(storeId, userId);

                if (store == null)
                {
                    return(Challenge(AuthenticationSchemes.Cookie));
                }
            }
            var tokenRequest = new TokenRequest()
            {
                Label = model.Label,
                Id    = model.PublicKey == null ? null : NBitpayClient.Extensions.BitIdExtensions.GetBitIDSIN(new PubKey(model.PublicKey))
            };

            string pairingCode = null;

            if (model.PublicKey == null)
            {
                tokenRequest.PairingCode = await _TokenRepository.CreatePairingCodeAsync();

                await _TokenRepository.UpdatePairingCode(new PairingCodeEntity()
                {
                    Id    = tokenRequest.PairingCode,
                    Label = model.Label,
                });

                await _TokenRepository.PairWithStoreAsync(tokenRequest.PairingCode, storeId);

                pairingCode = tokenRequest.PairingCode;
            }
            else
            {
                pairingCode = ((DataWrapper <List <PairingCodeResponse> >) await _TokenController.Tokens(tokenRequest)).Data[0].PairingCode;
            }

            GeneratedPairingCode = pairingCode;
            return(RedirectToAction(nameof(RequestPairing), new
            {
                pairingCode = pairingCode,
                selectedStore = storeId
            }));
        }
示例#10
0
        /// <summary>
        ///
        /// </summary>
        /// <exception cref="iimmpact.Client.ApiException">Thrown when fails to make API call</exception>
        /// <param name="tokenRequest"></param>
        /// <returns>Task of TokenResponse</returns>
        public async System.Threading.Tasks.Task <TokenResponse> V1TokenPostAsync(TokenRequest tokenRequest)
        {
            ApiResponse <TokenResponse> localVarResponse = await V1TokenPostAsyncWithHttpInfo(tokenRequest);

            return(localVarResponse.Data);
        }
 /// <summary>
 /// Obtains an <see cref="AccessToken"/> token for a user account silently if the user has already authenticated to another Microsoft application participating in SSO through the MSAL cache
 /// </summary>
 /// <param name="request">The details of the authentication request.</param>
 /// <param name="cancellationToken">A <see cref="CancellationToken"/> controlling the request lifetime</param>
 /// <returns>An <see cref="AccessToken"/> which can be used to authenticate service client calls</returns>
 public override AccessToken GetToken(TokenRequest request, CancellationToken cancellationToken = default)
 {
     return(GetTokenAsync(request, cancellationToken).GetAwaiter().GetResult());
 }
 public long AcquireTokenBestEffort(long upperLimitCount)
 {
     TokenRequest request = new TokenRequest();
     request.type = TokenRequestType.BEST_EFFORT;
     request.channel = _channel;
     request.initialBC = _bc;
     request.requestToken = upperLimitCount;
     if (_simpleBWControlService.ProcessRequest(request))
     {
         return (long)request.requestToken;
     }
     else
     {
         return 0;
     }
 }
        /// <summary>
        /// Login
        /// </summary>
        /// <exception cref="IO.Swagger.Client.ApiException">Thrown when fails to make API call</exception>
        /// <param name="request">Credenziali di login</param>
        /// <returns>ApiResponse of TokenResponse</returns>
        public ApiResponse <TokenResponse> TokenWithHttpInfo(TokenRequest request)
        {
            // verify the required parameter 'request' is set
            if (request == null)
            {
                throw new ApiException(400, "Missing required parameter 'request' when calling AuthorizationApi->Token");
            }

            var    localVarPath         = "/api/v2/account/token";
            var    localVarPathParams   = new Dictionary <String, String>();
            var    localVarQueryParams  = new List <KeyValuePair <String, String> >();
            var    localVarHeaderParams = new Dictionary <String, String>(Configuration.DefaultHeader);
            var    localVarFormParams   = new Dictionary <String, String>();
            var    localVarFileParams   = new Dictionary <String, FileParameter>();
            Object localVarPostBody     = null;

            // to determine the Content-Type header
            String[] localVarHttpContentTypes = new String[] {
                "application/json",
                "text/json",
                "application/xml",
                "text/xml",
                "application/x-www-form-urlencoded"
            };
            String localVarHttpContentType = Configuration.ApiClient.SelectHeaderContentType(localVarHttpContentTypes);

            // to determine the Accept header
            String[] localVarHttpHeaderAccepts = new String[] {
                "application/json",
                "text/json"
            };
            String localVarHttpHeaderAccept = Configuration.ApiClient.SelectHeaderAccept(localVarHttpHeaderAccepts);

            if (localVarHttpHeaderAccept != null)
            {
                localVarHeaderParams.Add("Accept", localVarHttpHeaderAccept);
            }

            if (request != null && request.GetType() != typeof(byte[]))
            {
                localVarPostBody = Configuration.ApiClient.Serialize(request); // http body (model) parameter
            }
            else
            {
                localVarPostBody = request; // byte array
            }


            // make the HTTP request
            IRestResponse localVarResponse = (IRestResponse)Configuration.ApiClient.CallApi(localVarPath,
                                                                                            Method.POST, localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarFileParams,
                                                                                            localVarPathParams, localVarHttpContentType);

            int localVarStatusCode = (int)localVarResponse.StatusCode;

            if (ExceptionFactory != null)
            {
                Exception exception = ExceptionFactory("Token", localVarResponse);
                if (exception != null)
                {
                    throw exception;
                }
            }

            return(new ApiResponse <TokenResponse>(localVarStatusCode,
                                                   localVarResponse.Headers.ToDictionary(x => x.Name, x => x.Value.ToString()),
                                                   (TokenResponse)Configuration.ApiClient.Deserialize(localVarResponse, typeof(TokenResponse))));
        }
 private bool ProcessBestEffortRequest(TokenRequest request, BWContext context)
 {
     if (context.bwConfig[3] >= 0)
     {
         if (context.tokenRc[3] >= request.requestToken)
         {
             context.tokenRc[3] -= request.requestToken;
         }
         else
         {
             request.requestToken = context.tokenRc[3];
             context.tokenRc[3] = 0;
         }
     }
     else
     {
         if (context.tokenRc[request.channel] < 0) return true;
         if (context.tokenRc[request.channel] >= request.requestToken)
         {
             context.tokenRc[request.channel] -= request.requestToken;
         }
         else
         {
             request.requestToken = context.tokenRc[request.channel];
             context.tokenRc[request.channel] = 0;
         }
     }
     if (request.requestToken == 0) return false;
     else return true;
 }
 public void RequestOAuthToken(TokenRequest tokenRequest)
 {
     SharpConnectionHelperSingleton.Instance.RequestOAuthToken(tokenRequest);
 }
        public TokenRequest constructTokenRequest(AuthenticationResponse codeResp)
        {
            TokenRequest tokenReq = new TokenRequest();
            tokenReq.code = codeResp.code;
            tokenReq.grant_type = "authorization_code";
            tokenReq.redirect_uri = return_uri;
            tokenReq.client_id = client_id;
            tokenReq = pre_send_TokenRequest(tokenReq);
            
            CST_Ops.recordme(this, codeResp, tokenReq);

            return tokenReq;
        }
示例#17
0
        public async Task <IActionResult> CreateToken(string storeId, CreateTokenViewModel model)
        {
            if (!ModelState.IsValid)
            {
                return(View(model));
            }
            model.Label = model.Label ?? String.Empty;
            storeId     = model.StoreId ?? storeId;
            var userId = GetUserId();

            if (userId == null)
            {
                return(Unauthorized());
            }
            var store = await _Repo.FindStore(storeId, userId);

            if (store == null)
            {
                return(Unauthorized());
            }
            if (store.Role != StoreRoles.Owner)
            {
                StatusMessage = "Error: You need to be owner of this store to request pairing codes";
                return(RedirectToAction(nameof(UserStoresController.ListStores), "UserStores"));
            }

            var tokenRequest = new TokenRequest()
            {
                Facade = model.Facade,
                Label  = model.Label,
                Id     = model.PublicKey == null ? null : NBitpayClient.Extensions.BitIdExtensions.GetBitIDSIN(new PubKey(model.PublicKey))
            };

            string pairingCode = null;

            if (model.PublicKey == null)
            {
                tokenRequest.PairingCode = await _TokenRepository.CreatePairingCodeAsync();

                await _TokenRepository.UpdatePairingCode(new PairingCodeEntity()
                {
                    Id     = tokenRequest.PairingCode,
                    Facade = model.Facade,
                    Label  = model.Label,
                });

                await _TokenRepository.PairWithStoreAsync(tokenRequest.PairingCode, storeId);

                pairingCode = tokenRequest.PairingCode;
            }
            else
            {
                pairingCode = ((DataWrapper <List <PairingCodeResponse> >) await _TokenController.Tokens(tokenRequest)).Data[0].PairingCode;
            }

            GeneratedPairingCode = pairingCode;
            return(RedirectToAction(nameof(RequestPairing), new
            {
                pairingCode = pairingCode,
                selectedStore = storeId
            }));
        }
示例#18
0
        /// <summary>
        /// Gets unique session based token that is valid for the duration of the session.
        /// </summary>
        /// <param name="request">Token request message.</param>
        /// <returns>Token response message.</returns>
        public TokenResponse GetToken(TokenRequest request)
        {
            TokenResponse response = new TokenResponse();
            response.CorrelationId = request.RequestId;

            // Validate client tag only
            if (!ValidRequest(request, response, Validate.ClientTag))
                return response;

            // Note: these are session based and expire when session expires.
            _accessToken = Guid.NewGuid().ToString();
            _shoppingCart = new ShoppingCart(defaultShippingMethod);

            response.AccessToken = _accessToken;
            return response;
        }
示例#19
0
 public async Task <TokenResponse> GetAccessTokenAsync(TokenRequest request)
 {
     return(await this.PostAsync <TokenResponse>("tokens", request).ConfigureAwait(false));
 }
        private static async Task MainAsync()
        {
            //discover all the endpoints using metadata identity server
            var msg = DateTime.Now.AddMinutes(18);

            var dif = DateTime.Now.Subtract(msg).TotalMinutes;

            var httpClientRo = new HttpClient();

            var discoRO = await httpClientRo.GetDiscoveryDocumentAsync("http://localhost:5000");

            if (discoRO.IsError)
            {
                System.Console.WriteLine(discoRO.Error);
                return;
            }
            // Grab a Bearer Token using ResouceOwnerPassword grant type

            var tokenclientPro = new TokenClient(httpClientRo, new TokenClientOptions
            {
                Address      = discoRO.TokenEndpoint,
                ClientId     = "ro.client",
                ClientSecret = "secret"
            });

            var tokenResponseRo = await tokenclientPro.RequestPasswordTokenAsync
                                      ("Caah", "password", "bankOfDotNetApi");

            try
            {
                if (tokenResponseRo.IsError)
                {
                    System.Console.WriteLine(tokenResponseRo.ErrorDescription);
                    return;
                }
                System.Console.WriteLine(tokenResponseRo.Json);
            }
            catch (System.Exception ex)
            {
                System.Console.WriteLine(ex.Message);
            }

            var httpClient = new HttpClient();

            var discovery = await httpClient.GetDiscoveryDocumentAsync("http://localhost:5000");

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

            using var tokenRequest = new TokenRequest
                  {
                      Address      = discovery.TokenEndpoint,
                      ClientId     = "client",
                      ClientSecret = "secret",
                      Parameters   =
                      {
                          { "scope",      "bankOfDotNetApi"    },
                          { "grant_type", "client_credentials" }
                      }
                  };
            var tokenResponse = await httpClient.RequestTokenAsync(tokenRequest);

            if (tokenResponse.IsError)
            {
                System.Console.WriteLine(tokenResponse.ErrorDescription);
                return;
            }
            System.Console.WriteLine(tokenResponse.Json);
        }
        public virtual TokenResponse callTokenEndpoint(TokenRequest req)
        {
            JsonDataStrcuture JsonDataStrcuture = new JsonDataStrcuture();

            string postContent = String.Format("client_id={0}&redirect_uri={1}&client_secret={2}&code={3}&grant_type=authorization_code",
                HttpUtility.UrlEncode(req.client_id),
                HttpUtility.UrlEncode(req.redirect_uri),
                HttpUtility.UrlEncode(client_secret),
                HttpUtility.UrlEncode(req.code),
                HttpUtility.UrlEncode(req.grant_type));

            HttpWebResponse response = HTTP.HTTPComm.HttpReq(TokenEndpointUrl, postContent, "POST");
            if (response != null)
            {
                DataContractJsonSerializer serializer = new DataContractJsonSerializer(typeof(JsonDataStrcuture));
                JsonDataStrcuture = serializer.ReadObject(response.GetResponseStream()) as JsonDataStrcuture;
                if (JsonDataStrcuture != null)
                {
                    TokenResponse TokenResponse = new TokenResponse();
                    if (TokenResponse.parseJasonDataStructure(JsonDataStrcuture, client_secret))
                    {
                        return TokenResponse;
                    }
                    else
                        return null;
                }
            }
            return null;
        }
        public Token getToken(string ServiceID, string access_id, List <string> scope, string ForwardIP = null, bool UseStaticIP = false, bool UseLocalTimeYN = false)
        {
            if (string.IsNullOrEmpty(ServiceID))
            {
                throw new LinkhubException(-99999999, "ServiceID is Not entered");
            }

            Token result = new Token();

            string URI = (UseStaticIP ? ServiceURL_REAL_GA : ServiceURL_REAL) + "/" + ServiceID + "/Token";

            string xDate = getTime(UseStaticIP, UseLocalTimeYN);

            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(URI);

            if (this._ProxyYN == true)
            {
                WebProxy proxyRequest = new WebProxy();

                Uri proxyURI = new Uri(this._ProxyAddress);
                proxyRequest.Address     = proxyURI;
                proxyRequest.Credentials = new NetworkCredential(this._ProxyUserName, this._ProxyPassword);
                request.Proxy            = proxyRequest;
            }

            request.Headers.Add("x-lh-date", xDate);

            request.Headers.Add("x-lh-version", APIVersion);

            if (ForwardIP != null)
            {
                request.Headers.Add("x-lh-forwarded", ForwardIP);
            }

            //request 메시지 access_id 사업자번호, 서비스 scope
            TokenRequest _TR = new TokenRequest();

            _TR.access_id = access_id;
            _TR.scope     = scope;

            string postData = "";

            using (MemoryStream ms = new MemoryStream())
            {
                //개체를 JsonTyeString으로 변경 후 postData에 삽입
                DataContractJsonSerializer ser = new DataContractJsonSerializer(typeof(TokenRequest));
                ser.WriteObject(ms, _TR);
                ms.Seek(0, SeekOrigin.Begin);
                postData = new StreamReader(ms).ReadToEnd();
            }

            string HMAC_target = "POST\n";

            HMAC_target += Convert.ToBase64String(MD5.Create().ComputeHash(Encoding.UTF8.GetBytes(postData))) + "\n";
            HMAC_target += xDate + "\n";
            if (ForwardIP != null)
            {
                HMAC_target += ForwardIP + "\n";
            }
            HMAC_target += APIVersion + "\n";
            HMAC_target += "/" + ServiceID + "/Token";

            HMACSHA1 hmac = new HMACSHA1(Convert.FromBase64String(_SecretKey));

            //HMAC_tartget을 비밀키 이용해서 hash 데이터로 만들고 base64인코딩 String으로
            string bearerToken = Convert.ToBase64String(hmac.ComputeHash(Encoding.UTF8.GetBytes(HMAC_target)));

            //위에서 생성한 bearerToken Autorization 헤더에 value로
            request.Headers.Add("Authorization", "LINKHUB" + " " + _LinkID + " " + bearerToken);

            request.Method = "POST";

            byte[] btPostDAta = Encoding.UTF8.GetBytes(postData);

            request.ContentLength = btPostDAta.Length;

            request.GetRequestStream().Write(btPostDAta, 0, btPostDAta.Length);

            try
            {
                HttpWebResponse response   = (HttpWebResponse)request.GetResponse();
                Stream          stReadData = response.GetResponseStream();
                //Json스트림을 Token 개체로 받기위해서 DataContractJsonSerializer 인스턴스 생성
                DataContractJsonSerializer ser = new DataContractJsonSerializer(typeof(Token));

                //Json타임 스트림을 개체로 변환
                //Token이지
                result = (Token)ser.ReadObject(stReadData);
            }
            catch (Exception we)
            {
                if (we is WebException && ((WebException)we).Response != null)
                {
                    Stream stReadData = ((WebException)we).Response.GetResponseStream();
                    DataContractJsonSerializer ser = new DataContractJsonSerializer(typeof(Error));
                    Error t = (Error)ser.ReadObject(stReadData);

                    throw new LinkhubException(t.code, t.message);
                }

                throw new LinkhubException(-99999999, we.Message);
            }

            return(result);
        }
 private bool ProcessBlockingRequest(TokenRequest request, BWContext context)
 {
     context.timeToWait = request.timeout;
     do
     {
         if (context.bwConfig[3] >= 0)
         {
             if (context.tokenRc[3] >= request.requestToken)
             {
                 context.tokenRc[3] -= request.requestToken;
                 request.timeout = context.timeToWait;
                 return true;
             }
         }
         else
         {
             if (context.tokenRc[request.channel] < 0) return true;
             if (context.tokenRc[request.channel] >= request.requestToken)
             {
                 context.tokenRc[request.channel] -= request.requestToken;
                 request.timeout = context.timeToWait;
                 return true;
             }
         }
         long beforeWait = System.Environment.TickCount;
         try
         {
             Monitor.Wait(this, (int)context.timeToWait);
         }
         catch (ThreadInterruptedException)
         {
         }
         context.timeToWait -= System.Environment.TickCount - beforeWait;
     } while (context.timeToWait > 0);
     return false;
 }
示例#24
0
 public static bool IsMatchRedirectUri(this OAuthClient oAuthClient, TokenRequest request)
 {
     return(request.grant_type != GrandType.AuthorizationCode ||
            IsMatchRedirectUri(oAuthClient, request.redirect_uri));
 }
 public bool AcquireToken(long tokenCount, long wait)
 {
     if (wait < 0) return false;
     TokenRequest request = new TokenRequest();
     request.type = TokenRequestType.BLOCKING;
     request.timeout = wait;
     request.channel = _channel;
     request.initialBC = _bc;
     request.requestToken = tokenCount;
     return _simpleBWControlService.ProcessRequest(request);
 }
示例#26
0
 public static bool IsCorrectSecret(this OAuthClient oAuthClient, TokenRequest request)
 {
     return(request.grant_type != GrandType.AuthorizationCode ||
            PasswordUtils.IsVerifiedPassword(request.client_secret, oAuthClient.ClientSecret));
 }
        private HttpResponseMessage ValidateRequest(TokenRequest request, out Client client)
        {
            client = null;

            if (request == null)
            {
                return OAuthErrorResponseMessage(OAuth2Constants.Errors.InvalidRequest);
            }

            // grant type is required
            if (string.IsNullOrWhiteSpace(request.Grant_Type))
            {
                return OAuthErrorResponseMessage(OAuth2Constants.Errors.UnsupportedGrantType);
            }

            // check supported grant types
            if (!request.Grant_Type.Equals(OAuth2Constants.GrantTypes.AuthorizationCode) &&
                !request.Grant_Type.Equals(OAuth2Constants.GrantTypes.Password) &&
                !request.Grant_Type.Equals(OAuth2Constants.GrantTypes.RefreshToken))
            {
                return OAuthErrorResponseMessage(OAuth2Constants.Errors.UnsupportedGrantType);
            }

            // resource owner password flow requires a well-formed scope
            if (request.Grant_Type.Equals(OAuth2Constants.GrantTypes.Password))
            {
                Uri appliesTo;
                if (!Uri.TryCreate(request.Scope, UriKind.Absolute, out appliesTo))
                {
                    Tracing.Error("Malformed scope: " + request.Scope);
                    return OAuthErrorResponseMessage(OAuth2Constants.Errors.InvalidScope);
                }

                Tracing.Information("OAuth2 endpoint called for scope: " + request.Scope);
            }

            if (!ValidateClient(out client))
            {
                Tracing.Error("Invalid client: " + ClaimsPrincipal.Current.Identity.Name);
                return OAuthErrorResponseMessage(OAuth2Constants.Errors.InvalidClient);
            }

            // validate grant types against global and client configuration
            if (request.Grant_Type.Equals(OAuth2Constants.GrantTypes.AuthorizationCode))
            {
                if (!ConfigurationRepository.OAuth2.EnableCodeFlow ||
                    !client.AllowCodeFlow)
                {
                    Tracing.Error("Code flow not allowed for client");
                    return OAuthErrorResponseMessage(OAuth2Constants.Errors.UnsupportedGrantType);
                }
            }

            if (request.Grant_Type.Equals(OAuth2Constants.GrantTypes.Password))
            {
                if (!ConfigurationRepository.OAuth2.EnableResourceOwnerFlow ||
                    !client.AllowResourceOwnerFlow)
                {
                    Tracing.Error("Resource owner password flow not allowed for client");
                    return OAuthErrorResponseMessage(OAuth2Constants.Errors.UnsupportedGrantType);
                }
            }

            if (request.Grant_Type.Equals(OAuth2Constants.GrantTypes.RefreshToken))
            {
                if (!client.AllowRefreshToken)
                {
                    Tracing.Error("Refresh tokens not allowed for client");
                    return OAuthErrorResponseMessage(OAuth2Constants.Errors.UnsupportedGrantType);
                }
            }

            return null;
        }
 public AccountResult(TokenRequest tokenRequest)
 {
     Successed    = true;
     TokenRequest = tokenRequest;
 }
示例#29
0
        /// <summary>
        ///
        /// </summary>
        /// <exception cref="iimmpact.Client.ApiException">Thrown when fails to make API call</exception>
        /// <param name="tokenRequest"></param>
        /// <returns>TokenResponse</returns>
        public TokenResponse V1TokenPost(TokenRequest tokenRequest)
        {
            ApiResponse <TokenResponse> localVarResponse = V1TokenPostWithHttpInfo(tokenRequest);

            return(localVarResponse.Data);
        }
示例#30
0
        public async Task <IActionResult> PostFromJsonAsync([FromBody] TokenRequest tokenRequest)
        {
            // Look for the authorization header, since we MUST support this method of authorization
            // https://tools.ietf.org/html/rfc6749#section-2.3.1
            // Decode and parse the client id/secret from the header
            // Authorization is in a form of Bearer <encoded client and secret>
            // We accept two cases for the json post, if the json post contains the client secret and client credentials
            // then we process with that information, other we look for a header with a bearer token
            // and parse the response then. We fail when there is a client_secret or client_id in the header and json at the
            // same time.
            string[] clientIdAndSecret = new string[0];

            if (Request.Headers.ContainsKey("Authorization"))
            {
                string[] encodedClientAndSecret = Request.Headers["Authorization"]
                                                  .ToString()
                                                  .Split(' ');

                if (encodedClientAndSecret.Length != 2)
                {
                    _logger.Debug("Header is not in the form of Basic <encoded credentials>");
                    return(Unauthorized());
                }

                if (!encodedClientAndSecret[0].EqualsIgnoreCase("Basic"))
                {
                    _logger.Debug("Authorization scheme is not Basic");
                    return(Unauthorized(new TokenError(TokenErrorType.InvalidClient)));
                }

                try
                {
                    clientIdAndSecret = GetClientIdAndSecret(encodedClientAndSecret[1]);

                    if (clientIdAndSecret.Length != 2)
                    {
                        return(BadRequest(new TokenError(TokenErrorType.InvalidClient)));
                    }
                }
                catch (Exception)
                {
                    return(BadRequest(new TokenError(TokenErrorType.InvalidRequest)));
                }
            }

            if (clientIdAndSecret.Length == 2)
            {
                if (tokenRequest.Client_id != null || tokenRequest.Client_secret != null)
                {
                    return(BadRequest(new TokenError(TokenErrorType.InvalidClient)));
                }

                // Correct format will include 2 entries
                // format of the string is <client_id>:<client_secret>
                tokenRequest.Client_id     = clientIdAndSecret[0];
                tokenRequest.Client_secret = clientIdAndSecret[1];
            }

            if (tokenRequest.Client_id == null && tokenRequest.Client_secret == null)
            {
                return(Unauthorized());
            }

            // Handle token request
            var authenticationResult = await _requestProvider.HandleAsync(tokenRequest);

            if (authenticationResult.TokenError != null)
            {
                return(BadRequest(authenticationResult.TokenError));
            }

            return(Ok(authenticationResult.TokenResponse));
        }
示例#31
0
        /// <summary>
        ///
        /// </summary>
        /// <exception cref="iimmpact.Client.ApiException">Thrown when fails to make API call</exception>
        /// <param name="tokenRequest"></param>
        /// <returns>Task of ApiResponse (TokenResponse)</returns>
        public async System.Threading.Tasks.Task <ApiResponse <TokenResponse> > V1TokenPostAsyncWithHttpInfo(TokenRequest tokenRequest)
        {
            // verify the required parameter 'tokenRequest' is set
            if (tokenRequest == null)
            {
                throw new ApiException(400, "Missing required parameter 'tokenRequest' when calling AuthorizationTokenApi->V1TokenPost");
            }

            var    localVarPath         = "/v1/token";
            var    localVarPathParams   = new Dictionary <String, String>();
            var    localVarQueryParams  = new List <KeyValuePair <String, String> >();
            var    localVarHeaderParams = new Dictionary <String, String>(this.Configuration.DefaultHeader);
            var    localVarFormParams   = new Dictionary <String, String>();
            var    localVarFileParams   = new Dictionary <String, FileParameter>();
            Object localVarPostBody     = null;

            // to determine the Content-Type header
            String[] localVarHttpContentTypes = new String[] {
                "application/json"
            };
            String localVarHttpContentType = this.Configuration.ApiClient.SelectHeaderContentType(localVarHttpContentTypes);

            // to determine the Accept header
            String[] localVarHttpHeaderAccepts = new String[] {
                "application/json"
            };
            String localVarHttpHeaderAccept = this.Configuration.ApiClient.SelectHeaderAccept(localVarHttpHeaderAccepts);

            if (localVarHttpHeaderAccept != null)
            {
                localVarHeaderParams.Add("Accept", localVarHttpHeaderAccept);
            }

            if (tokenRequest != null && tokenRequest.GetType() != typeof(byte[]))
            {
                localVarPostBody = this.Configuration.ApiClient.Serialize(tokenRequest); // http body (model) parameter
            }
            else
            {
                localVarPostBody = tokenRequest; // byte array
            }


            // make the HTTP request
            IRestResponse localVarResponse = (IRestResponse)await this.Configuration.ApiClient.CallApiAsync(localVarPath,
                                                                                                            Method.POST, localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarFileParams,
                                                                                                            localVarPathParams, localVarHttpContentType);

            int localVarStatusCode = (int)localVarResponse.StatusCode;

            if (ExceptionFactory != null)
            {
                Exception exception = ExceptionFactory("V1TokenPost", localVarResponse);
                if (exception != null)
                {
                    throw exception;
                }
            }

            return(new ApiResponse <TokenResponse>(localVarStatusCode,
                                                   localVarResponse.Headers.ToDictionary(x => x.Name, x => x.Value.ToString()),
                                                   (TokenResponse)this.Configuration.ApiClient.Deserialize(localVarResponse, typeof(TokenResponse))));
        }
        private void SetupServices(IServiceCollection services)
        {
            string dynamicsOdataUri = _configuration["DYNAMICS_ODATA_URI"];
            string aadTenantId      = _configuration["DYNAMICS_AAD_TENANT_ID"];
            string serverAppIdUri   = _configuration["DYNAMICS_SERVER_APP_ID_URI"];
            string clientKey        = _configuration["DYNAMICS_CLIENT_KEY"];
            string clientId         = _configuration["DYNAMICS_CLIENT_ID"];

            string ssgUsername = _configuration["SSG_USERNAME"];
            string ssgPassword = _configuration["SSG_PASSWORD"];

            AuthenticationResult authenticationResult = null;



            services.AddCors(options =>
            {
                options.AddPolicy(MyAllowSpecificOrigins,
                                  builder =>
                {
                    builder.WithOrigins("https://localhost",
                                        "http://cannabis-licensing-dev.pathfinder.bcgov",
                                        "http://cannabis-licensing-test.pathfinder.bcgov",
                                        "http://cannabis-licensing-prod.pathfinder.bcgov",
                                        "https://dev.justice.gov.bc.ca",
                                        "https://test.justice.gov.bc.ca",
                                        "https://justice.gov.bc.ca");
                });
            });

            /*
             *
             * services.AddHttpClient("Dynamics", c =>
             *  {
             *
             *      c.BaseAddress = new Uri(dynamicsOdataUri);
             *  })
             *  .AddPolicyHandler(GetRetryPolicy())
             *  .AddPolicyHandler(GetCircuitBreakerPolicy());
             *
             * services.AddTransient(new Func<IServiceProvider, IDynamicsClient>((serviceProvider) =>
             * {
             *  var service = serviceProvider.GetRequiredService<System.Net.Http.IHttpClientFactory>();
             *  var httpClient = service.CreateClient("Dynamics");
             *
             *  IDynamicsClient client = new DynamicsClient(httpClient, _configuration);
             *
             *  return client;
             * }));
             */

            services.AddHttpClient <IDynamicsClient, DynamicsClient>();



            // add BCeID Web Services

            string bceidUrl    = _configuration["BCEID_SERVICE_URL"];
            string bceidSvcId  = _configuration["BCEID_SERVICE_SVCID"];
            string bceidUserid = _configuration["BCEID_SERVICE_USER"];
            string bceidPasswd = _configuration["BCEID_SERVICE_PASSWD"];

            services.AddTransient <BCeIDBusinessQuery>(_ => new BCeIDBusinessQuery(bceidSvcId, bceidUserid, bceidPasswd, bceidUrl));

            // add BC Express Pay (Bambora) service
            services.AddHttpClient <IBCEPService, BCEPService>()
            .AddPolicyHandler(GetRetryPolicy())
            .AddPolicyHandler(GetCircuitBreakerPolicy());

            // add the PDF client.
            services.AddHttpClient <IPdfService, PdfService>()
            .AddPolicyHandler(GetRetryPolicy())
            .AddPolicyHandler(GetCircuitBreakerPolicy());

            // add the GeoCoder Client.
            services.AddHttpClient <IGeocoderService, GeocoderService>()
            .AddPolicyHandler(GetRetryPolicy())
            .AddPolicyHandler(GetCircuitBreakerPolicy());

            // add the file manager.
            string fileManagerURI = _configuration["FILE_MANAGER_URI"];

            if (!_env.IsProduction()) // needed for macOS TLS being turned off
            {
                AppContext.SetSwitch("System.Net.Http.SocketsHttpHandler.Http2UnencryptedSupport", true);
            }
            if (!string.IsNullOrEmpty(fileManagerURI))
            {
                var httpClientHandler = new HttpClientHandler();

                if (!_env.IsProduction()) // Ignore certificate errors in non-production modes.
                                          // This allows you to use OpenShift self-signed certificates for testing.
                {
                    // Return `true` to allow certificates that are untrusted/invalid
                    httpClientHandler.ServerCertificateCustomValidationCallback =
                        HttpClientHandler.DangerousAcceptAnyServerCertificateValidator;
                }

                var httpClient = new HttpClient(httpClientHandler);
                // set default request version to HTTP 2.  Note that Dotnet Core does not currently respect this setting for all requests.
                httpClient.DefaultRequestVersion = HttpVersion.Version20;

                var initialChannel = GrpcChannel.ForAddress(fileManagerURI, new GrpcChannelOptions {
                    HttpClient = httpClient
                });

                var initialClient = new FileManagerClient(initialChannel);
                // call the token service to get a token.
                var tokenRequest = new TokenRequest()
                {
                    Secret = _configuration["FILE_MANAGER_SECRET"]
                };

                var tokenReply = initialClient.GetToken(tokenRequest);

                if (tokenReply != null && tokenReply.ResultStatus == ResultStatus.Success)
                {
                    // Add the bearer token to the client.

                    httpClient.DefaultRequestHeaders.Add("Authorization", $"Bearer {tokenReply.Token}");

                    var channel = GrpcChannel.ForAddress(fileManagerURI, new GrpcChannelOptions()
                    {
                        HttpClient = httpClient
                    });

                    services.AddTransient <FileManagerClient>(_ => new FileManagerClient(channel));
                }
            }
        }
示例#33
0
        public async Task <Response> GetTokenAsync(string urlBase, string servicePrefix, string controller, TokenRequest request)
        {
            try
            {
                string        requestString = JsonConvert.SerializeObject(request);
                StringContent content       = new StringContent(requestString, Encoding.UTF8, "application/json");
                HttpClient    client        = new HttpClient
                {
                    BaseAddress = new Uri(urlBase)
                };

                string url = $"{servicePrefix}{controller}";
                HttpResponseMessage response = await client.PostAsync(url, content);

                string result = await response.Content.ReadAsStringAsync();

                if (!response.IsSuccessStatusCode)
                {
                    return(new Response
                    {
                        IsSuccess = false,
                        Message = result,
                    });
                }

                TokenResponse token = JsonConvert.DeserializeObject <TokenResponse>(result);
                return(new Response
                {
                    IsSuccess = true,
                    Result = token
                });
            }
            catch (Exception ex)
            {
                return(new Response
                {
                    IsSuccess = false,
                    Message = ex.Message
                });
            }
        }
        public async Task <DataWrapper <List <PairingCodeResponse> > > Tokens([FromBody] TokenRequest request)
        {
            if (request == null)
            {
                throw new BitpayHttpException(400, "The request body is missing");
            }
            PairingCodeEntity pairingEntity = null;

            if (string.IsNullOrEmpty(request.PairingCode))
            {
                if (string.IsNullOrEmpty(request.Id) || !NBitpayClient.Extensions.BitIdExtensions.ValidateSIN(request.Id))
                {
                    throw new BitpayHttpException(400, "'id' property is required");
                }

                var pairingCode = await _TokenRepository.CreatePairingCodeAsync();

                await _TokenRepository.PairWithSINAsync(pairingCode, request.Id);

                pairingEntity = await _TokenRepository.UpdatePairingCode(new PairingCodeEntity()
                {
                    Id    = pairingCode,
                    Label = request.Label
                });
            }
            else
            {
                var sin = this.User.GetSIN() ?? request.Id;
                if (string.IsNullOrEmpty(sin) || !NBitpayClient.Extensions.BitIdExtensions.ValidateSIN(sin))
                {
                    throw new BitpayHttpException(400, "'id' property is required, alternatively, use BitId");
                }

                pairingEntity = await _TokenRepository.GetPairingAsync(request.PairingCode);

                if (pairingEntity == null)
                {
                    throw new BitpayHttpException(404, "The specified pairingCode is not found");
                }
                pairingEntity.SIN = sin;

                if (string.IsNullOrEmpty(pairingEntity.Label) && !string.IsNullOrEmpty(request.Label))
                {
                    pairingEntity.Label = request.Label;
                    await _TokenRepository.UpdatePairingCode(pairingEntity);
                }

                var result = await _TokenRepository.PairWithSINAsync(request.PairingCode, sin);

                if (result != PairingResult.Complete && result != PairingResult.Partial)
                {
                    throw new BitpayHttpException(400, $"Error while pairing ({result})");
                }
            }

            var pairingCodes = new List <PairingCodeResponse>
            {
                new PairingCodeResponse()
                {
                    Policies          = new Newtonsoft.Json.Linq.JArray(),
                    PairingCode       = pairingEntity.Id,
                    PairingExpiration = pairingEntity.Expiration,
                    DateCreated       = pairingEntity.CreatedTime,
                    Facade            = "merchant",
                    Token             = pairingEntity.TokenValue,
                    Label             = pairingEntity.Label
                }
            };

            return(DataWrapper.Create(pairingCodes));
        }
示例#35
0
 public async Task <Token> CreateToken(TokenRequest createTokenRequest)
 {
     return(await SendRequest <Token>(HttpMethod.Post, TOKENS_PATH, createTokenRequest));
 }
示例#36
0
        private async Task <AuthResult> LogInHelperAsync(string email, string hashedPassword, SymmetricCryptoKey key,
                                                         TwoFactorProviderType?twoFactorProvider = null, string twoFactorToken = null, bool?remember = null)
        {
            var storedTwoFactorToken = await _tokenService.GetTwoFactorTokenAsync(email);

            var appId = await _appIdService.GetAppIdAsync();

            var deviceRequest = new DeviceRequest(appId, _platformUtilsService);
            var request       = new TokenRequest
            {
                Email = email,
                MasterPasswordHash = hashedPassword,
                Device             = deviceRequest,
                Remember           = false
            };

            if (twoFactorToken != null && twoFactorProvider != null)
            {
                request.Provider = twoFactorProvider;
                request.Token    = twoFactorToken;
                request.Remember = remember.GetValueOrDefault();
            }
            else if (storedTwoFactorToken != null)
            {
                request.Provider = TwoFactorProviderType.Remember;
                request.Token    = storedTwoFactorToken;
            }

            var response = await _apiService.PostIdentityTokenAsync(request);

            ClearState();
            var result = new AuthResult
            {
                TwoFactor = response.Item2 != null
            };

            if (result.TwoFactor)
            {
                // Two factor required.
                var twoFactorResponse = response.Item2;
                Email = email;
                MasterPasswordHash = hashedPassword;
                _key = _setCryptoKeys ? key : null;
                TwoFactorProvidersData    = twoFactorResponse.TwoFactorProviders2;
                result.TwoFactorProviders = twoFactorResponse.TwoFactorProviders2;
                return(result);
            }

            var tokenResponse = response.Item1;

            if (tokenResponse.TwoFactorToken != null)
            {
                await _tokenService.SetTwoFactorTokenAsync(tokenResponse.TwoFactorToken, email);
            }
            await _tokenService.SetTokensAsync(tokenResponse.AccessToken, tokenResponse.RefreshToken);

            await _userService.SetInformationAsync(_tokenService.GetUserId(), _tokenService.GetEmail(),
                                                   _kdf.Value, _kdfIterations.Value);

            if (_setCryptoKeys)
            {
                await _cryptoService.SetKeyAsync(key);

                await _cryptoService.SetKeyHashAsync(hashedPassword);

                await _cryptoService.SetEncKeyAsync(tokenResponse.Key);

                // User doesn't have a key pair yet (old account), let's generate one for them.
                if (tokenResponse.PrivateKey == null)
                {
                    try
                    {
                        var keyPair = await _cryptoService.MakeKeyPairAsync();

                        await _apiService.PostAccountKeysAsync(new KeysRequest
                        {
                            PublicKey           = keyPair.Item1,
                            EncryptedPrivateKey = keyPair.Item2.EncryptedString
                        });

                        tokenResponse.PrivateKey = keyPair.Item2.EncryptedString;
                    }
                    catch { }
                }

                await _cryptoService.SetEncPrivateKeyAsync(tokenResponse.PrivateKey);
            }

            _vaultTimeoutService.FingerprintLocked = false;
            _messagingService.Send("loggedIn");
            return(result);
        }
示例#37
0
 public ClientVm GetMatched(TokenRequest tokenRequest)
 {
     throw new NotImplementedException();
 }
示例#38
0
 protected virtual async Task <IActionResult> AuthorizationCodeGrant(TClient client, TokenRequest tokenRequest, bool validatePkce, CodeVerifierSecret codeVerifierSecret)
 {
     throw new NotImplementedException();
 }
示例#39
0
        }                             // TODO: Determine if this should needs to be public?

        /// <summary>
        /// The authenticate asynchronous method used to call the specified token authentication endpoint
        /// </summary>
        /// <param name="tokenEndpoint">string</param>
        /// <param name="tokenRequest">TokenRequest</param>
        /// <returns>Task</returns>
        public async Task AuthenticateAsync(string tokenEndpoint, TokenRequest tokenRequest)
        {
            await AuthenticateAsync(new Uri(tokenEndpoint), tokenRequest).ConfigureAwait(false);
        }
示例#40
0
 protected virtual Task <IActionResult> RefreshTokenGrant(TClient client, TokenRequest tokenRequest)
 {
     throw new NotImplementedException();
 }
 public virtual TokenRequest pre_send_TokenRequest(TokenRequest req)
 {
     return req;
 }
示例#42
0
        protected virtual async Task <IActionResult> ClientCredentialsGrant(TClient client, TokenRequest tokenRequest)
        {
            logger.ScopeTrace("Down, OAuth Client Credentials grant accepted.", triggerEvent: true);

            var tokenResponse = new TokenResponse
            {
                TokenType = IdentityConstants.TokenTypes.Bearer,
                ExpiresIn = client.AccessTokenLifetime,
            };

            string algorithm = IdentityConstants.Algorithms.Asymmetric.RS256;

            var claims = new List <Claim>();

            claims.AddClaim(JwtClaimTypes.Subject, $"c_{client.ClientId}");
            claims.AddClaim(JwtClaimTypes.AuthTime, DateTimeOffset.UtcNow.ToUnixTimeSeconds().ToString());
            //TODO should the amr claim be included???
            //claims.AddClaim(JwtClaimTypes.Amr, IdentityConstants.AuthenticationMethodReferenceValues.Pwd);

            var scopes = tokenRequest.Scope.ToSpaceList();

            tokenResponse.AccessToken = await jwtLogic.CreateAccessTokenAsync(client, claims, scopes, algorithm);

            logger.ScopeTrace($"Token response '{tokenResponse.ToJsonIndented()}'.");
            logger.ScopeTrace("Down, OAuth Token response.", triggerEvent: true);
            return(new JsonResult(tokenResponse));
        }
        public TokenResponse TokenEndpoint(TokenRequest req)
        {
            IDTokenAndAccessTokenEntry IDTokenAndAccessTokenEntry;
            TokenResponse resp = new TokenResponse();
            CST_Ops.recordme(this, req, resp, false, false);
            string IdPSessionSecret;
            if (req == null) return null;
            switch (req.grant_type)
            {
                case "authorization_code":
                    IdPSessionSecret = AuthorizationCodeRecs.findISSByClientIDAndCode(req.client_id/*, req.UserID*/, req.code);
                    if (IdPSessionSecret == null)
                        return null;
                    AuthorizationCodeEntry AuthCodeEntry = (AuthorizationCodeEntry)AuthorizationCodeRecs.getEntry(IdPSessionSecret, req.client_id);

                    if (AuthCodeEntry.Redir_dest != req.redirect_uri)
                        return null;

                    IDTokenAndAccessTokenEntry = (IDTokenAndAccessTokenEntry)createAccessTokenEntry(AuthCodeEntry.redirect_uri, AuthCodeEntry.scope, AuthCodeEntry.state);
                    if (IDTokenAndAccessTokenRecs.setEntry(req.access_token, req.client_id, AuthCodeEntry.UserID, IDTokenAndAccessTokenEntry) == false)
                        return null;

                    resp.access_token = IDTokenAndAccessTokenEntry.access_token;
                    resp.refresh_token = IDTokenAndAccessTokenEntry.refresh_token;
                    resp.scope = IDTokenAndAccessTokenEntry.scope;
                    resp.id_token = IDTokenAndAccessTokenEntry.id_token;
                    resp.id_token.Claims.UserId = AuthCodeEntry.UserID;
                    return resp;
            }
            return null;
        }
示例#44
0
        private async void LoginAsync()
        {
            if (string.IsNullOrEmpty(Email))
            {
                await App.Current.MainPage.DisplayAlert(Languages.Error, Languages.EmailError, Languages.Accept);

                return;
            }

            if (string.IsNullOrEmpty(Password))
            {
                await App.Current.MainPage.DisplayAlert(Languages.Error, Languages.PasswordError, Languages.Accept);

                return;
            }

            IsRunning = true;
            IsEnabled = false;

            if (Connectivity.NetworkAccess != NetworkAccess.Internet)
            {
                IsRunning = false;
                IsEnabled = true;

                await App.Current.MainPage.DisplayAlert(Languages.Error, Languages.ConnectionError, Languages.Accept);

                return;
            }

            var url     = App.Current.Resources["UrlAPI"].ToString();
            var request = new TokenRequest
            {
                Password = Password,
                Username = Email,
            };

            var response = await _apiService.GetTokenAsync(url, "api", "/Account/CreateToken", request);

            IsRunning = false;
            IsEnabled = true;

            if (!response.IsSuccess)
            {
                await App.Current.MainPage.DisplayAlert(Languages.Error, Languages.LoginError, Languages.Accept);

                Password = string.Empty;
                return;
            }

            var token = (TokenResponse)response.Result;

            Settings.Token   = JsonConvert.SerializeObject(token);
            Settings.IsLogin = true;

            IsRunning = false;
            IsEnabled = true;

            await _navigationService.NavigateAsync($"/{nameof(OnSaleMasterDetailPage)}/NavigationPage/{nameof(ProductsPage)}");

            Password = string.Empty;
        }
 private bool ProcessRequest(TokenRequest request)
 {
     IBWControllable bc = request.initialBC;
     while (bc != null)
     {
         BWContext context = _contextMap[bc] as BWContext;
         if (context == null)
         {
             RollbackRequest(request);
             return false;
         }
         lock (context)
         {
             if (context.bwConfig != null)
             {
                 bool result;
                 if (request.type == TokenRequestType.BLOCKING)
                 {
                     result = ProcessBlockingRequest(request, context);
                 }
                 else if (request.type == TokenRequestType.NONBLOCKING)
                 {
                     result = ProcessNonblockingRequest(request, context);
                 }
                 else
                 {
                     result = ProcessBestEffortRequest(request, context);
                 }
                 if (!result)
                 {
                     // for non-blocking mode, the callback is
                     // recorded and will be rolled back when being reset,
                     // so we don't need to do rollback here.
                     if (request.type != TokenRequestType.NONBLOCKING)
                     {
                         RollbackRequest(request);
                     }
                     return false;
                 }
             }
             TokenRequestContext requestContext = new TokenRequestContext();
             requestContext.acquiredToken = request.requestToken;
             requestContext.bc = bc;
             request.acquiredStack.Push(requestContext);
         }
         bc = bc.GetParentBWControllable();
     }
     // for best effort request, we need to rollback over-charged tokens
     if (request.type == TokenRequestType.BEST_EFFORT)
     {
         RollbackRequest(request);
     }
     return true;
 }
        private async Task <AuthResult> VerifyAndGenerateToken(TokenRequest tokenRequest)
        {
            var jwtTokenHandler = new JwtSecurityTokenHandler();

            try
            {
                // Validation 1 - Validate JWT token format
                var tokenInVerification = jwtTokenHandler.ValidateToken(tokenRequest.Token, _tokenValidationParams, out var validatedToken);

                // Validation 2 - Validate encryption algorithm
                if (validatedToken is JwtSecurityToken jwtSecurityToken)
                {
                    var result = jwtSecurityToken.Header.Alg.Equals(SecurityAlgorithms.HmacSha256, StringComparison.InvariantCultureIgnoreCase);

                    if (result == false)
                    {
                        return(null);
                    }
                }

                // Validation 3 - Validate expire date
                var utcExpireDate = long.Parse(tokenInVerification.Claims.FirstOrDefault(x => x.Type == JwtRegisteredClaimNames.Exp).Value);

                var expireDate = UnixTimeStampToDateTime(utcExpireDate);

                if (expireDate > DateTime.UtcNow)
                {
                    return(new AuthResult()
                    {
                        Success = false,
                        Errors = new List <string>()
                        {
                            "Token has not yet expired"
                        }
                    });
                }

                // Validation 4 - Validate existing of the token
                var storedToken = await _apiDbContext.RefreshTokens.FirstOrDefaultAsync(x => x.Token == tokenRequest.RefreshToken);

                if (storedToken == null)
                {
                    return(new AuthResult()
                    {
                        Success = false,
                        Errors = new List <string>()
                        {
                            "Token does not exist"
                        }
                    });
                }

                // Validation 5 - Validate if used
                if (storedToken.IsUsed)
                {
                    return(new AuthResult()
                    {
                        Success = false,
                        Errors = new List <string>()
                        {
                            "Token has been used"
                        }
                    });
                }

                // Validation 6 - Validate if revoked
                if (storedToken.IsRevoked)
                {
                    return(new AuthResult()
                    {
                        Success = false,
                        Errors = new List <string>()
                        {
                            "Token has been revoked"
                        }
                    });
                }

                // Validation 7 - Validate id
                var jti = tokenInVerification.Claims.FirstOrDefault(x => x.Type == JwtRegisteredClaimNames.Jti).Value;

                if (storedToken.JwtId != jti)
                {
                    return(new AuthResult()
                    {
                        Success = false,
                        Errors = new List <string>()
                        {
                            "Token does not match"
                        }
                    });
                }

                // Update current token
                storedToken.IsUsed = true;
                _apiDbContext.RefreshTokens.Update(storedToken);
                await _apiDbContext.SaveChangesAsync();

                // Generate a new token
                var dbUser = await _userManager.FindByIdAsync(storedToken.UserId);

                return(await GenerateJwtToken(dbUser));
            }
            catch (Exception ex)
            {
                return(null);
            }
        }
 private bool ProcessNonblockingRequest(TokenRequest request, BWContext context)
 {
     if (context.bwConfig[3] >= 0)
     {
         if (context.tokenRc[3] >= request.requestToken)
         {
             context.tokenRc[3] -= request.requestToken;
             return true;
         }
     }
     else
     {
         if (context.tokenRc[request.channel] < 0) return true;
         if (context.tokenRc[request.channel] >= request.requestToken)
         {
             context.tokenRc[request.channel] -= request.requestToken;
             return true;
         }
     }
     (context.pendingRequestArray[request.channel] as IList).Add(request);
     return false;
 }
        public async void Login()
        {
            var isValid = ValidateData();

            if (!isValid)
            {
                IsEnable  = true;
                IsRunning = false;
                return;
            }

            EntryEmpty = "Transparent";
            IsEnable   = false;
            IsRunning  = true;
            var request = new TokenRequest
            {
                Password = Password,
                Username = Email
            };

            var url        = App.Current.Resources["UrlAPI"].ToString();
            var connection = await _apiService.CheckConnection();

            if (!connection)
            {
                IsRunning = true;
                await Application.Current.MainPage.DisplayAlert("Error", "Check Internet Connection", "OK");

                IsRunning = false;
            }
            else
            {
                var response = await _apiService.GetTokenAsync(
                    url,
                    "Account",
                    "/CreateToken",
                    request);

                if (!response.IsSuccess)
                {
                    AlertDialog = "Please Check your Password";
                    EntryEmpty  = "Red";
                    Password    = string.Empty;
                    IsRunning   = false;
                    IsEnable    = true;
                    return;
                }
                var tokenData = response.Result;

                var response2 = await _apiService.GetTravelerByEmail(
                    url,
                    "api",
                    "/Travelers/GetTravelerByEmail",
                    "bearer",
                    tokenData.Token,
                    Email);

                var traveler = response2.Result;

                Settings.Traveler     = JsonConvert.SerializeObject(traveler);
                Settings.Token        = JsonConvert.SerializeObject(tokenData);
                Settings.IsRemembered = IsRemember;

                await Shell.Current.GoToAsync("trippage");

                EntryEmpty  = "Transparent";
                AlertDialog = string.Empty;
                IsEnable    = true;
                IsRunning   = false;
            }
        }
 /**
  * Give back the acquired tokens due to failing to accomplish the requested
  * operation or over-charged tokens in the case of best-effort request.
  * @param request
  */
 private void RollbackRequest(TokenRequest request)
 {
     while (request.acquiredStack.Count > 0)
     {
         TokenRequestContext requestContext = request.acquiredStack.Pop() as TokenRequestContext;
         BWContext context = _contextMap[requestContext.bc] as BWContext;
         if (context != null)
         {
             lock (context)
             {
                 if (context.bwConfig != null)
                 {
                     if (context.bwConfig[3] >= 0)
                     {
                         if (request.type == TokenRequestType.BEST_EFFORT)
                         {
                             context.tokenRc[3] += requestContext.acquiredToken - request.requestToken;
                         }
                         else
                         {
                             context.tokenRc[3] += requestContext.acquiredToken;
                         }
                     }
                     else
                     {
                         if (context.bwConfig[request.channel] >= 0)
                         {
                             if (request.type == TokenRequestType.BEST_EFFORT)
                             {
                                 context.tokenRc[request.channel] += requestContext.acquiredToken - request.requestToken;
                             }
                             else
                             {
                                 context.tokenRc[request.channel] += requestContext.acquiredToken;
                             }
                         }
                     }
                 }
             }
         }
     }
 }
            // Token: 0x060003C2 RID: 962 RVA: 0x00040E90 File Offset: 0x0003F090
            public Task <string> AuthorizeAsync(IHttpClient client, YandexMoney.IWebBrowser <string> browser, string uri, AuthorizationRequestParams prms)
            {
                bool          flag = browser == null;
                Task <string> result;

                if (flag)
                {
                    result = null;
                }
                else
                {
                    this._tcs = new TaskCompletionSource <string>();
                    browser.NavigationEvent += async delegate(object s, string e)
                    {
                        Dictionary <string, string> d = Misc.QueryParamsToDictionary(e);
                        bool flag2 = d.ContainsKey("code");
                        if (flag2)
                        {
                            TokenRequest <TokenResult> tr = new TokenRequest <TokenResult>(client, new JsonSerializer <TokenResult>())
                            {
                                Code        = d["code"],
                                ClientId    = prms.ClientId,
                                RedirectUri = prms.RedirectUri
                            };
                            TokenResult token = new TokenResult();
                            string      ar    = string.Concat(new string[]
                            {
                                "https://money.yandex.ru/oauth/token?code=",
                                tr.Code,
                                "&client_id=",
                                tr.ClientId,
                                "&grant_type=authorization_code&redirect_uri=",
                                tr.RedirectUri
                            });
                            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(ar);
                            request.AllowAutoRedirect = false;
                            request.ContentType       = "application/json; charset=utf-8";
                            HttpWebResponse response           = (HttpWebResponse)request.GetResponse();
                            Stream          dataStream         = response.GetResponseStream();
                            StreamReader    reader             = new StreamReader(dataStream);
                            string          responseFromServer = reader.ReadToEnd();
                            object          obj = JsonConvert.DeserializeObject <object>(responseFromServer);
                            if (YandexMoney.AuthorizationBroker.< > o__1.< > p__1 == null)
                            {
                                YandexMoney.AuthorizationBroker.< > o__1.< > p__1 = CallSite <Func <CallSite, object, string> > .Create(Microsoft.CSharp.RuntimeBinder.Binder.Convert(CSharpBinderFlags.None, typeof(string), typeof(YandexMoney.AuthorizationBroker)));
                            }
                            Func <CallSite, object, string> target = YandexMoney.AuthorizationBroker.< > o__1.< > p__1.Target;
                            CallSite <> p__ = YandexMoney.AuthorizationBroker.< > o__1.< > p__1;
                            if (YandexMoney.AuthorizationBroker.< > o__1.< > p__0 == null)
                            {
                                YandexMoney.AuthorizationBroker.< > o__1.< > p__0 = CallSite <Func <CallSite, object, string, object> > .Create(Microsoft.CSharp.RuntimeBinder.Binder.GetIndex(CSharpBinderFlags.None, typeof(YandexMoney.AuthorizationBroker), new CSharpArgumentInfo[]
                                {
                                    CSharpArgumentInfo.Create(CSharpArgumentInfoFlags.None, null),
                                    CSharpArgumentInfo.Create(CSharpArgumentInfoFlags.UseCompileTimeType | CSharpArgumentInfoFlags.Constant, null)
                                }));
                            }
                            string t = target(< > p__, YandexMoney.AuthorizationBroker.< > o__1.< > p__0.Target(YandexMoney.AuthorizationBroker.< > o__1.< > p__0, obj, "access_token"));
                            reader.Close();
                            dataStream.Close();
                            response.Close();
                            token.Token = t;
                            bool flag3 = token == null;
                            if (!flag3)
                            {
                                bool flag4 = this._tcs != null;
                                if (flag4)
                                {
                                    this._tcs.SetResult((token == null) ? null : token.Token);
                                }
                                tr                 = null;
                                token              = null;
                                ar                 = null;
                                request            = null;
                                response           = null;
                                dataStream         = null;
                                reader             = null;
                                responseFromServer = null;
                                obj                = null;
                                t = null;
                            }
                        }
                    };
                    browser.Navigate(uri, prms.PostBytes(), "Content-Type: application/x-www-form-urlencoded/r/n");
                    result = this._tcs.Task;
                }
                return(result);
            }
 public bool AcquireTokenNonblocking(long tokenCount, ITokenBucketCallback callback)
 {
     TokenRequest request = new TokenRequest();
     request.type = TokenRequestType.NONBLOCKING;
     request.callback = callback;
     request.channel = _channel;
     request.initialBC = _bc;
     request.requestToken = tokenCount;
     return _simpleBWControlService.ProcessRequest(request);
 }
示例#52
0
        private async Task <(int, ClaimsPrincipal, string, string)> AcquireTokensAsync(OpenidConnectPkceState openidClientPkceState, string code)
        {
            var tokenRequest = new TokenRequest
            {
                GrantType   = IdentityConstants.GrantTypes.AuthorizationCode,
                Code        = code,
                ClientId    = openidClientPkceState.ClientId,
                RedirectUri = openidClientPkceState.CallBackUri,
            };

            var codeVerifierSecret = new CodeVerifierSecret
            {
                CodeVerifier = openidClientPkceState.CodeVerifier,
            };

            var oidcDiscovery = await GetOidcDiscoveryAsync(openidClientPkceState.OidcDiscoveryUri);

            var request = new HttpRequestMessage(HttpMethod.Post, oidcDiscovery.TokenEndpoint);

            request.Content = new FormUrlEncodedContent(tokenRequest.ToDictionary().AddToDictionary(codeVerifierSecret));

            var httpClient = serviceProvider.GetService <HttpClient>();
            var response   = await httpClient.SendAsync(request);

            switch (response.StatusCode)
            {
            case HttpStatusCode.OK:
                var result = await response.Content.ReadAsStringAsync();

                var tokenResponse = result.ToObject <TokenResponse>();
                tokenResponse.Validate(true);
                if (tokenResponse.AccessToken.IsNullOrEmpty())
                {
                    throw new ArgumentNullException(nameof(tokenResponse.AccessToken), tokenResponse.GetTypeName());
                }
                if (tokenResponse.ExpiresIn <= 0)
                {
                    throw new ArgumentNullException(nameof(tokenResponse.ExpiresIn), tokenResponse.GetTypeName());
                }

                var oidcDiscoveryKeySet = await GetOidcDiscoveryKeysAsync(openidClientPkceState.OidcDiscoveryUri);

                (var idTokenPrincipal, _) = JwtHandler.ValidateToken(tokenResponse.IdToken, oidcDiscovery.Issuer, oidcDiscoveryKeySet.Keys, openidClientPkceState.ClientId, nameClaimType: globalOpenidClientPkceSettings.NameClaimType, roleClaimType: globalOpenidClientPkceSettings.RoleClaimType);

                var nonce = idTokenPrincipal.Claims.Where(c => c.Type == JwtClaimTypes.Nonce).Select(c => c.Value).SingleOrDefault();
                if (!openidClientPkceState.Nonce.Equals(nonce, StringComparison.Ordinal))
                {
                    throw new SecurityException("Nonce do not match.");
                }

                return(tokenResponse.ExpiresIn, idTokenPrincipal, tokenResponse.IdToken, tokenResponse.AccessToken);

            case HttpStatusCode.BadRequest:
                var resultBadRequest = await response.Content.ReadAsStringAsync();

                var tokenResponseBadRequest = resultBadRequest.ToObject <TokenResponse>();
                tokenResponseBadRequest.Validate(true);
                throw new Exception($"Error login call back, Bad request. StatusCode={response.StatusCode}");

            default:
                throw new Exception($"Error login call back, Status Code not expected. StatusCode={response.StatusCode}");
            }
        }
        /// <summary>
        /// Login
        /// </summary>
        /// <exception cref="IO.Swagger.Client.ApiException">Thrown when fails to make API call</exception>
        /// <param name="request">Credenziali di login</param>
        /// <returns>TokenResponse</returns>
        public TokenResponse Token(TokenRequest request)
        {
            ApiResponse <TokenResponse> localVarResponse = TokenWithHttpInfo(request);

            return(localVarResponse.Data);
        }
        private HttpResponseMessage ProcessResourceOwnerCredentialRequest(TokenRequest request, string tokenType,
            Client client)
        {
            Tracing.Information("Starting resource owner password credential flow for client: " + client.Name);
            var appliesTo = new EndpointReference(request.Scope);

            if (string.IsNullOrWhiteSpace(request.UserName) || string.IsNullOrWhiteSpace(request.Password))
            {
                Tracing.Error("Invalid resource owner credentials for: " + appliesTo.Uri.AbsoluteUri);
                return OAuthErrorResponseMessage(OAuth2Constants.Errors.InvalidGrant);
            }

            if (UserRepository.ValidateUser(request.UserName, request.Password))
            {
                return CreateTokenResponse(request.UserName, client, appliesTo, tokenType, client.AllowRefreshToken);
            }
            Tracing.Error("Resource owner credential validation failed: " + request.UserName);
            return OAuthErrorResponseMessage(OAuth2Constants.Errors.InvalidGrant);
        }