public async Task Initiate(string email, string password)
        {
            this.email    = email.Trim().ToLowerInvariant();
            this.password = password;

            this.request = await Identity.Verify(this.email);
        }
Пример #2
0
        public async Task <IActionResult> Authenticate([FromForm] IdentityTokenRequest request)
        {
            int idSistema = 3;
            var response  = await _RAISHttpClient.Authenticate(request.Username, request.Password, idSistema);

            if (!response.Success)
            {
                var errorMessage = response.Message;
                return(new JsonResult(errorMessage)
                {
                    StatusCode = StatusCodes.Status401Unauthorized
                });
            }

            var authToken = await _tokenProviderService.GetToken(request);

            if (authToken.Error != null)
            {
                return(new JsonResult(authToken)
                {
                    StatusCode = StatusCodes.Status401Unauthorized
                });
            }

            var userId = response.Data.idUsuario;
            var menu   = await _RAISHttpClient.GetMenuStructure(userId, idSistema);

            return(Ok(new {
                authToken,
                response,
                menu
            }));
        }
        public IdentityTokenResponse PostJSONToken(IdentityTokenRequest token)
        {
            IdentityTokenResponse response = new IdentityTokenResponse();

            try
            {
                IdentityToken identityToken = null;

                using (DecodedJsonToken decodedToken = JsonTokenDecoder.Decode(token))
                {
                    if (decodedToken.IsValid)
                    {
                        identityToken = new IdentityToken(token, decodedToken.Audience, decodedToken.AuthMetadataUri);
                    }
                }

                response.token = identityToken;
            }
            catch (Exception ex)
            {
                response.errorMessage = ex.Message;
            }

            return(response);
        }
        public async Task <TokenMintingResponse> MintIdentityTokenAsync(IdentityTokenRequest identityTokenRequest)
        {
            var extensionGrantRequest = ToArbitraryIdentityRequest(identityTokenRequest);
            var result = await _tokenEndpointHandlerExtra.ProcessRawAsync(extensionGrantRequest);

            return(ToTokenMintingResponse(result));
        }
Пример #5
0
        public async Task Initiate(string email, string password)
        {
            this.email    = email.Trim().ToLowerInvariant();
            this.password = password;

            var search = await Cards.Search(this.email);

            if (search.Count != 0)
            {
                throw new VirgilException("The card with this e-mail was already created");
            }

            this.request = await Identity.Verify(this.email);
        }
Пример #6
0
        public async Task <IdentityTokenResponse> GetToken(IdentityTokenRequest request)
        {
            var parameters = new NameValueCollection
            {
                { "username", request.Username },
                { "password", request.Password },
                { "grant_type", request.GrantType },
                { "scope", request.Scope },
                { "refresh_token", request.RefreshToken },
                { "response_type", OidcConstants.ResponseTypes.Token }
            };

            var response = await GetIdpToken(parameters);

            return(GetTokenResponse(response));
        }
        internal ArbitraryIdentityRequest ToArbitraryIdentityRequest(IdentityTokenRequest identityTokenRequest)
        {
            Guard.ArgumentNotNull(nameof(identityTokenRequest), identityTokenRequest);
            var valid = !string.IsNullOrWhiteSpace(_clientId) ||
                        !string.IsNullOrWhiteSpace(identityTokenRequest.ClientId);

            Guard.OperationValid(valid, "all clientId(s) are null!");
            var scopesList            = identityTokenRequest.Scope.Split(' ').ToList();
            var extensionGrantRequest = new ArbitraryIdentityRequest()
            {
                ClientId              = string.IsNullOrEmpty(identityTokenRequest.ClientId) ? _clientId : identityTokenRequest.ClientId,
                Scopes                = scopesList,
                Subject               = identityTokenRequest.Subject,
                ArbitraryClaims       = identityTokenRequest.ArbitraryClaims,
                IdentityTokenLifetime = identityTokenRequest.IdentityTokenLifetime?.ToString()
            };

            return(extensionGrantRequest);
        }
Пример #8
0
        public async Task Initiate(string email, string password)
        {
            this.email    = email.Trim().ToLowerInvariant();
            this.password = password;

            var search = await Cards.Search(this.email);

            if (search.Count == 0)
            {
                throw new VirgilException("Account doesn't exist");
            }

            this.recipientCard = search
                                 .OrderByDescending(it => it.CreatedAt)
                                 .FirstOrDefault();

            this.state = States.CardFound;

            this.request = await Identity.Verify(this.email);
        }
 public Task <TokenMintingResponse> MintIdentityTokenAsync(IdentityTokenRequest identityTokenRequest)
 {
     throw new NotImplementedException();
 }
Пример #10
0
        public async Task <HttpResponseMessage> Validate([FromBody] IdentityTokenRequest token)
        {
            //validate the identity token passed from the client
            IdentityTokenResponse response = new IdentityTokenResponse();

            try
            {
                //decode and validate the token passed in
                IdentityToken identityToken = null;
                using (DecodedJsonToken decodedToken = JsonTokenDecoder.Decode(token))
                {
                    if (decodedToken.IsValid)
                    {
                        identityToken = new IdentityToken(token, decodedToken.Audience, decodedToken.AuthMetadataUri);
                    }
                }
                response.token = identityToken;

                //now that the key is validated, we can perform a lookup against DocDB for it's hased value (combination of metadata document URL with the Exchange identifier)
                if (identityToken != null)
                {
                    //the token is valid...check if user is valid (has valid refresh token)
                    response.validToken = true;
                    string hash = ComputeSHA256Hash(response.token.uniqueID, response.token.amurl, Salt);
                    response.user = DocumentDBRepository <UserModel> .GetItem("Users", i => i.hash == hash);

                    if (response.user != null)
                    {
                        //check for and validate the refresh token
                        if (!String.IsNullOrEmpty(response.user.refresh_token))
                        {
                            var graphToken = await TokenHelper.GetAccessTokenWithRefreshToken(response.user.refresh_token, SettingsHelper.O365UnifiedAPIResourceId);

                            if (graphToken != null)
                            {
                                //TODO: get the user details against AAD Graph
                                response.validUser = true;
                            }
                        }
                    }
                    else
                    {
                        //the user doesn't exist, so we can add a placeholder record in the data store...TODO: get more data on user????
                        response.user = new UserModel()
                        {
                            id = Guid.NewGuid().ToString().ToLower(), hash = hash
                        };
                        await DocumentDBRepository <UserModel> .CreateItemAsync("Users", response.user);
                    }
                }
                else
                {
                    //this was an invalid token!!!!
                }
            }
            catch (Exception ex)
            {
                response.errorMessage = ex.Message;
            }

            return(Request.CreateResponse <IdentityTokenResponse>(HttpStatusCode.OK, response));
        }
        public async Task <List <TokenExchangeResponse> > ProcessExchangeAsync(TokenExchangeRequest tokenExchangeRequest)
        {
            if (tokenExchangeRequest.Extras == null || tokenExchangeRequest.Extras.Count == 0)
            {
                throw new Exception($"{Name}: We require that extras be populated!");
            }
            List <ValidatedToken> validatedIdentityTokens = new List <ValidatedToken>();

            foreach (var item in tokenExchangeRequest.Tokens)
            {
                var principal = await _tokenValidator.ValidateTokenAsync(new TokenDescriptor
                {
                    TokenScheme = item.TokenScheme,
                    Token       = item.Token
                });

                var sub = principal.GetSubjectFromPincipal();
                if (string.IsNullOrEmpty(sub))
                {
                    _summaryLogger.Add("subject", "A subject was not found in the ClaimsPrincipal object!");
                    throw new Exception("A subject was not found in the ClaimsPrincipal object!");
                }
                validatedIdentityTokens.Add(new ValidatedToken
                {
                    Token       = item.Token,
                    TokenScheme = item.TokenScheme,
                    Principal   = principal
                });
            }

            // for this demo, lets assume all the extras are roles.
            var roles = tokenExchangeRequest.Extras;

            roles.Add("user");

            ResourceOwnerTokenRequest resourceOwnerTokenRequest = new ResourceOwnerTokenRequest()
            {
                AccessTokenLifetime = 3600,
                ArbitraryClaims     = new Dictionary <string, List <string> >()
                {
                    { "role", roles }
                },
                Scope    = "offline_access graphQLPlay",
                Subject  = validatedIdentityTokens[0].Principal.GetSubjectFromPincipal(),
                ClientId = "arbitrary-resource-owner-client"
            };

            var resourceOwnerResponse = await _tokenMintingService.MintResourceOwnerTokenAsync(resourceOwnerTokenRequest);

            if (resourceOwnerResponse.IsError)
            {
                throw new Exception(resourceOwnerResponse.Error);
            }

            var tokenExchangeResponse = new TokenExchangeResponse()
            {
                accessToken = new AccessTokenResponse()
                {
                    hint          = nameof(BriarRabbitInProcTokenExchangeHandler),
                    access_token  = resourceOwnerResponse.AccessToken,
                    refresh_token = resourceOwnerResponse.RefreshToken,
                    expires_in    = resourceOwnerResponse.ExpiresIn,
                    token_type    = resourceOwnerResponse.TokenType,
                    authority     =
                        $"{_httpContextAssessor.HttpContext.Request.Scheme}://{_httpContextAssessor.HttpContext.Request.Host}",
                    HttpHeaders = new List <HttpHeader>
                    {
                        new HttpHeader()
                        {
                            Name = "x-authScheme", Value = resourceOwnerResponse.Scheme
                        }
                    }
                }
            };


            IdentityTokenRequest tokenRequest = new IdentityTokenRequest()
            {
                IdentityTokenLifetime = 3600,
                ArbitraryClaims       = new Dictionary <string, List <string> >()
                {
                    { "role", roles }
                },
                Scope    = "graphQLPlay",
                Subject  = validatedIdentityTokens[0].Principal.GetSubjectFromPincipal(),
                ClientId = "arbitrary-resource-owner-client"
            };

            var identityResponse =
                await _tokenMintingService.MintIdentityTokenAsync(tokenRequest);

            if (identityResponse.IsError)
            {
                throw new Exception(identityResponse.Error);
            }
            var identityTokenExchangeResponse = new TokenExchangeResponse()
            {
                IdentityToken = new IdentityTokenResponse()
                {
                    hint       = nameof(BriarRabbitInProcTokenExchangeHandler),
                    id_token   = identityResponse.IdentityToken,
                    expires_in = identityResponse.ExpiresIn,
                    authority  =
                        $"{_httpContextAssessor.HttpContext.Request.Scheme}://{_httpContextAssessor.HttpContext.Request.Host}",
                    HttpHeaders = new List <HttpHeader>
                    {
                        new HttpHeader()
                        {
                            Name = "x-authScheme", Value = identityResponse.Scheme
                        }
                    }
                }
            };

            return(new List <TokenExchangeResponse>()
            {
                new TokenExchangeResponse()
                {
                    customToken = new CustomTokenResponse()
                    {
                        authority = Guid.NewGuid().ToString(),
                        hint = "briar_rabbit/token-exchange-validator/custom",
                        Type = Guid.NewGuid().ToString(),
                        Token = Guid.NewGuid().ToString(),
                        HttpHeaders = new List <HttpHeader>()
                        {
                            new HttpHeader()
                            {
                                Name = Guid.NewGuid().ToString(),
                                Value = Guid.NewGuid().ToString()
                            }
                        }
                    },
                },
                identityTokenExchangeResponse,
                tokenExchangeResponse
            });
        }
        public async Task <List <TokenExchangeResponse> > ProcessExchangeAsync(
            TokenExchangeRequest tokenExchangeRequest,
            Dictionary <string, List <KeyValuePair <string, string> > > mapOpaqueKeyValuePairs)
        {
            var access_token = await GetTokenAsync();

            if (string.IsNullOrEmpty(access_token))
            {
                throw new Exception("Unable to fetch client_credentials access_token");
            }

            var headers = new List <HttpHeader>(_externalExchangeRecord.oAuth2_client_credentials.AdditionalHeaders)
            {
                new HttpHeader()
                {
                    Name = "Authorization", Value = $"Bearer {access_token}"
                },
                new HttpHeader()
                {
                    Name = "Accept", Value = $"application/json"
                }
            };
            var passThrough = _externalExchangeRecord.MintType == "passThroughHandler";
            var externalUrl = passThrough ? _externalExchangeRecord.PassThroughHandler.Url : _externalExchangeRecord.ExternalFinalExchangeHandler.Url;

            (string content, HttpStatusCode statusCode)responseBag;
            using (var httpClient = _defaultHttpClientFactory.HttpClient)
            {
                responseBag = await Utils.EfficientApiCalls.HttpClientHelpers.PostStreamAsync(
                    _defaultHttpClientFactory.HttpClient,
                    externalUrl,
                    headers,
                    new TokenExchangeRequestPackage(tokenExchangeRequest)
                {
                    MapOpaqueKeyValuePairs = mapOpaqueKeyValuePairs
                },
                    CancellationToken.None);
            }

            if (responseBag.statusCode == HttpStatusCode.OK)
            {
                if (passThrough)
                {
                    var passThroughResult = JsonConvert.DeserializeObject <List <TokenExchangeResponse> >(responseBag.content);
                    return(passThroughResult);
                }
                else
                {
                    var tokenExchangeResponses        = new List <TokenExchangeResponse>();
                    var externalExchangeTokenRequests = JsonConvert.DeserializeObject <List <ExternalExchangeTokenResponse> >(responseBag.content);

                    foreach (var externalExchangeResourceOwnerTokenRequest in externalExchangeTokenRequests)
                    {
                        if (externalExchangeResourceOwnerTokenRequest.CustomTokenResponse != null)
                        {
                            var tokenExchangeResponse = new TokenExchangeResponse()
                            {
                                customToken = externalExchangeResourceOwnerTokenRequest.CustomTokenResponse
                            };
                            tokenExchangeResponses.Add(tokenExchangeResponse);
                        }
                        if (externalExchangeResourceOwnerTokenRequest.ArbitraryIdentityTokenRequest != null)
                        {
                            var arbitraryIdentityTokenRequest = externalExchangeResourceOwnerTokenRequest
                                                                .ArbitraryIdentityTokenRequest;
                            IdentityTokenRequest tokenRequest = new IdentityTokenRequest()
                            {
                                IdentityTokenLifetime = arbitraryIdentityTokenRequest.IdentityTokenLifetime,
                                ArbitraryClaims       = arbitraryIdentityTokenRequest.ArbitraryClaims,
                                Scope    = arbitraryIdentityTokenRequest.Scope,
                                Subject  = arbitraryIdentityTokenRequest.Subject,
                                ClientId = _externalExchangeRecord.ExternalFinalExchangeHandler.ClientId // configured value
                            };

                            var response =
                                await _tokenMintingService.MintIdentityTokenAsync(tokenRequest);

                            if (response.IsError)
                            {
                                throw new Exception(response.Error);
                            }
                            var tokenExchangeResponse = new TokenExchangeResponse()
                            {
                                IdentityToken = new IdentityTokenResponse()
                                {
                                    hint       = arbitraryIdentityTokenRequest.Hint,
                                    id_token   = response.IdentityToken,
                                    expires_in = response.ExpiresIn,
                                    authority  =
                                        $"{_httpContextAssessor.HttpContext.Request.Scheme}://{_httpContextAssessor.HttpContext.Request.Host}",
                                    HttpHeaders = arbitraryIdentityTokenRequest.HttpHeaders
                                }
                            };
                            tokenExchangeResponses.Add(tokenExchangeResponse);
                        }

                        if (externalExchangeResourceOwnerTokenRequest.ArbitraryResourceOwnerTokenRequest != null)
                        {
                            var arbitraryResourceOwnerTokenRequest = externalExchangeResourceOwnerTokenRequest
                                                                     .ArbitraryResourceOwnerTokenRequest;
                            ResourceOwnerTokenRequest resourceOwnerTokenRequest = new ResourceOwnerTokenRequest()
                            {
                                AccessTokenLifetime = arbitraryResourceOwnerTokenRequest.AccessTokenLifetime,
                                ArbitraryClaims     = arbitraryResourceOwnerTokenRequest.ArbitraryClaims,
                                Scope    = arbitraryResourceOwnerTokenRequest.Scope,
                                Subject  = arbitraryResourceOwnerTokenRequest.Subject,
                                ClientId = _externalExchangeRecord.ExternalFinalExchangeHandler.ClientId // configured value
                            };

                            var response =
                                await _tokenMintingService.MintResourceOwnerTokenAsync(resourceOwnerTokenRequest);

                            if (response.IsError)
                            {
                                throw new Exception(response.Error);
                            }

                            var tokenExchangeResponse = new TokenExchangeResponse()
                            {
                                accessToken = new AccessTokenResponse()
                                {
                                    hint          = arbitraryResourceOwnerTokenRequest.Hint,
                                    access_token  = response.AccessToken,
                                    refresh_token = response.RefreshToken,
                                    expires_in    = response.ExpiresIn,
                                    token_type    = response.TokenType,
                                    authority     =
                                        $"{_httpContextAssessor.HttpContext.Request.Scheme}://{_httpContextAssessor.HttpContext.Request.Host}",
                                    HttpHeaders = arbitraryResourceOwnerTokenRequest.HttpHeaders
                                }
                            };
                            tokenExchangeResponses.Add(tokenExchangeResponse);
                        }
                    }
                    return(tokenExchangeResponses);
                }
            }

            return(null);
        }