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); }
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 }); }
/// <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; } }
/// <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); }
public void UpdatePayload(Action <TokenPayload> updateAction) { var payload = ParsedPayload; updateAction(payload); ParsedPayload = payload; }
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(); }
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); }
/// <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]; } } }
/// <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]; } }
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); }
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); }
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}"); } } }
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]; } }
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; } }
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); }
/// <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() }; } }
/// <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)); }
public static PrepareTokenResult Create(TokenPayload tokenPayload, Policy policy) { return(new PrepareTokenResult { TokenPayload = tokenPayload, Policy = policy }); }
/// <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 })); }
/// <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)); }
private AccessTokenBuilder() { payload = new TokenPayload { Version = "1.0", RefId = Util.Nonce(), Access = new AccessBody() }; }
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)); }
/// <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)); }
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"); }
/// <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); }