public void ShouldNotAuthenticateWhenMissingHeaders()
        {
            IPrincipal principal = null;

            var handler = new BasicAuthenticationHandler(new FakeChannel(), new UserValidation((u, p) => true), "realm");
            var authenticated = handler.Authenticate(new HttpRequestMessage(), new HttpResponseMessage(), out principal);

            Assert.IsFalse(authenticated, "The user must not be authenticated");
        }
Exemplo n.º 2
0
        public Note[] Get([FromQuery] string containing)
        {
            var authorizationHeader = Request.Headers["Authorization"];
            var user = BasicAuthenticationHandler.GetUserFrom(authorizationHeader);

            return(_database.Notes
                   .FromSqlRaw($"SELECT * FROM Notes WHERE Author='{user.Username}' AND Content LIKE '%{containing}%' ORDER BY Id")
                   .ToArray());
        }
        public void ShouldChallengeWhenMissingHeaders()
        {
            IPrincipal principal = null;

            var response = new HttpResponseMessage();

            var handler = new BasicAuthenticationHandler(new FakeChannel(), new UserValidation((u, p) => true), "realm");
            var authenticated = handler.Authenticate(new HttpRequestMessage(), response, out principal);

            Assert.AreEqual(HttpStatusCode.Unauthorized, response.StatusCode);
            Assert.IsTrue(response.Headers.WwwAuthenticate.Any(h => h.Scheme == BasicAuthenticationScheme && h.Parameter.Contains("realm")),
                "A WWW must be present in the response");
        }
         public BasicAuthenticationTests()
         {
             _options = new Mock<IOptionsMonitor<AuthenticationSchemeOptions>>();
 
             var logger = new Mock<ILogger<BasicAuthenticationHandler>>();
             _loggerFactory = new Mock<ILoggerFactory>();
             _loggerFactory.Setup(x => x.CreateLogger(It.IsAny<String>())).Returns(logger.Object);
 
             _encoder = new Mock<UrlEncoder>();
             _clock = new Mock<ISystemClock>();
             _principalProvider = new Mock<IProvidePrincipal>();
 
             _handler = new BasicAuthenticationHandler(_options.Object, _loggerFactory.Object, _encoder.Object, _clock.Object, _principalProvider.Object);
         }
        public void ShouldNotAuthenticateWithInvalidEncodedUsernameAndPassword()
        {
            IPrincipal principal = null;

            var request = new HttpRequestMessage();
            var response = new HttpResponseMessage();

            var credentials = "some credentials";

            request.Headers.Authorization = new Headers.AuthenticationHeaderValue(BasicAuthenticationScheme, credentials);

            var handler = new BasicAuthenticationHandler(new FakeChannel(), new UserValidation((u, p) => true), "realm");
            var authenticated = handler.Authenticate(request, response, out principal);

            Assert.IsFalse(authenticated, "The user should have not been authenticated");
        }
Exemplo n.º 6
0
        public ActionResult <Note> Post([FromBody] CreateNote createNote)
        {
            var authorizationHeader = Request.Headers["Authorization"];
            var user = BasicAuthenticationHandler.GetUserFrom(authorizationHeader);

            var note = new Note
            {
                Author  = user.Username,
                Content = createNote.Content,
            };

            _database.Add(note);
            _database.SaveChanges();

            return(CreatedAtRoute("GetNoteById", new { noteId = note.Id }, note));
        }
Exemplo n.º 7
0
        public BasicAuthenticationHandlerTests()
        {
            _options = new Mock <IOptionsMonitor <AuthenticationSchemeOptions> >();
            _options.Setup(x => x.Get("Basic")).Returns(new AuthenticationSchemeOptions());

            var logger = new Mock <ILogger <BasicAuthenticationHandler> >();

            _loggerFactory = new Mock <ILoggerFactory>();
            _loggerFactory.Setup(x => x.CreateLogger(It.IsAny <string>())).Returns(logger.Object);

            _encoder = new Mock <UrlEncoder>();
            _clock   = new Mock <ISystemClock>();

            _userService = new Mock <UserService>();

            _handler = new BasicAuthenticationHandler(_options.Object, _loggerFactory.Object, _encoder.Object, _clock.Object, _userService.Object);
        }
        public BasicAuthenticationHandlerFixture()
        {
            var options = new Mock <IOptionsMonitor <AuthenticationSchemeOptions> >();

            options.Setup(x => x.Get(BasicAuthenticationHandler.SchemeName)).Returns(new AuthenticationSchemeOptions());

            var logger        = new Mock <ILogger <BasicAuthenticationHandler> >();
            var loggerFactory = new Mock <ILoggerFactory>();

            loggerFactory.Setup(x => x.CreateLogger(It.IsAny <string>())).Returns(logger.Object);

            var encoder = new Mock <UrlEncoder>();
            var clock   = new Mock <ISystemClock>();

            _dataStore = new Mock <IDataStore>();

            _handler = new BasicAuthenticationHandler(options.Object, loggerFactory.Object, encoder.Object, clock.Object, _dataStore.Object);
        }
        public void ShouldCallAuthenticateWithProvidedUserAndPassword()
        {
            IPrincipal principal = null;

            var request = new HttpRequestMessage();
            var response = new HttpResponseMessage();

            var credentials = EncodeCredentials("foo", "pass");

            request.Headers.Authorization = new Headers.AuthenticationHeaderValue(BasicAuthenticationScheme, credentials);

            var handler = new BasicAuthenticationHandler(new FakeChannel(),
                new UserValidation((u, p) => u == "foo" && p == "pass"),
                "realm");
            var authenticated = handler.Authenticate(request, response, out principal);

            Assert.IsTrue(authenticated, "The user should have been authenticated");
        }
        public void BasicAuthenticationHandlerTests_Setup()
        {
            this._options = new Mock <IOptionsMonitor <AuthenticationSchemeOptions> >();
            this._logger  = new Mock <ILoggerFactory>();
            this._encoder = new Mock <UrlEncoder>();
            this._clock   = new Mock <ISystemClock>();
            this._authenticationService = new Mock <IApiAuthenicationService>();

            var logger = new Mock <ILogger <BasicAuthenticationHandler> >();

            this._logger.Setup(x => x.CreateLogger(It.IsAny <string>())).Returns(logger.Object);

            this._authenticationHandler = new BasicAuthenticationHandler(this._options.Object,
                                                                         this._logger.Object,
                                                                         this._encoder.Object,
                                                                         this._clock.Object,
                                                                         this._authenticationService.Object);
        }
Exemplo n.º 11
0
        public async Task <IActionResult> Register([FromBody] UserRegistrationInfo registrationInfo, CancellationToken cancellationToken)
        {
            if (registrationInfo == null)
            {
                return(BadRequest());
            }
            var  passwordHash = BasicAuthenticationHandler.HashPassword(registrationInfo.Password);
            var  userInfo     = new UserInfo(registrationInfo.Login, passwordHash);
            User user         = null;

            try
            {
                user = await users.CreateAsync(userInfo, cancellationToken);
            }
            catch (UserDuplicationException)
            {
                return(Conflict());
            }

            return(Ok(user));
        }
        /// <summary>
        /// Not all WWW-Authenticate basic auth responses are handled by the NSUrlSessionHandler, such as those
        /// from VSTS NuGet package sources, so an Authorization header is added to the request and re-sent
        /// if basic auth credentials can be found.
        /// </summary>
        protected override async Task <HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
        {
            bool retry = false;

            while (true)
            {
                var response = await base.SendAsync(request, cancellationToken).ConfigureAwait(false);

                if (retry || response.StatusCode != HttpStatusCode.Unauthorized)
                {
                    return(response);
                }

                if (!BasicAuthenticationHandler.Authenticate(request, response, Credentials))
                {
                    return(response);
                }

                retry = true;
            }
        }
 public AccountsController(BasicAuthenticationHandler authenticationHandler,
                           IBasicAuthenticationService authenticationService)
 {
     _authenticationService = authenticationService;
     _authenticationHandler = authenticationHandler;
 }
        public void ShouldNotSetPrincipalWhenMissingHeaders()
        {
            IPrincipal principal = null;

            var handler = new BasicAuthenticationHandler(new FakeChannel(), new UserValidation((u, p) => true), "realm");
            var authenticated = handler.Authenticate(new HttpRequestMessage(), new HttpResponseMessage(), out principal);

            Assert.IsNull(principal, "The principal should not be set");
        }
 public void ShouldReturnScheme()
 {
     var handler = new BasicAuthenticationHandler(new FakeChannel(), new UserValidation((u, p) => true), "realm");
     Assert.AreEqual(BasicAuthenticationScheme, handler.Scheme);
 }
        public void ShouldSetPrincipalForAuthenticatedUsers()
        {
            IPrincipal principal = null;

            var request = new HttpRequestMessage();
            var response = new HttpResponseMessage();

            var credentials = EncodeCredentials("foo", "pass");

            request.Headers.Authorization = new Headers.AuthenticationHeaderValue(BasicAuthenticationScheme, credentials);

            var handler = new BasicAuthenticationHandler(new FakeChannel(), new UserValidation((u, p) => u == "foo" && p == "pass"), "realm");
            var authenticated = handler.Authenticate(request, response, out principal);

            Assert.AreEqual("foo", principal.Identity.Name, "The principal should have been set with the user name");
        }
 public void ShouldThrowWithNullRealm()
 {
     var handler = new BasicAuthenticationHandler(new FakeChannel(), new UserValidation((u, p) => true), null);
 }
 public void ShouldThrowWithNullValidationFunction()
 {
     var handler = new BasicAuthenticationHandler(new FakeChannel(), null, "realm");
 }