public async void OnRedirectToIdentityProvider_CustomUserFlow_UpdatesContext()
        {
            var options = new MicrosoftIdentityOptions()
            {
                SignUpSignInPolicyId = DefaultUserFlow
            };
            var handler        = new AzureADB2COpenIDConnectEventHandlers(OpenIdConnectDefaults.AuthenticationScheme, options);
            var httpContext    = HttpContextUtilities.CreateHttpContext();
            var authProperties = new AuthenticationProperties();

            authProperties.Items.Add(OidcConstants.PolicyKey, CustomUserFlow);
            var context = new RedirectContext(httpContext, _authScheme, new OpenIdConnectOptions(), authProperties)
            {
                ProtocolMessage = new OpenIdConnectMessage()
                {
                    IssuerAddress = _defaultIssuer
                }
            };

            await handler.OnRedirectToIdentityProvider(context).ConfigureAwait(false);

            Assert.Equal(OpenIdConnectScope.OpenIdProfile, context.ProtocolMessage.Scope);
            Assert.Equal(OpenIdConnectResponseType.IdToken, context.ProtocolMessage.ResponseType);
            Assert.Equal(_customIssuer, context.ProtocolMessage.IssuerAddress, true);
            Assert.False(context.Properties.Items.ContainsKey(OidcConstants.PolicyKey));
        }
        private void AddProtectedWebApiCallsProtectedWebApi_TestCommon(IServiceCollection services, ServiceProvider provider)
        {
            // Correct services added
            Assert.Contains(services, s => s.ServiceType == typeof(IHttpContextAccessor));
            Assert.Contains(services, s => s.ServiceType == typeof(ITokenAcquisition));
            Assert.Contains(services, s => s.ServiceType == typeof(IConfigureOptions <ConfidentialClientApplicationOptions>));
            Assert.Contains(services, s => s.ServiceType == typeof(IConfigureOptions <MicrosoftIdentityOptions>));
            Assert.Contains(services, s => s.ServiceType == typeof(IConfigureOptions <JwtBearerOptions>));

            // JWT options added correctly
            var configuredJwtOptions = provider.GetService <IConfigureOptions <JwtBearerOptions> >() as ConfigureNamedOptions <JwtBearerOptions>;

            Assert.Equal(_jwtBearerScheme, configuredJwtOptions.Name);

            // Token validated event added correctly
            var jwtOptions            = provider.GetRequiredService <IOptionsFactory <JwtBearerOptions> >().Create(_jwtBearerScheme);
            var httpContext           = HttpContextUtilities.CreateHttpContext();
            var authScheme            = new AuthenticationScheme(JwtBearerDefaults.AuthenticationScheme, JwtBearerDefaults.AuthenticationScheme, typeof(JwtBearerHandler));
            var tokenValidatedContext = new TokenValidatedContext(httpContext, authScheme, jwtOptions)
            {
                SecurityToken = new JwtSecurityToken()
            };

            jwtOptions.Events.TokenValidated(tokenValidatedContext);

            Assert.NotNull(httpContext.GetTokenUsedToCallWebAPI());
        }
Example #3
0
        private async void AddMicrosoftWebApi_TestJwtBearerTokenValidatedEvent(JwtBearerOptions jwtOptions, Func <TokenValidatedContext, Task> tokenValidatedFunc)
        {
            var scopeTypes = new[] { ClaimConstants.Scope, ClaimConstants.Scp, ClaimConstants.Roles, ClaimConstants.Role };
            var expectedExceptionMessage = IDWebErrorMessage.NeitherScopeOrRolesClaimFoundInToken;
            var scopeValue = "scope";

            var httpContext           = HttpContextUtilities.CreateHttpContext();
            var authScheme            = new AuthenticationScheme(JwtBearerDefaults.AuthenticationScheme, JwtBearerDefaults.AuthenticationScheme, typeof(JwtBearerHandler));
            var tokenValidatedContext = new TokenValidatedContext(httpContext, authScheme, jwtOptions);

            tokenValidatedContext.Principal = new ClaimsPrincipal();

            // No scopes throws exception
            var exception = await Assert.ThrowsAsync <UnauthorizedAccessException>(async() => { await jwtOptions.Events.TokenValidated(tokenValidatedContext).ConfigureAwait(false); }).ConfigureAwait(false);

            Assert.Equal(expectedExceptionMessage, exception.Message);

            // At least one scope executes successfully
            foreach (var scopeType in scopeTypes)
            {
                tokenValidatedContext.Principal = new ClaimsPrincipal(
                    new ClaimsIdentity(new Claim[]
                {
                    new Claim(scopeType, scopeValue),
                }));
                await jwtOptions.Events.TokenValidated(tokenValidatedContext).ConfigureAwait(false);
            }

            await tokenValidatedFunc.Received(4).Invoke(Arg.Any <TokenValidatedContext>()).ConfigureAwait(false);
        }
Example #4
0
        private async Task AddMicrosoftWebApiCallsWebApi_TestCommon(IServiceCollection services, ServiceProvider provider, Func <TokenValidatedContext, Task> tokenValidatedFuncMock)
        {
            // Assert correct services added
            Assert.Contains(services, s => s.ServiceType == typeof(IHttpContextAccessor));
            Assert.Contains(services, s => s.ServiceType == typeof(ITokenAcquisition));
            Assert.Contains(services, s => s.ServiceType == typeof(IConfigureOptions <ConfidentialClientApplicationOptions>));
            Assert.Contains(services, s => s.ServiceType == typeof(IConfigureOptions <MicrosoftIdentityOptions>));
            Assert.Contains(services, s => s.ServiceType == typeof(IConfigureOptions <JwtBearerOptions>));

            // Assert token validated event added correctly
            var jwtOptions            = provider.GetRequiredService <IOptionsFactory <JwtBearerOptions> >().Create(JwtBearerScheme);
            var httpContext           = HttpContextUtilities.CreateHttpContext();
            var authScheme            = new AuthenticationScheme(JwtBearerDefaults.AuthenticationScheme, JwtBearerDefaults.AuthenticationScheme, typeof(JwtBearerHandler));
            var tokenValidatedContext = new TokenValidatedContext(httpContext, authScheme, jwtOptions)
            {
                SecurityToken = new JwtSecurityToken(),
                Principal     = new ClaimsPrincipal(),
            };

            await jwtOptions.Events.TokenValidated(tokenValidatedContext).ConfigureAwait(false);

            // Assert events called
            await tokenValidatedFuncMock.ReceivedWithAnyArgs().Invoke(Arg.Any <TokenValidatedContext>()).ConfigureAwait(false);

            Assert.NotNull(httpContext.GetTokenUsedToCallWebAPI());
        }
Example #5
0
        public void VerifyUserHasAnyAcceptedScope_RequiredScopesEmptyString_Throws()
        {
            RequiredScopeFilter requiredScopeFilter = new RequiredScopeFilter(new string[] { });
            var httpContext = HttpContextUtilities.CreateHttpContext(new string[] { }, new string[] { });

            Assert.Throws <ArgumentNullException>(() => requiredScopeFilter.OnAuthorization(CreateRequiredContext(httpContext)));
        }
Example #6
0
        public async Task OnRedirectToIdentityProvider_DefaultUserFlow_DoesntUpdateContext()
        {
            var errorAccessor = Substitute.For <ILoginErrorAccessor>();
            var options       = new MicrosoftIdentityOptions()
            {
                SignUpSignInPolicyId = DefaultUserFlow
            };
            var handler        = new AzureADB2COpenIDConnectEventHandlers(OpenIdConnectDefaults.AuthenticationScheme, options, errorAccessor);
            var httpContext    = HttpContextUtilities.CreateHttpContext();
            var authProperties = new AuthenticationProperties();

            authProperties.Items.Add(OidcConstants.PolicyKey, DefaultUserFlow);
            var context = new RedirectContext(httpContext, _authScheme, new OpenIdConnectOptions(), authProperties)
            {
                ProtocolMessage = new OpenIdConnectMessage()
                {
                    IssuerAddress = _defaultIssuer
                }
            };

            await handler.OnRedirectToIdentityProvider(context).ConfigureAwait(false);

            errorAccessor.DidNotReceive().SetMessage(httpContext, Arg.Any <string>());
            Assert.Null(context.ProtocolMessage.Scope);
            Assert.Null(context.ProtocolMessage.ResponseType);
            Assert.Equal(_defaultIssuer, context.ProtocolMessage.IssuerAddress);
            Assert.True(context.Properties.Items.ContainsKey(OidcConstants.PolicyKey));
        }
Example #7
0
 public CookiePolicyOptionsExtensionsTests()
 {
     _cookiePolicyOptions = new CookiePolicyOptions()
     {
         MinimumSameSitePolicy = SameSiteMode.Strict
     };
     _httpContext = HttpContextUtilities.CreateHttpContext();
 }
        public void StoreTokenUsedToCallWebAPI()
        {
            var httpContext = HttpContextUtilities.CreateHttpContext();
            var token       = new JwtSecurityToken();

            httpContext.StoreTokenUsedToCallWebAPI(token);

            Assert.Same(token, httpContext.Items[WebApiTokenKeyName]);
        }
        /// <summary>
        /// Create a session object for specific user account
        /// </summary>
        /// <param name="username"></param>
        /// <param name="password"></param>
        /// <returns></returns>
        internal static BaseSessionObject GetSessionObject(string username, string password)
        {
            BaseSessionObject sessionObject = CreateSessionObject();

            sessionObject.Init(username, password);
            var context = HttpContextUtilities.GetHttpContext();

            SaveSessionObjectToHttpContext(sessionObject, context);
            return(sessionObject);
        }
        public SessionDataLoadingResult Load()
        {
            var context = HttpContextUtilities.GetHttpContext();

            if (context != null)
            {
                return(LoadSessionObjectDataFromCookie(context));
            }
            return(LoadSessionObjectDataFromAssemblyIsolatedStorage());
        }
Example #11
0
        public void VerifyUserHasAnyAcceptedScope_NullParameters_ThrowsException()
        {
            HttpContext httpContext = null;

            Assert.Throws <ArgumentNullException>(() => httpContext.VerifyUserHasAnyAcceptedScope(string.Empty));

            httpContext = HttpContextUtilities.CreateHttpContext();

            Assert.Throws <ArgumentNullException>("acceptedScopes", () => httpContext.VerifyUserHasAnyAcceptedScope(null));
        }
Example #12
0
        public void VerifyUserHasAnyAcceptedScope_WithNoUserContext_Throws()
        {
            string[]            expectedScopes      = new string[] { ScopeOne };
            RequiredScopeFilter requiredScopeFilter = new RequiredScopeFilter(expectedScopes);
            var httpContext = HttpContextUtilities.CreateHttpContext();

            var exc = Assert.Throws <UnauthorizedAccessException>(() => requiredScopeFilter.OnAuthorization(CreateRequiredContext(httpContext)));

            Assert.Equal(IDWebErrorMessage.UnauthenticatedUser, exc.Message);
        }
        /// <summary>
        ///
        /// </summary>
        /// <param name="user"></param>
        /// <returns></returns>
        internal static BaseSessionObject GetSessionObject(User user)
        {
            BaseSessionObject sessionObject = CreateSessionObject();

            sessionObject.Init(user);
            var context = HttpContextUtilities.GetHttpContext();

            SaveSessionObjectToHttpContext(sessionObject, context);
            return(sessionObject);
        }
        public void VerifyAppHasAnyAcceptedRoles_NoClaims_ThrowsException()
        {
            var acceptedRoles      = new[] { "access_as_application", "access_as_application_for_write" };
            var expectedStatusCode = (int)HttpStatusCode.Unauthorized;

            var httpContext = HttpContextUtilities.CreateHttpContext();

            Assert.Throws <UnauthorizedAccessException>(() => httpContext.ValidateAppRole(acceptedRoles));
            Assert.Equal(expectedStatusCode, httpContext.Response.StatusCode);
        }
Example #15
0
        public void VerifyUserHasAnyAcceptedScope()
        {
            string[]            expectedScopes      = new string[] { ScopeOne };
            RequiredScopeFilter requiredScopeFilter = new RequiredScopeFilter(expectedScopes);
            var httpContext = HttpContextUtilities.CreateHttpContext(expectedScopes, new string[] { });

            requiredScopeFilter.OnAuthorization(CreateRequiredContext(httpContext));
            Assert.Equal(expectedScopes, requiredScopeFilter._acceptedScopes);
            Assert.Equal(expectedScopes, requiredScopeFilter._effectiveAcceptedScopes);
        }
        public void Remove()
        {
            var context = HttpContextUtilities.GetHttpContext();

            if (context != null)
            {
                RemoveSessionObjectDataFromCookie(context);
                return;
            }
            RemoveSessionObjectDataFromAssemblyIsolatedStorage();
        }
        public void VerifyUserHasAnyAcceptedScope_NoClaims_ThrowsException()
        {
            var acceptedScopes     = new[] { "acceptedScope1", "acceptedScope2" };
            var expectedStatusCode = (int)HttpStatusCode.Unauthorized;

            var httpContext = HttpContextUtilities.CreateHttpContext();

            Assert.Throws <UnauthorizedAccessException>(() => httpContext.VerifyUserHasAnyAcceptedScope(acceptedScopes));

            Assert.Equal(expectedStatusCode, httpContext.Response.StatusCode);
        }
        private (HttpContext, AuthenticationScheme, AuthenticationProperties) CreateContextParameters(IServiceProvider provider)
        {
            var httpContext = HttpContextUtilities.CreateHttpContext();

            httpContext.RequestServices = provider;

            var authScheme     = new AuthenticationScheme(OpenIdConnectDefaults.AuthenticationScheme, OpenIdConnectDefaults.AuthenticationScheme, typeof(OpenIdConnectHandler));
            var authProperties = new AuthenticationProperties();

            return(httpContext, authScheme, authProperties);
        }
        public void GetTokenUsedToCallWebAPI()
        {
            var httpContext = HttpContextUtilities.CreateHttpContext();
            var token       = new JwtSecurityToken();

            Assert.Null(httpContext.GetTokenUsedToCallWebAPI());

            httpContext.StoreTokenUsedToCallWebAPI(token);

            Assert.Same(token, httpContext.GetTokenUsedToCallWebAPI());
        }
        public void Save(SessionData data)
        {
            var context = HttpContextUtilities.GetHttpContext();

            if (context != null)
            {
                SaveSessionObjectDataToCookie(data, context);
                return;
            }

            SaveSessionObjectDataToAssemblyIsolatedStorage(data);
        }
Example #21
0
        public void VerifyUserHasAnyAcceptedScope_NoAcceptedScopes_ThrowsException()
        {
            var acceptedScopes       = new[] { "acceptedScope1", "acceptedScope2" };
            var actualScopes         = new[] { "acceptedScope3", "acceptedScope4" };
            var expectedErrorMessage = string.Format(CultureInfo.InvariantCulture, IDWebErrorMessage.MissingScopes, string.Join(",", acceptedScopes));
            var expectedStatusCode   = (int)HttpStatusCode.Forbidden;

            var httpContext = HttpContextUtilities.CreateHttpContext(actualScopes, new string[] { });

            Assert.Throws <UnauthorizedAccessException>(() => httpContext.VerifyUserHasAnyAcceptedScope(acceptedScopes));

            Assert.Equal(expectedStatusCode, httpContext.Response.StatusCode);
        }
        public void VerifyAppHasAnyAcceptedRole_NoAcceptedRoles_ThrowsException()
        {
            var acceptedRoles        = new[] { "access_as_application", "access_as_application_for_write" };
            var actualRoles          = new[] { "access_as_application_for_read_all_directory", "access_as_application_for_read" };
            var expectedErrorMessage = string.Format(CultureInfo.InvariantCulture, IDWebErrorMessage.MissingRoles, string.Join(", ", acceptedRoles));
            var expectedStatusCode   = (int)HttpStatusCode.Forbidden;

            var httpContext = HttpContextUtilities.CreateHttpContext(new string[] { }, actualRoles);

            Assert.Throws <UnauthorizedAccessException>(() => httpContext.ValidateAppRole(acceptedRoles));

            Assert.Equal(expectedStatusCode, httpContext.Response.StatusCode);
        }
        public void VerifyUserHasAnyAcceptedScope_NoClaims_ThrowsException()
        {
            var acceptedScopes       = new[] { "acceptedScope1", "acceptedScope2" };
            var expectedErrorMessage = $"The 'scope' claim does not contain scopes '{string.Join(",", acceptedScopes)}' or was not found";
            var expectedStatusCode   = (int)HttpStatusCode.Unauthorized;

            var httpContext = HttpContextUtilities.CreateHttpContext();

            var exception = Assert.Throws <HttpRequestException>(() => httpContext.VerifyUserHasAnyAcceptedScope(acceptedScopes));

            Assert.Equal(expectedStatusCode, httpContext.Response.StatusCode);
            Assert.Equal(expectedErrorMessage, exception.Message);
        }
 public JwtBearerMiddlewareDiagnosticsTests()
 {
     _customEventWasRaised = false;
     _httpContext          = HttpContextUtilities.CreateHttpContext();
     _logger         = Substitute.For <ILogger <JwtBearerMiddlewareDiagnostics> >();
     _jwtDiagnostics = new JwtBearerMiddlewareDiagnostics(new LoggerMock <JwtBearerMiddlewareDiagnostics>(_logger));
     _jwtOptions     = new JwtBearerOptions();
     _jwtEvents      = new JwtBearerEvents();
     _authScheme     = new AuthenticationScheme(JwtBearerDefaults.AuthenticationScheme, JwtBearerDefaults.AuthenticationScheme, typeof(JwtBearerHandler));
     _eventHandler   = (context) => {
         _customEventWasRaised = true;
         return(Task.CompletedTask);
     };
 }
Example #25
0
        public void VerifyUserHasAnyAcceptedScope_WithMismatchScope_Throws()
        {
            string[]            expectedScopes      = new string[] { ScopeOne };
            RequiredScopeFilter requiredScopeFilter = new RequiredScopeFilter(expectedScopes);
            var httpContext = HttpContextUtilities.CreateHttpContext(new string[] { ScopeTwo }, new string[] { });

            string message = string.Format(
                CultureInfo.InvariantCulture,
                IDWebErrorMessage.MissingScopes,
                string.Join(",", expectedScopes));
            var exc = Assert.Throws <UnauthorizedAccessException>(() => requiredScopeFilter.OnAuthorization(CreateRequiredContext(httpContext)));

            Assert.Equal(message, exc.Message);
        }
Example #26
0
        private (HttpContext, AuthenticationScheme, AuthenticationProperties) CreateContextParameters(IServiceProvider provider)
        {
            var httpContext = HttpContextUtilities.CreateHttpContext();

            httpContext.RequestServices = provider;
            httpContext.Request.Form    = new FormCollection(
                new Dictionary <string, StringValues>()
            {
                { ClaimConstants.ClientInfo, Base64UrlHelpers.Encode($"{{\"uid\":\"{TestConstants.Uid}\",\"utid\":\"{TestConstants.Utid}\"}}") }
            });
            var authScheme     = new AuthenticationScheme(OpenIdConnectDefaults.AuthenticationScheme, OpenIdConnectDefaults.AuthenticationScheme, typeof(OpenIdConnectHandler));
            var authProperties = new AuthenticationProperties();

            return(httpContext, authScheme, authProperties);
        }
Example #27
0
 public OpenIdConnectMiddlewareDiagnosticsTests()
 {
     _customEventWasRaised = false;
     _httpContext          = HttpContextUtilities.CreateHttpContext();
     _logger            = Substitute.For <ILogger <OpenIdConnectMiddlewareDiagnostics> >();
     _openIdDiagnostics = new OpenIdConnectMiddlewareDiagnostics(new LoggerMock <OpenIdConnectMiddlewareDiagnostics>(_logger));
     _openIdOptions     = new OpenIdConnectOptions();
     _openIdEvents      = new OpenIdConnectEvents();
     _authProperties    = new AuthenticationProperties();
     _authScheme        = new AuthenticationScheme(OpenIdConnectDefaults.AuthenticationScheme, OpenIdConnectDefaults.AuthenticationScheme, typeof(OpenIdConnectHandler));
     _eventHandler      = (context) => {
         _customEventWasRaised = true;
         return(Task.CompletedTask);
     };
 }
Example #28
0
        public void VerifyUserHasAnyAcceptedScope_MatchesAcceptedScopes_ExecutesSuccessfully()
        {
            var httpContext = HttpContextUtilities.CreateHttpContext(new[] { "acceptedScope1" });

            httpContext.VerifyUserHasAnyAcceptedScope("acceptedScope1");

            httpContext = HttpContextUtilities.CreateHttpContext(new[] { "acceptedScope1 acceptedScope2" });
            httpContext.VerifyUserHasAnyAcceptedScope("acceptedScope2");

            httpContext = HttpContextUtilities.CreateHttpContext(new[] { "acceptedScope2" });
            httpContext.VerifyUserHasAnyAcceptedScope("acceptedScope1", "acceptedScope2");

            httpContext = HttpContextUtilities.CreateHttpContext(new[] { "acceptedScope2 acceptedScope1" });
            httpContext.VerifyUserHasAnyAcceptedScope("acceptedScope1", "acceptedScope2");
        }
        public void VerifyAppHasAnyAcceptedRole_MatchesAcceptedRoles_ExecutesSuccessfully()
        {
            var httpContext = HttpContextUtilities.CreateHttpContext(new string[] { }, new[] { "acceptedRole1" });

            httpContext.ValidateAppRole("acceptedRole1");

            httpContext = HttpContextUtilities.CreateHttpContext(new string[] { }, new[] { "acceptedRole1 acceptedRole2" });
            httpContext.ValidateAppRole("acceptedRole2");

            httpContext = HttpContextUtilities.CreateHttpContext(new string[] { }, new[] { "acceptedRole2" });
            httpContext.ValidateAppRole("acceptedRole1", "acceptedRole2");

            httpContext = HttpContextUtilities.CreateHttpContext(new string[] { }, new[] { "acceptedRole2 acceptedRole1" });
            httpContext.ValidateAppRole("acceptedRole1", "acceptedRole2");
        }
Example #30
0
        public async Task OnRedirectToIdentityProvider_CustomUserFlow_UpdatesContext(bool hasClientCredentials)
        {
            var errorAccessor = Substitute.For <ILoginErrorAccessor>();
            var options       = new MicrosoftIdentityOptions()
            {
                SignUpSignInPolicyId = DefaultUserFlow
            };

            if (hasClientCredentials)
            {
                options.ClientSecret = TestConstants.ClientSecret;
            }

            var handler        = new AzureADB2COpenIDConnectEventHandlers(OpenIdConnectDefaults.AuthenticationScheme, options, errorAccessor);
            var httpContext    = HttpContextUtilities.CreateHttpContext();
            var authProperties = new AuthenticationProperties();

            authProperties.Items.Add(OidcConstants.PolicyKey, CustomUserFlow);
            var context = new RedirectContext(httpContext, _authScheme, new OpenIdConnectOptions(), authProperties)
            {
                ProtocolMessage = new OpenIdConnectMessage()
                {
                    IssuerAddress = _defaultIssuer,
                    Scope         = TestConstants.Scopes,
                },
            };

            await handler.OnRedirectToIdentityProvider(context).ConfigureAwait(false);

            errorAccessor.DidNotReceive().SetMessage(httpContext, Arg.Any <string>());
            Assert.Equal(TestConstants.Scopes, context.ProtocolMessage.Scope);
            Assert.Equal(_customIssuer, context.ProtocolMessage.IssuerAddress, true);
            Assert.False(context.Properties.Items.ContainsKey(OidcConstants.PolicyKey));
            if (hasClientCredentials)
            {
                Assert.Equal(OpenIdConnectResponseType.CodeIdToken, context.ProtocolMessage.ResponseType);
            }
            else
            {
                Assert.Equal(OpenIdConnectResponseType.IdToken, context.ProtocolMessage.ResponseType);
            }
        }