public async Task <IActionResult> CreateAuthorizeResponseActionResultAsync(
            string key,
            bool delete = true)
        {
            var original = await _oidcPipelineStore.GetOriginalIdTokenRequestAsync(key);

            var downstream = await _oidcPipelineStore.GetDownstreamIdTokenResponseAsync(key);

            if (!string.IsNullOrWhiteSpace(original.Nonce))
            {
                downstream.Custom["nonce"] = original.Nonce;
            }

            var header  = new JwtHeader();
            var handler = new JwtSecurityTokenHandler();
            var idToken = handler.ReadJwtToken(downstream.IdToken);
            var claims  = idToken.Claims.ToList();
            var scope   = (from item in claims where item.Type == "scope" select item).FirstOrDefault();

            var authResponse = new AuthorizeResponse();

            if (original.CodeChallenge.IsPresent() &&
                original.CodeChallengeMethod.IsPresent())
            {
                // slide out the stored stuff , as we will have a incoming token request with a code
                await _oidcPipelineStore.StoreDownstreamIdTokenResponseAsync(key, downstream);

                authResponse.Code = key;
            }
            else
            {
                authResponse.IdentityToken = downstream.IdToken;
                authResponse.AccessToken   = downstream.AccessToken;
            }
            authResponse.Request    = original;
            authResponse.Downstream = downstream;
            authResponse.Scope      = scope?.Value;



            var authorizeResult = new AuthorizeResult(authResponse);

            if (delete && authResponse.Code.IsMissing())
            {
                await _oidcPipelineStore.DeleteStoredCacheAsync(key);
            }
            return(authorizeResult);
        }
        public async Task <IActionResult> OnPostWay2(string data)
        {
            string key = _oidcPipeLineKey.GetOIDCPipeLineKey();
            var    originalIdTokenRequest = await _oidcPipelineStore.GetOriginalIdTokenRequestAsync(key);

            var tempCustom = await _oidcPipelineStore.GetTempCustomObjectsAsync(key);

            var custom = new Custom
            {
                Name    = "Bugs Bunny",
                Numbers = new List <int>()
                {
                    1, 2, 3
                },
                Strings = new List <string>()
                {
                    "a", "bb", "ccc"
                },
                SomeObject = new SomeObject {
                    Name = "Daffy Duck"
                },
                SomeObjects = new List <SomeObject>()
                {
                    new SomeObject {
                        Name = "Daisy Duck"
                    },
                    new SomeObject {
                        Name = "Porky Pig"
                    },
                },
                Temp = tempCustom
            };
            var json = _serializer.Serialize(custom);

            await _oidcPipelineStore.StoreDownstreamCustomDataAsync(key, new Dictionary <string, object> {
                { "prodInstance", Guid.NewGuid() },
                { "extraStuff", custom },
                { "originalRequest", originalIdTokenRequest.Raw }
            });

            var result = await _oidcResponseGenerator.CreateAuthorizeResponseActionResultAsync(key, true);

            await _signInManager.SignOutAsync();// we don't want our loggin hanging around

            return(result);
        }
Exemple #3
0
        public async Task <IActionResult> CreateIdTokenActionResultResponseAsync(
            string key,
            NameValueCollection extras = null,
            bool delete = true)
        {
            var original = await _oidcPipelineStore.GetOriginalIdTokenRequestAsync(key);

            var downstream = await _oidcPipelineStore.GetDownstreamIdTokenResponse(key);

            var header  = new JwtHeader();
            var handler = new JwtSecurityTokenHandler();
            var idToken = handler.ReadJwtToken(downstream.id_token);
            var claims  = idToken.Claims.ToList();
            var scope   = (from item in claims where item.Type == "scope" select item).FirstOrDefault();



            var authResponse = new AuthorizeResponse()
            {
                Request = new ValidatedAuthorizeRequest
                {
                    State        = original.state,
                    RedirectUri  = original.redirect_uri,
                    ResponseMode = original.response_mode
                },
                IdentityToken = downstream.id_token,
                AccessToken   = downstream.access_token,
                Scope         = scope?.Value
            };
            var authorizeResult = new AuthorizeResult(authResponse, extras);

            if (delete)
            {
                await _oidcPipelineStore.DeleteStoredCacheAsync(key);
            }
            return(authorizeResult);
        }
Exemple #4
0
        public async Task OnGetAsync()
        {
            NameIdentifier = User.Claims.GetClaimsByType(".externalNamedIdentitier").FirstOrDefault().Value;
            IdToken        = User.Claims.GetClaimsByType(".id_token").FirstOrDefault().Value;

            var key = _oidcPipelineKey.GetOIDCPipeLineKey();

            OriginalAuthorizationRequest = await _oidcPipelineStore.GetOriginalIdTokenRequestAsync(key);

            var queryScopes = (from item in OriginalAuthorizationRequest.Raw
                               where item.Key == "scope"
                               let scopes = item.Value.Split(" ")
                                            from cItem in scopes
                                            where cItem.StartsWith(ScopeBaseUrl)
                                            select cItem).ToList();

            var scope = string.Join(" ", queryScopes);

            scope += " offline_access";



            var docoTokenService = await _tokenServiceDiscoveryCache.GetAsync();

            _logger.LogDebug(docoTokenService.Raw);

            /*
             * ArbitraryTokenTokenRequestV2 = new ArbitraryTokenTokenRequestV2() {
             *  Address = docoTokenService.TokenEndpoint,
             *  ClientId = _FluffyBunny4TokenServiceConfiguration.ClientId,
             *  ClientSecret = _FluffyBunny4TokenServiceConfiguration.ClientSecret,
             *  Subject = NameIdentifier,
             *  Scope = new HashSet<string>(),
             *  ArbitraryClaims = new Dictionary<string, List<string>>(),
             *  ArbitraryAmrs = new List<string>(),
             *  ArbitraryAudiences = new List<string>(),
             *  CustomPayload = null
             * };
             */
            TokenExchangeTokenRequest = new TokenExchangeTokenRequest
            {
                Address          = docoTokenService.TokenEndpoint,
                ClientId         = _FluffyBunny4TokenServiceConfiguration.ClientId,
                ClientSecret     = _FluffyBunny4TokenServiceConfiguration.ClientSecret,
                Scope            = scope,
                GrantType        = OidcConstants.GrantTypes.TokenExchange,
                SubjectTokenType = FluffyBunny4.Constants.TokenExchangeTypes.IdToken,
                SubjectToken     = IdToken
            };
            _logger.LogDebug(_serializer.Serialize(TokenExchangeTokenRequest, true));

            var client = _httpClientFactory.CreateClient("HttpClient");

            TokenPayload = await _fluffyBunnyTokenService.RequestTokenExchangeTokenAsync(client, TokenExchangeTokenRequest);

            if (TokenPayload.IsError)
            {
                _logger.LogError("RequestTokenExchangeTokenAsync");
                _logger.LogError(TokenPayload.ErrorDescription);
            }
            var tokenExchangePayload = new
            {
                access_token  = TokenPayload.AccessToken,
                refresh_token = TokenPayload.RefreshToken,
                scope         = TokenPayload.Scope,
                token_type    = TokenPayload.TokenType
            };
            await _oidcPipelineStore.StoreTempCustomObjectAsync(key, "token-exchange", tokenExchangePayload);
        }
Exemple #5
0
        public async Task OnGetAsync()
        {
            NameIdentifier = User.Claims.GetClaimsByType(".externalNamedIdentitier").FirstOrDefault().Value;

            var key = _oidcPipelineKey.GetOIDCPipeLineKey();

            OriginalAuthorizationRequest = await _oidcPipelineStore.GetOriginalIdTokenRequestAsync(key);

            var queryScopes = (from item in OriginalAuthorizationRequest.Raw
                               where item.Key == "scope"
                               let scopes = item.Value.Split(" ")
                                            from cItem in scopes
                                            where cItem.StartsWith(ScopeBaseUrl)
                                            select cItem).ToList();


            ConsentResponseContainers = new List <ConsentResponseContainer>();
            ExternalServiceEntities   = await _oidcConsentOrchestratorAdmin.GetAllExternalServiceEntitiesAsync();

            foreach (var es in ExternalServiceEntities)
            {
                var queryScopesService = (from item in queryScopes
                                          where item.StartsWith($"{ScopeBaseUrl}{es.Name}")
                                          select item).ToList();
                if (queryScopesService.Any())
                {
                    var discoCache = _consentDiscoveryCacheAccessor.GetConsentDiscoveryCache(es);
                    var doco       = await discoCache.GetAsync();

                    List <string> scopes = null;
                    switch (doco.AuthorizationType)
                    {
                    case Constants.AuthorizationTypes.Implicit:
                        scopes = null;
                        break;

                    case Constants.AuthorizationTypes.Subject:
                        scopes = null;
                        break;

                    case Constants.AuthorizationTypes.SubjectAndScopes:
                        scopes = queryScopes;
                        break;
                    }
                    if (doco.AuthorizationType != Constants.AuthorizationTypes.Implicit)
                    {
                        var request = new ConsentAuthorizeRequest
                        {
                            AuthorizeType = doco.AuthorizationType,
                            Scopes        = scopes,
                            Subject       = NameIdentifier
                        };
                        var response = await _consentExternalService.PostAuthorizationRequestAsync(doco, request);

                        var consentResponseContainer = new ConsentResponseContainer()
                        {
                            ExternalServiceEntity = es,
                            DiscoveryDocument     = doco,
                            Request  = request,
                            Response = response
                        };
                        ConsentResponseContainers.Add(consentResponseContainer);
                    }
                    else
                    {
                        ConsentResponseContainers.Add(new ConsentResponseContainer {
                            ExternalServiceEntity = es,
                            DiscoveryDocument     = doco,
                            Request  = null,
                            Response = null
                        });
                    }
                }
            }
            var finalScopes = (from item in ConsentResponseContainers
                               where item.Response.Authorized == true
                               from scope in item.Response.Scopes
                               select scope).ToList();

            var claims = (from item in ConsentResponseContainers
                          where item.Response.Authorized == true && item.Response.Claims != null
                          from claim in item.Response.Claims
                          let c = new ConsentAuthorizeClaim
            {
                Type = $"{item.ExternalServiceEntity.Name}.{claim.Type}",
                Value = claim.Value
            }
                          select c)
                         .DistinctBy(p => new { p.Type, p.Value })
                         .ToList();


            var customs = (from item in ConsentResponseContainers
                           where item.Response.Authorized == true && item.Response.CustomPayload != null
                           let c = new CustomPayloadContainer
            {
                Name = $"{item.ExternalServiceEntity.Name}",
                CustomPayload = item.Response.CustomPayload
            }
                           select c).ToList();

            var docoTokenService = await _tokenServiceDiscoveryCache.GetAsync();

            ArbitraryTokenTokenRequestV2 = new ArbitraryTokenTokenRequestV2()
            {
                Address            = docoTokenService.TokenEndpoint,
                ClientId           = _FluffyBunny4TokenServiceConfiguration.ClientId,
                ClientSecret       = _FluffyBunny4TokenServiceConfiguration.ClientSecret,
                Subject            = NameIdentifier,
                Scope              = new HashSet <string>(),
                ArbitraryClaims    = new Dictionary <string, List <string> >(),
                ArbitraryAmrs      = new List <string>(),
                ArbitraryAudiences = new List <string>(),
                CustomPayload      = null
            };

            if (customs.Any())
            {
                Dictionary <string, object> customMap = new Dictionary <string, object>();
                foreach (var custom in customs)
                {
                    customMap[custom.Name] = custom.CustomPayload;
                }
                ArbitraryTokenTokenRequestV2.CustomPayload = customMap;
            }
            foreach (var item in finalScopes)
            {
                ArbitraryTokenTokenRequestV2.Scope.Add(item);
            }

            foreach (var claim in claims)
            {
                if (!ArbitraryTokenTokenRequestV2.ArbitraryClaims.ContainsKey(claim.Type))
                {
                    ArbitraryTokenTokenRequestV2.ArbitraryClaims[claim.Type] = new List <string>();
                }
                ArbitraryTokenTokenRequestV2.ArbitraryClaims[claim.Type].Add(claim.Value);
            }
            JsonArbitraryTokenTokenRequestV2 = _serializer.Serialize(ArbitraryTokenTokenRequestV2);

            var httpClient   = new HttpClient();
            var tokenPayload = await _fluffyBunnyTokenService.RequestArbitraryTokenAsync(httpClient, ArbitraryTokenTokenRequestV2);
        }