public static async Task AuthenticateRequest_WithMWSVersion_WithDisableV1_WillThrowExceptionWithInvalidVersion(
            string method)
        {
            // Arrange
            var testData = await method.FromResource();

            var testOptions = TestExtensions.ServerOptions;

            testOptions.DisableV1 = true;
            var authenticator = new MAuthAuthenticator(testOptions, NullLogger <MAuthAuthenticator> .Instance);
            var mAuthCore     = new MAuthCore();

            var signedRequest = await mAuthCore
                                .AddAuthenticationInfo(testData.ToHttpRequestMessage(), new PrivateKeyAuthenticationInfo()
            {
                ApplicationUuid = testData.ApplicationUuid,
                PrivateKey      = TestExtensions.ClientPrivateKey,
                SignedTime      = testData.SignedTime
            });

            // Act
            var exception = (await Assert.ThrowsAsync <InvalidVersionException>(
                                 () => authenticator.AuthenticateRequest(signedRequest)));

            // Assert
            Assert.NotNull(exception);
            Assert.Equal("Authentication with MWS version is disabled.", exception.Message);
        }
        public static async Task AuthenticateRequest_WithMWSV2Request_AfterNumberOfAttempts_WillThrowExceptionWithRequestFailure(
            MAuthServiceRetryPolicy policy)
        {
            // Arrange
            var testData      = await "GET".FromResource();
            var version       = MAuthVersion.MWSV2;
            var authenticator = new MAuthAuthenticator(TestExtensions.GetServerOptionsWithAttempts(
                                                           policy, shouldSucceedWithin: false), NullLogger <MAuthAuthenticator> .Instance);
            var mAuthCore = new MAuthCoreV2();

            var signedRequest = await mAuthCore
                                .AddAuthenticationInfo(testData.ToHttpRequestMessage(version), new PrivateKeyAuthenticationInfo()
            {
                ApplicationUuid = testData.ApplicationUuid,
                PrivateKey      = TestExtensions.ClientPrivateKey,
                SignedTime      = testData.SignedTime
            });

            // Act
            var exception = (await Assert.ThrowsAsync <AuthenticationException>(
                                 () => authenticator.AuthenticateRequest(signedRequest)));

            var innerException = exception.InnerException as RetriedRequestException;

            // Assert
            Assert.NotNull(innerException);
            Assert.Equal((int)policy + 1, innerException.Responses.Count);
            Assert.Equal(HttpStatusCode.ServiceUnavailable, innerException.Responses.First().StatusCode);
        }
Ejemplo n.º 3
0
        public async Task AuthenticateRequest_AfterNumberOfAttempts_WillThrowExceptionWithRequestFailure(
            MAuthServiceRetryPolicy policy)
        {
            // Arrange
            var testData = await TestData.For("GET");

            var authenticator = new MAuthAuthenticator(TestExtensions.GetServerOptionsWithAttempts(
                                                           policy, shouldSucceedWithin: false));

            var signedRequest = await testData.Request.AddAuthenticationInfo(new PrivateKeyAuthenticationInfo()
            {
                ApplicationUuid = TestExtensions.ClientUuid,
                PrivateKey      = TestExtensions.ClientPrivateKey,
                SignedTime      = testData.SignedTime
            });

            // Act
            var exception = (await Assert.ThrowsAsync <AuthenticationException>(
                                 () => authenticator.AuthenticateRequest(signedRequest)));

            var innerException = exception.InnerException as RetriedRequestException;

            // Assert
            Assert.NotNull(innerException);
            Assert.Equal((int)policy + 1, innerException.Responses.Count);
            Assert.Equal(HttpStatusCode.ServiceUnavailable, innerException.Responses.First().StatusCode);
        }
        /// <summary>
        /// Creates a new <see cref="MAuthMiddleware"/>
        /// </summary>
        /// <param name="next">The <see cref="RequestDelegate"/> representing the next middleware in the pipeline.</param>
        /// <param name="options">The <see cref="MAuthMiddlewareOptions"/> representing the options for the middleware.</param>
        /// <param name="loggerFactory">The <see cref="ILoggerFactory"/> representing the factory that used to create logger instances.</param>
        public MAuthMiddleware(RequestDelegate next, MAuthMiddlewareOptions options, ILoggerFactory loggerFactory)
        {
            this.next     = next;
            this.options  = options;
            loggerFactory = loggerFactory ?? NullLoggerFactory.Instance;
            ILogger logger = loggerFactory.CreateLogger <MAuthMiddleware>();

            this.authenticator = new MAuthAuthenticator(options, logger);
        }
        protected override async Task <HttpResponseMessage> SendAsync(
            HttpRequestMessage request, CancellationToken cancellationToken)
        {
            currentNumberOfAttempts += 1;
            var version   = request.GetAuthHeaderValue().GetVersionFromAuthenticationHeader();
            var mAuthCore = MAuthCoreFactory.Instantiate(version);

            if (currentNumberOfAttempts < SucceedAfterThisManyAttempts)
            {
                return(new HttpResponseMessage(HttpStatusCode.ServiceUnavailable));
            }
            var authInfo = MAuthAuthenticator.GetAuthenticationInfo(request, mAuthCore);

            if (!mAuthCore.Verify(authInfo.Payload,
                                  await mAuthCore.GetSignature(request, authInfo),
                                  TestExtensions.ServerPublicKey
                                  ))
            {
                return new HttpResponseMessage(HttpStatusCode.Unauthorized)
                       {
                           RequestMessage = request
                       }
            }
            ;

            if (!request.RequestUri.AbsolutePath.Equals(
                    $"{Constants.MAuthTokenRequestPath}{clientUuid.ToHyphenString()}.json",
                    StringComparison.OrdinalIgnoreCase))
            {
                return new HttpResponseMessage(HttpStatusCode.NotFound)
                       {
                           RequestMessage = request
                       }
            }
            ;

            return(new HttpResponseMessage(HttpStatusCode.OK)
            {
                RequestMessage = request,
                Content = new StringContent(
                    JsonConvert.SerializeObject(new
                {
                    security_token = new ApplicationInfo()
                    {
                        Uuid = clientUuid,
                        Name = "Medidata.MAuth.Tests",
                        CreationDate = new DateTimeOffset(2016, 8, 1, 0, 0, 0, TimeSpan.Zero),
                        PublicKey = TestExtensions.ClientPublicKey
                    }
                })
                    )
            });
        }
    }
}
        public static async Task GetAuthenticationInfo_WithSignedRequest_ForMWSVersion_WillReturnCorrectAuthInfo(string method)
        {
            // Arrange
            var testData = await method.FromResource();

            var version     = MAuthVersion.MWS;
            var testOptions = TestExtensions.ServerOptions;
            var mAuthCore   = MAuthCoreFactory.Instantiate(version);

            // Act
            var actual = MAuthAuthenticator.GetAuthenticationInfo(testData.ToHttpRequestMessage(version), mAuthCore);

            // Assert
            Assert.Equal(testData.ApplicationUuid, actual.ApplicationUuid);
            Assert.Equal(Convert.FromBase64String(testData.Payload), actual.Payload);
            Assert.Equal(testData.SignedTime, actual.SignedTime);
        }
Ejemplo n.º 7
0
        /// <summary>
        /// Attempts to authenticate the provided request in the <see cref="IOwinContext"/> with the provided
        /// authenticator.
        /// </summary>
        /// <param name="context">The context of the request.</param>
        /// <param name="authenticator">The authenticator which will attempt the request authentication.</param>
        /// <param name="shouldIgnoreExceptions">Determines if any exceptions during the authentication
        /// should be thrown.</param>
        /// <returns>
        /// This method returns <see langword="true"/> if it successfully authenticated the request;
        /// otherwise it will return either <see langword="false"/> if the method should ignore exceptions or
        /// will throw an exception if any errors occurred during the authentication.</returns>
        public static async Task <bool> TryAuthenticate(
            this IOwinContext context, MAuthAuthenticator authenticator, bool shouldIgnoreExceptions)
        {
            try
            {
                return(await authenticator.AuthenticateRequest(context.Request.ToHttpRequestMessage()));
            }
            catch (Exception)
            {
                if (shouldIgnoreExceptions)
                {
                    return(false);
                }

                throw;
            }
        }
Ejemplo n.º 8
0
        /// <summary>
        /// Attempts to authenticate the provided request in the <see cref="HttpRequestMessage"/> with the provided
        /// authenticator.
        /// </summary>
        /// <param name="request">The request to try to authenticate.</param>
        /// <param name="authenticator">The authenticator which will attempt the request authentication.</param>
        /// <param name="shouldIgnoreExceptions">Determines if any exceptions during the authentication
        /// should be thrown.</param>
        /// <returns>
        /// This method returns <see langword="true"/> if it successfully authenticated the request;
        /// otherwise it will return either <see langword="false"/> if the method should ignore exceptions or
        /// will throw an exception if any errors occurred during the authentication.</returns>
        public static async Task <bool> TryAuthenticate(
            this HttpRequestMessage request, MAuthAuthenticator authenticator, bool shouldIgnoreExceptions)
        {
            try
            {
                return(await authenticator.AuthenticateRequest(request).ConfigureAwait(false));
            }
            catch (Exception)
            {
                if (shouldIgnoreExceptions)
                {
                    return(false);
                }

                throw;
            }
        }
Ejemplo n.º 9
0
        public async Task AuthenticateRequest_WithValidRequest_WillAuthenticate(string method)
        {
            // Arrange
            var testData = await TestData.For(method);

            var authenticator = new MAuthAuthenticator(TestExtensions.ServerOptions);

            var signedRequest = await testData.Request.AddAuthenticationInfo(new PrivateKeyAuthenticationInfo()
            {
                ApplicationUuid = TestExtensions.ClientUuid,
                PrivateKey      = TestExtensions.ClientPrivateKey,
                SignedTime      = testData.SignedTime
            });

            // Act
            var isAuthenticated = await authenticator.AuthenticateRequest(signedRequest);

            // Assert
            Assert.True(isAuthenticated);
        }
Ejemplo n.º 10
0
        public async Task AuthenticateRequest_WithNumberOfAttempts_WillAuthenticate(MAuthServiceRetryPolicy policy)
        {
            // Arrange
            var testData = await TestData.For("GET");

            var authenticator = new MAuthAuthenticator(TestExtensions.GetServerOptionsWithAttempts(
                                                           policy, shouldSucceedWithin: true));

            var signedRequest = await testData.Request.AddAuthenticationInfo(new PrivateKeyAuthenticationInfo()
            {
                ApplicationUuid = TestExtensions.ClientUuid,
                PrivateKey      = TestExtensions.ClientPrivateKey,
                SignedTime      = testData.SignedTime
            });

            // Act
            var isAuthenticated = await authenticator.AuthenticateRequest(signedRequest);

            // Assert
            Assert.True(isAuthenticated);
        }
        public static async Task AuthenticateRequest_WithDefaultRequest_WhenV2Fails_FallBackToV1AndAuthenticate()
        {
            // Arrange
            var testData   = await "GET".FromResource();
            var mockLogger = new Mock <ILogger>();

            var authenticator = new MAuthAuthenticator(TestExtensions.ServerOptions, mockLogger.Object);
            var requestData   = testData.ToDefaultHttpRequestMessage();

            // Act
            var isAuthenticated = await authenticator.AuthenticateRequest(requestData);

            // Assert
            Assert.True(isAuthenticated);
            mockLogger.Verify(x => x.Log(
                                  LogLevel.Warning, It.IsAny <EventId>(),
                                  It.Is <FormattedLogValues>(v => v.ToString()
                                                             .Contains("Completed successful authentication attempt after fallback to V1")),
                                  It.IsAny <Exception>(), It.IsAny <Func <object, Exception, string> >()
                                  ));
        }
        public static async Task AuthenticateRequest_WithValidMWSRequest_WillAuthenticate(string method)
        {
            // Arrange
            var testData = await method.FromResource();

            var authenticator = new MAuthAuthenticator(TestExtensions.ServerOptions, NullLogger <MAuthAuthenticator> .Instance);
            var mAuthCore     = new MAuthCore();

            var signedRequest = await mAuthCore
                                .AddAuthenticationInfo(testData.ToHttpRequestMessage(MAuthVersion.MWS), new PrivateKeyAuthenticationInfo()
            {
                ApplicationUuid = testData.ApplicationUuid,
                PrivateKey      = TestExtensions.ClientPrivateKey,
                SignedTime      = testData.SignedTime
            });

            // Act
            var isAuthenticated = await authenticator.AuthenticateRequest(signedRequest);

            // Assert
            Assert.True(isAuthenticated);
        }
        public static async Task AuthenticateRequest_WithNumberOfAttempts_WillAuthenticate(
            MAuthServiceRetryPolicy policy)
        {
            // Arrange
            var testData = await "GET".FromResourceV2();

            var authenticator = new MAuthAuthenticator(TestExtensions.GetServerOptionsWithAttempts(
                                                           policy, shouldSucceedWithin: true), NullLogger <MAuthAuthenticator> .Instance);
            var mAuthCore = new MAuthCoreV2();

            var signedRequest = await mAuthCore
                                .AddAuthenticationInfo(testData.ToDefaultHttpRequestMessage(), new PrivateKeyAuthenticationInfo()
            {
                ApplicationUuid = testData.ApplicationUuid,
                PrivateKey      = TestExtensions.ClientPrivateKey,
                SignedTime      = testData.SignedTime
            });

            // Act
            var isAuthenticated = await authenticator.AuthenticateRequest(signedRequest);

            // Assert
            Assert.True(isAuthenticated);
        }
Ejemplo n.º 14
0
 /// <summary>
 /// Initializes a new instance of the <see cref="MAuthAuthenticatingHandler"/> class with the provided
 /// <see cref="MAuthWebApiOptions"/>.
 /// </summary>
 /// <param name="options">The options for this message handler.</param>
 public MAuthAuthenticatingHandler(MAuthWebApiOptions options)
 {
     this.options       = options;
     this.authenticator = this.SetupMAuthAuthenticator(options);
 }
 /// <summary>
 /// Initializes a new instance of the <see cref="MAuthAuthenticatingHandler"/> class with the provided
 /// <see cref="MAuthOptionsBase"/> and an inner <see cref="HttpMessageHandler"/>.
 /// </summary>
 /// <param name="options">The options for this message handler.</param>
 /// <param name="innerHandler">
 /// The inner handler which is responsible for processing the HTTP response messages.
 /// </param>
 public MAuthAuthenticatingHandler(MAuthWebApiOptions options, HttpMessageHandler innerHandler)
     : base(innerHandler)
 {
     this.options  = options;
     authenticator = new MAuthAuthenticator(options);
 }
 /// <summary>
 /// Initializes a new insance of the <see cref="MAuthAuthenticatingHandler"/> class with the provided
 /// <see cref="MAuthWebApiOptions"/>.
 /// </summary>
 /// <param name="options">The options for this message handler.</param>
 public MAuthAuthenticatingHandler(MAuthWebApiOptions options)
 {
     this.options  = options;
     authenticator = new MAuthAuthenticator(options);
 }
 public MAuthMiddleware(RequestDelegate next, MAuthMiddlewareOptions options)
 {
     this.next          = next;
     this.options       = options;
     this.authenticator = new MAuthAuthenticator(options);
 }
 public MAuthMiddleware(OwinMiddleware next, MAuthMiddlewareOptions options, ILogger owinLogger) : base(next)
 {
     this.options = options;
     Microsoft.Extensions.Logging.ILogger logger = new OwinLoggerWrapper(owinLogger);
     authenticator = new MAuthAuthenticator(options, logger);
 }
 public MAuthMiddleware(OwinMiddleware next, MAuthMiddlewareOptions options) : base(next)
 {
     this.options  = options;
     authenticator = new MAuthAuthenticator(options);
 }