/// <summary>
        /// Called when a request to the Token endpoint arrives with a "grant_type" of "password". This
        /// occurs when the user has provided name and password credentials directly into the client
        /// application's user interface, and the client application is using those to acquire an "access_token"
        /// and optional "refresh_token". If the web application supports the resource owner credentials
        /// grant type it must validate the context.Username and context.Password as appropriate. To issue an
        /// access token the context.Validated must be called with a new ticket containing the claims about the
        /// resource owner which should be associated with the access token. The application should take
        /// appropriate measures to ensure that the endpoint isn’t abused by malicious callers. The default
        /// behavior is to reject this grant type. See also http://tools.ietf.org/html/rfc6749#section-4.3.2
        /// </summary>
        public async Task GrantResourceOwnerCredentialsAsync(OAuthGrantResourceOwnerCredentialsContext context)
        {
            context.AssertNotNull("context");

            var allowedOrigin = context.OwinContext.Get <string>(Core.Constants.TokenAllowedOriginKey); // ?? Constants.DefaultAllowedOrigin;

            if (string.IsNullOrEmpty(allowedOrigin))
            {
                throw new UnauthorizedException("The allowed origin was not inferred from the client ID");
            }

            Helper.SetAccessControlAllowOrigin(context.OwinContext, allowedOrigin);

            var username = new Username(context.UserName);
            var password = new Password(context.Password);

            UserClaimsIdentity userClaimsIdentity;

            try
            {
                userClaimsIdentity = await this.getUserClaimsIdentity.HandleAsync(
                    new GetUserClaimsIdentityQuery(null, username, password, context.Options.AuthenticationType));
            }
            catch (BadRequestException t)
            {
                context.SetError("invalid_grant", t.Message);
                return;
            }

            await this.updateLastAccessTokenDate.HandleAsync(new UpdateLastAccessTokenDateCommand(
                                                                 userClaimsIdentity.UserId,
                                                                 DateTime.UtcNow,
                                                                 UpdateLastAccessTokenDateCommand.AccessTokenCreationType.SignIn));

            var props = this.CreateAuthenticationProperties(context.ClientId, userClaimsIdentity);

            var ticket = new AuthenticationTicket(userClaimsIdentity.ClaimsIdentity, props);

            context.Validated(ticket);
        }