예제 #1
0
        public TokenPayload GetPayload(string token)
        {
            var payload = new TokenPayload();

            var principal = GetPrincipal(token);

            if (principal == null)
            {
                return(null);
            }
            ClaimsIdentity identity = null;

            try
            {
                identity = (ClaimsIdentity)principal.Identity;
                foreach (var claim in identity.Claims)
                {
                    payload[claim.Type] = claim.Value;
                }
            }
            catch (NullReferenceException)
            {
                return(null);
            };

            return(payload);
        }
예제 #2
0
        private List <ClaimsIdentity> FillToken(TokenPayload payload)
        {
            var claims = new List <Claim>();

            claims.Add(new Claim(ClaimTypes.GivenName, payload.given_name));
            claims.Add(new Claim(ClaimTypes.Name, payload.name));
            claims.Add(new Claim(ClaimTypes.Email, payload.email));
            claims.Add(new Claim(ClaimTypes.Surname, payload.family_name));

            foreach (var item in payload.group)
            {
                claims.Add(new Claim(ClaimTypes.Role, item));
            }
            foreach (var item in payload.realm_access.roles)
            {
                claims.Add(new Claim(ClaimTypes.Role, item));
            }
            foreach (var item in payload.resource_access.account.roles)
            {
                claims.Add(new Claim(ClaimTypes.Role, item));
            }

            var identity = new ClaimsIdentity(claims);

            return(new List <ClaimsIdentity> {
                identity
            });
        }
예제 #3
0
        /// <summary>
        /// Creates the builder object from a token request.
        /// </summary>
        /// <param name="tokenRequest">token request</param>
        public StandingOrderTokenBuilder(TokenRequest tokenRequest)
        {
            if (tokenRequest.RequestPayload.RequestBodyCase != RequestBodyCase.StandingOrderBody)
            {
                throw new ArgumentException(
                          "Require token request with standing order body.");
            }
            if (tokenRequest.RequestPayload.To == null)
            {
                throw new ArgumentException("No payee on token request");
            }
            StandingOrderBody body = tokenRequest.RequestPayload
                                     .StandingOrderBody;

            this.payload = new TokenPayload
            {
                Version          = "1.0",
                RefId            = tokenRequest.RequestPayload.RefId,
                From             = tokenRequest.RequestOptions.From,
                To               = tokenRequest.RequestPayload.To,
                Description      = tokenRequest.RequestPayload.Description,
                ReceiptRequested = tokenRequest.RequestOptions.ReceiptRequested,
                TokenRequestId   = tokenRequest.Id,
                StandingOrder    = body
            };
            if (tokenRequest.RequestPayload.ActingAs != null)
            {
                this.payload.ActingAs = tokenRequest.RequestPayload.ActingAs;
            }
        }
예제 #4
0
        /// <summary>
        /// Creates a payment request (a transfer token payload)
        /// and sends it to a potential payer.
        /// </summary>
        /// <param name="tokenClient">initialized SDK</param>
        /// <param name="payee">payee Token member</param>
        /// <param name="payerAlias">payer Token member alias</param>
        /// <returns>a transfer Token</returns>
        public static NotifyStatus NotifyPaymentRequest(
            Tokenio.User.TokenClient tokenClient,
            UserMember payee,
            Alias payerAlias)
        {
            // We'll use this as a reference ID. Normally, a payee who
            // explicitly sets a reference ID would use an ID from a db.
            // E.g., an online merchant might use the ID of a "shopping cart".
            // We don't have a db, so we fake it with a random string:
            string       cartId         = Util.Nonce();
            TokenPayload paymentRequest = new TokenPayload
            {
                Description = "Sample payment request",
                From        = new TokenMember {
                    Alias = payerAlias
                },
                To = new TokenMember {
                    Alias = payee.GetFirstAliasBlocking()
                },
                Transfer = new TransferBody {
                    Amount = "100.00", Currency = "EUR"
                },
                RefId = cartId
            };


            NotifyStatus status = tokenClient.NotifyPaymentRequestBlocking(paymentRequest);

            return(status);
        }
예제 #5
0
        public void UpdatePayload(Action <TokenPayload> updateAction)
        {
            var payload = ParsedPayload;

            updateAction(payload);
            ParsedPayload = payload;
        }
예제 #6
0
        public dynamic GenerateToken(TokenPayload payload)
        {
            if (!IsInputValidForDifferentGrantType(payload))
            {
                throw new InvalidRequestException();
            }

            string grantType = payload.GrantType?.ToLower(CultureInfo.CurrentCulture) ?? null;

            if (grantType == ApiConstant.GrantTypeAuthenticateSite)
            {
                return(GetTokenForAuthenticateSiteGrantType());
            }

            if (grantType == ApiConstant.GrantTypePassword)
            {
                return(GetTokenForPasswordGrantType(payload));
            }

            if (grantType == ApiConstant.GrantTypeRefreshToken)
            {
                return(GetTokenForRefreshTokenGrantType(payload));
            }

            throw new UnauthorizedException();
        }
예제 #7
0
        private JObject GetTokenForRefreshTokenGrantType(TokenPayload payload)
        {
            var obj = new JObject()
            {
                ["token_type"] = ApiConstant.TokenTypeBearer,
                ["expires_in"] = GetAccessTokenLifeTimeInSeconds()
            };

            RefreshToken refreshToken = FindRefreshToken(payload.RefreshToken);

            if (refreshToken == null)
            {
                throw new InvalidRefreshTokenException("The specified refresh token is invalid!");
            }

            if (refreshToken.CreatedAt.AddMinutes(Convert.ToInt32(Configuration["RefreshTokenLifeTime"], CultureInfo.CurrentCulture)) < DateTime.Now)
            {
                throw new ExpiredRefreshTokenException("The specified refresh token is expired!");
            }

            UserDetails userDetails = GetUserDetailsByUsername(refreshToken.UserId);

            if (userDetails == null)
            {
                userDetails = GetDefaultAnonymousUserDetails();
            }

            obj.Add("access_token", tokenService.CreateAccessToken(userDetails));

            return(obj);
        }
예제 #8
0
 /// <summary>
 /// Creates the builder object.
 /// </summary>
 /// <param name="member">payer of the token</param>
 /// <param name="amount">lifetime amount of the token</param>
 /// <param name="currency">currency of the token</param>
 public TransferTokenBuilder(
     Member member,
     double amount,
     string currency)
 {
     this.member  = member;
     this.payload = new TokenPayload
     {
         Version  = "1.0",
         Transfer = new TransferBody
         {
             Currency       = currency,
             LifetimeAmount = amount.ToString(),
             Instructions   = new TransferInstructions
             {
                 Metadata = new TransferInstructions.Types.Metadata()
             }
         }
     };
     if (member != null)
     {
         From(member.MemberId());
         IList <Alias> aliases = member.GetAliasesBlocking();
         if (aliases.Count > 0)
         {
             payload.From.Alias = aliases[0];
         }
     }
 }
예제 #9
0
        /// <summary>
        /// Creates the builder object.
        /// </summary>
        /// <param name="member">payer of the token</param>
        /// <param name="amount">amount per charge of the standing order token</param>
        /// <param name="currency">currency of the token</param>
        /// <param name="frequency">ISO 20022 code for the frequency of the standing order:
        ///            DAIL, WEEK, TOWK, MNTH, TOMN, QUTR, SEMI, YEAR</param>
        /// <param name="startDate">start date of the standing order: ISO 8601 YYYY-MM-DD or YYYYMMDD</param>
        /// <param name="endDate">end date of the standing order: ISO 8601 YYYY-MM-DD or YYYYMMDD</param>
        public StandingOrderTokenBuilder(
            Member member,
            double amount,
            string currency,
            string frequency,
            string startDate,
            string endDate = null)
        {
            this.payload = new TokenPayload
            {
                Version = "1.0",
                From    = new TokenMember
                {
                    Id = member.MemberId()
                },
                StandingOrder = new StandingOrderBody
                {
                    Currency  = currency,
                    Amount    = amount.ToString(),
                    Frequency = frequency,
                    StartDate = startDate,
                    EndDate   = endDate ?? ""
                }
            };

            IList <Alias> aliases = member.GetAliasesBlocking();

            if (aliases.Count > 0)
            {
                payload.From.Alias = aliases[0];
            }
        }
예제 #10
0
        private async Task <ReferralTokenReceipt> SendSignalRAuthReply(ReferralTokenReceipt referralToken, AuthReplyMethod methodEnum)
        {
            string methodName = null;

            switch (methodEnum)
            {
            case AuthReplyMethod.InitialRegistration:
                methodName = SignalrMethodNames.InitialRegistration;
                break;

            case AuthReplyMethod.Reauthenticated:
                methodName = SignalrMethodNames.Reauthenticated;
                break;
            }
            try
            {
                var replyPayload = new TokenPayload()
                {
                    DiscordUserId = referralToken.ReferralUserId
                };
                await _botHub.Clients.User(SignalrUsernames.BotUsername).SendAsync(methodName, replyPayload);

                referralToken.ReplySent = true;
            }
            catch (Exception ex)
            {
                _logger.Log(LogLevel.Error, "Failed sending SignalR auth response", ex);
                referralToken.ReplyError = true;
            }

            return(referralToken);
        }
예제 #11
0
        public string CreateToken(string username, TokenPayload payloads = null)
        {
            var descriptor = new SecurityTokenDescriptor
            {
                Issuer  = issuer,
                Subject = new ClaimsIdentity(new[]
                {
                    new Claim(ClaimTypes.Name, username)
                }),
                IssuedAt           = DateTime.UtcNow,
                Expires            = _tokenKeyStorage.DefaultExpires,
                SigningCredentials = credentials
            };

            var secToken = handler.CreateJwtSecurityToken(descriptor);

            if (payloads != null)
            {
                foreach (var kv in payloads)
                {
                    secToken.Payload[kv.Key] = kv.Value;
                }
            }

            var tokenString = handler.WriteToken(secToken);

            return(tokenString);
        }
예제 #12
0
        public async Task <Token> Parse(string token, string issuer, string audience, bool validateSignature)
        {
            using (Logger.BeginScope(nameof(Parse)))
            {
                try
                {
                    Validator.ValidateFormat(token, Settings.MaxTokenSize);

                    var jws = ParseJws(token);

                    Validator.ValidateJoseHeader(jws);

                    var payloadClaims = Base64Url.DeserializeData(jws.Parts[1], "JWT payload");
                    var payload       = new TokenPayload(payloadClaims);

                    Validator.ValidatePayload(payload, issuer, audience, Settings.ClockSkew);

                    if (validateSignature)
                    {
                        await Validator.ValidateSignature(jws);
                    }

                    return(new Token
                    {
                        Algorithm = jws.Algorithm,
                        Header = jws.Header,
                        Payload = payload
                    });
                }
                catch (Exception ex)
                {
                    throw Logger.Exception($"Error parsing the Json Web Token: {ex.Message}");
                }
            }
        }
예제 #13
0
        public BulkTransferTokenBuilder(
            Member member,
            IList <BulkTransferBody.Types.Transfer> transfers,
            double totalAmount,
            TransferEndpoint source)
        {
            payload = new TokenPayload
            {
                Version = "1.0",
                From    = new TokenMember
                {
                    Id = member.MemberId()
                },
                BulkTransfer = new BulkTransferBody
                {
                    TotalAmount = totalAmount.ToString(),
                    Source      = source,
                    Transfers   =
                    {
                        transfers
                    }
                }
            };
            var aliases = member.GetAliases()
                          .Result;

            if (aliases == null)
            {
                payload.From.Alias = aliases[0];
            }
        }
예제 #14
0
        public BulkTransferTokenBuilder(TokenRequest tokenRequest)
        {
            if (tokenRequest.RequestPayload.RequestBodyCase != RequestBodyOneofCase.BulkTransferBody)
            {
                throw new ArgumentException(
                          "Require token request with bulk transfer body.");
            }

            if (tokenRequest.RequestPayload.To != null)
            {
                throw new ArgumentException("No payee on token request");
            }

            var body = tokenRequest.RequestPayload.BulkTransferBody;

            payload = new TokenPayload
            {
                Version          = "1.0",
                RefId            = tokenRequest.RequestPayload.RefId,
                From             = tokenRequest.RequestOptions.From,
                To               = tokenRequest.RequestPayload.To,
                Description      = tokenRequest.RequestPayload.Description,
                ReceiptRequested = tokenRequest.RequestOptions.ReceiptRequested,
                TokenRequestId   = tokenRequest.Id,
                BulkTransfer     = body
            };
            if (tokenRequest.RequestPayload.ActingAs != null)
            {
                payload.ActingAs = tokenRequest.RequestPayload.ActingAs;
            }
        }
예제 #15
0
        public /*async*/ /*Task<*/ AuthTokens /*> */ GetNewTokens(string refreshToken)
        {
            var    headers = Request.Headers;
            string access  = null;

            if (headers.Contains("token"))
            {
                access = headers.GetValues("token").First();
            }
            if (access == null)
            {
                throw new System.Exception("Access token wasn't received.");
            }

            var payload = TokenPayload.GetPayload(access);



            Validate(refreshToken);
            var x = /*await*/ new AuthTokens("", ""); //identity.GenerateTokens();

            if (x == null)
            {
                throw new System.Exception("Tokens weren't generated.");
            }
            return(x);
        }
예제 #16
0
        /// <summary>
        /// Creates the builder object from a token payload
        /// </summary>
        /// <param name="member">payer of the token</param>
        /// <param name="tokenPayload">token payload</param>
        public TransferTokenBuilder(Member member, TokenPayload tokenPayload)
        {
            if (tokenPayload.BodyCase != TRANSFER.Transfer)
            {
                throw new ArgumentException("Require token payload with transfer body.");
            }

            if (tokenPayload.To == null)
            {
                throw new ArgumentException("No payee on token payload.");
            }

            this.member  = member;
            this.payload = tokenPayload;

            if (this.payload.From == null)
            {
                this.payload.From = new TokenMember
                {
                    Id = member.MemberId()
                };
            }

            if (this.payload.Transfer.Instructions == null)
            {
                this.payload.Transfer.Instructions = new TransferInstructions
                {
                    Metadata = new TransferInstructions.Types.Metadata()
                };
            }
        }
예제 #17
0
        /// <summary>
        /// Creates an instance of {@link AccessTokenBuilder} from a token request.
        /// </summary>
        /// <param name="tokenRequest">token request</param>
        /// <returns>instance of {@link AccessTokenBuilder}</returns>
        public static AccessTokenBuilder FromTokenRequest(TokenRequest tokenRequest)
        {
            if (!tokenRequest.RequestPayload.RequestBodyCase.Equals(RequestBodyCase.AccessBody))
            {
                throw new ArgumentException("Require token request with access body.");
            }

            var builder = new TokenPayload
            {
                Version          = "1.0",
                RefId            = tokenRequest.RequestPayload.RefId,
                From             = tokenRequest.RequestOptions.From,
                To               = tokenRequest.RequestPayload.To,
                Description      = tokenRequest.RequestPayload.Description,
                ReceiptRequested = tokenRequest.RequestOptions.ReceiptRequested,
                Access           = new AccessBody()
            };

            if (tokenRequest.RequestPayload.ActingAs != null)
            {
                builder.ActingAs = tokenRequest.RequestPayload.ActingAs;
            }

            return(new AccessTokenBuilder(builder, null));
        }
예제 #18
0
 public static PrepareTokenResult Create(TokenPayload tokenPayload, Policy policy)
 {
     return(new PrepareTokenResult
     {
         TokenPayload = tokenPayload,
         Policy = policy
     });
 }
예제 #19
0
 /// <summary>
 /// Cancels the existing token and creates a replacement for it. Supported
 /// only for access tokens.
 /// </summary>
 /// <param name="tokenToCancel">the token to cancel</param>
 /// <param name="tokenToCreate">the payload to create new token with</param>
 /// <returns>the result of the replacement opration</returns>
 public Task <TokenOperationResult> ReplaceToken(
     Token tokenToCancel,
     TokenPayload tokenToCreate)
 {
     return(CancelAndReplace(tokenToCancel, new CreateToken {
         Payload = tokenToCreate
     }));
 }
예제 #20
0
        /// <summary>
        /// Creates an instance of {@link AccessTokenBuilder} from an existing token payload.
        /// </summary>
        /// <param name="payload">payload to initialize from</param>
        /// <returns>instance of {@link AccessTokenBuilder}</returns>
        public static AccessTokenBuilder FromPayload(TokenPayload payload)
        {
            var builder = payload.Clone();

            builder.Access = new AccessBody();
            builder.RefId  = Util.Nonce();
            return(new AccessTokenBuilder(builder));
        }
        /// <summary>
        /// Notifies subscribed devices of payment requests.
        /// </summary>
        /// <param name="tokenPayload">the payload of a token to be sent</param>
        /// <returns>status of the notification request</returns>
        public Task <NotifyStatus> NotifyPaymentRequest(TokenPayload tokenPayload)
        {
            var request = new RequestTransferRequest {
                TokenPayload = tokenPayload
            };

            return(gateway.RequestTransferAsync(request)
                   .ToTask(response => response.Status));
        }
예제 #22
0
 private AccessTokenBuilder()
 {
     payload = new TokenPayload
     {
         Version = "1.0",
         RefId   = Util.Nonce(),
         Access  = new AccessBody()
     };
 }
예제 #23
0
 public AuthenticateService(
     IUserService userService,
     ISecretManagementService secretManagementService,
     IOptions <TokenPayload> tokenPayload)
 {
     _userService             = userService;
     _secretManagementService = secretManagementService;
     _tokenPayload            = tokenPayload.Value;
 }
 public MojangAccountService(TokenPayload tokens, IRestClient authClient, IRestClient apiClient)
 {
     clientToken        = tokens.ClientToken;
     accessToken        = tokens.AccessToken;
     this.authClient    = authClient;
     this.apiClient     = apiClient;
     authClient.BaseUrl = new Uri(AuthServerUrl);
     apiClient.BaseUrl  = new Uri(ApiServerUrl);
 }
        public TokenPayload Decode(string token)
        {
            if (!_signer.TryDecode(token, out var payloadBytes))
            {
                throw new InvalidOperationException("Token Forged");
            }

            return(TokenPayload.FromPayloadBytes(payloadBytes));
        }
예제 #26
0
        /// <summary>
        /// Sends a notification to request a payment.
        /// </summary>
        /// <param name="tokenPayload">the payload of a token to be sent</param>
        /// <returns>status of the notification request</returns>
        public Task <NotifyStatus> NotifyPaymentRequest(TokenPayload tokenPayload)
        {
            UnauthenticatedClient unauthenticated = ClientFactory.Unauthenticated(channel);

            if (tokenPayload.RefId.Length == 0)
            {
                tokenPayload.RefId = Util.Nonce();
            }
            return(unauthenticated.NotifyPaymentRequest(tokenPayload));
        }
예제 #27
0
        private AccessTokenBuilder(TokenPayload tokenPayload, string tokenRequestId = null)
        {
            payload = tokenPayload;
            if (payload.Access == null)
            {
                payload.Access = new AccessBody();
            }

            this.tokenRequestId = tokenRequestId;
        }
        public void NullTokenTest()
        {
            ITokenManager mgr = new NullTokenManager();

            string token = mgr.Encode(null);

            TokenPayload p = mgr.Decode(token);

            Assert.IsTrue(p != null && p.ID == "1");
        }
예제 #29
0
        /// <summary>
        /// Signs a token payload.
        /// </summary>
        /// <param name="payload"></param>
        /// <param name="keyLevel"></param>
        /// <returns></returns>
        public Signature SignTokenPayload(TokenPayload payload, Level keyLevel)
        {
            ISigner signer = cryptoEngine.CreateSigner(keyLevel);

            return(new Signature
            {
                KeyId = signer.GetKeyId(),
                MemberId = MemberId,
                Signature_ = signer.Sign(Stringify(payload, TokenAction.Endorsed))
            });
        }
        /// <summary>
        /// Illustrate Member.GetToken
        /// </summary>
        /// <param name="member">Token member</param>
        public static Token GetToken(Member member, String tokenId)
        {
            Token token = member.GetTokenBlocking(tokenId);

            // get token payload
            TokenPayload payload = token.Payload;

            // get signatures
            IList <TokenSignature> signatures = token.PayloadSignatures;

            return(token);
        }