/// <summary>
        /// Validates the client id
        /// </summary>
        /// <param name="context"></param>
        /// <returns></returns>
        public override Task ValidateClientAuthentication(OAuthValidateClientAuthenticationContext context)
        {

            string clientId;
            string clientSecret;
            // Gets the clientid and client secret from authenticate header
            if (!context.TryGetBasicCredentials(out clientId, out clientSecret))
            {
                // try to get form values
                context.TryGetFormCredentials(out clientId, out clientSecret);

            }

            // Validate clientid and clientsecret. You can omit validating client secret if none is provided in your request (as in sample client request above)
            var validClient = true;//!string.IsNullOrWhiteSpace(clientId);

            if (validClient)
            {
                // Need to make the client_id available for later security checks
                context.OwinContext.Set<string>("as:client_id", clientId);

                context.Validated();
            }
            else
            {
                context.Rejected();
            }

            return Task.FromResult(0);

        }
        public override Task ValidateClientAuthentication(OAuthValidateClientAuthenticationContext context)
        {
            try
            {
                var username = context.Parameters["username"];
                var password = context.Parameters["password"];

                if (identityService.AuthenticateUser(username, password))
                {
                    context.OwinContext.Set("securityApi:username", username);
                    context.Validated();
                }
                else
                {
                    context.SetError("Invalid credentials");
                    context.Rejected();
                }
            }
            catch(Exception exception)
            {
                context.SetError(exception.Message);
                context.Rejected();
            }
            return Task.FromResult(0);
        }
Ejemplo n.º 3
0
        public override Task ValidateClientAuthentication(OAuthValidateClientAuthenticationContext context)
        {
            try
            {
                var username = context.Parameters["username"];
                var password = context.Parameters["password"];

                if (username == password)
                {
                    context.OwinContext.Set("otf:username", username);
                    context.Validated();
                }
                else
                {
                    context.SetError("Invalid credentials");
                    context.Rejected();
                }
            }
            catch
            {
                context.SetError("Server error");
                context.Rejected();
            }
            return Task.FromResult(0);
        }
        /// <summary>
        /// 第一步:客户端认证
        /// </summary>
        /// <param name="context"></param>
        /// <returns></returns>
        public override async Task ValidateClientAuthentication(OAuthValidateClientAuthenticationContext context)
        {
            string grant_type = context.Parameters[Constant.GrantTypes.GrantType];

            if (grant_type == Constant.GrantTypes.Password)
            {
                string username = context.Parameters[Constant.GrantTypes.UserName];
                string password = context.Parameters[Constant.GrantTypes.Password];

                //TODO 调用登录逻辑
                bool loginFlag = true;
                if (loginFlag)
                {
                    //把当前用户存入上下文
                    context.OwinContext.Set<string>("loginuser", username);
                    bool flag = context.Validated();
                }
                else
                {
                    context.Rejected();
                    return;
                }
            }
            else if (grant_type == Constant.GrantTypes.RefreshToken)
            {
                bool flag = context.Validated();
            }
            else
            {
                context.Rejected();
                return;
            }
        }
Ejemplo n.º 5
0
        public override async Task ValidateClientAuthentication(OAuthValidateClientAuthenticationContext context)
        {
            try
            {
                string clientId, clientSecret;
                if (context.TryGetBasicCredentials(out clientId, out clientSecret) || context.TryGetFormCredentials(out clientId, out clientSecret))
                {
                    if (Validator.ValidateClient(clientId, clientSecret))
                    {
                        context.Validated();
                    }
                }
                else
                {
                    context.SetError("Invalid credentials");
                    context.Rejected();
                }
            }
            catch (Exception e)
            {
                context.SetError("Server error");
                context.Rejected();
            }

        }
        public override async Task ValidateClientAuthentication(OAuthValidateClientAuthenticationContext context)
        {
            //context.Validated();
            //return;

            string clientId = string.Empty;
            string clientSecret = string.Empty;

            if (!context.TryGetBasicCredentials(out clientId, out clientSecret))
            {
                context.TryGetFormCredentials(out clientId, out clientSecret);
            }

            if (context.ClientId == null)
            {
                context.SetError("invalid_client", "Client credentials could not be retrieved through the Authorization header.");
                context.Rejected();

                return;
            }

            try
            {
                if (clientId == "MyApp" && clientSecret == "MySecret")
                {
                    ApplicationClient client = new ApplicationClient();

                    client.Id = "MyApp";
                    client.AllowedGrant = OAuthGrant.ResourceOwner;
                    client.ClientSecretHash = new PasswordHasher().HashPassword("MySecret");
                    client.Name = "My App";
                    client.CreatedOn = DateTimeOffset.UtcNow;

                    context.OwinContext.Set<ApplicationClient>("oauth:client", client);
                    context.Validated(clientId);
                }
                else
                {
                    // Client could not be validated.
                    context.SetError("invalid_client", "Client credentials are invalid.");
                    context.Rejected();
                }
            }
            catch (Exception ex)
            {
                string errorMessage = ex.Message;
                context.SetError("server_error");
                context.Rejected();
            }

            return;
        }
        public override async Task ValidateClientAuthentication(
            OAuthValidateClientAuthenticationContext context)
        {
            string clientId;
            string clientSecret;

            if (context.TryGetBasicCredentials(out clientId, out clientSecret))
            {
                UserManager<IdentityUser> userManager =
                    context.OwinContext.GetUserManager<UserManager<IdentityUser>>();
                OAuthDbContext dbContext =
                    context.OwinContext.Get<OAuthDbContext>();

                try
                {
                    Client client = await dbContext
                        .Clients
                        .FirstOrDefaultAsync(clientEntity => clientEntity.Id == clientId);

                    if (client != null &&
                        userManager.PasswordHasher.VerifyHashedPassword(
                            client.ClientSecretHash, clientSecret) == PasswordVerificationResult.Success)
                    {
                        // Client has been verified.
                        context.OwinContext.Set<Client>("oauth:client", client);
                        context.Validated(clientId);
                    }
                    else
                    {
                        // Client could not be validated.
                        context.SetError("invalid_client", "Client credentials are invalid.");
                        context.Rejected();
                    }
                }
                catch
                {
                    // Could not get the client through the IClientManager implementation.
                    context.SetError("server_error");
                    context.Rejected();
                }
            }
            else
            {
                // The client credentials could not be retrieved.
                context.SetError(
                    "invalid_client",
                    "Client credentials could not be retrieved through the Authorization header.");

                context.Rejected();
            }
        }
        public override async Task ValidateClientAuthentication(
        OAuthValidateClientAuthenticationContext context)
        {
            string clientId;
            string clientSecret;
            context.OwinContext.Response.Headers["Access-Control-Allow-Origin"] = "*";
            if (!context.TryGetBasicCredentials(out clientId, out clientSecret))
            {
                context.TryGetFormCredentials(out clientId, out clientSecret);
            }
            if (clientId != null)
            {
                
                UserManager dbContext =        context.OwinContext.Get<UserManager>();

                try
                {

                    
                    var client = await dbContext.FindAsync(clientId, clientSecret);

                    if (client != null)
                    {
                        // Client has been verified.
                        
                        client.AuthGrant = OAuthGrant.ResourceOwner;
                        context.OwinContext.Set<User>("oauth:client", client);
                        context.Validated(clientId);
                    }
                    else
                    {
                        // Client could not be validated.
                        
                        context.Rejected();
                        context.SetError("invalid_client Client credentials are invalid.");
                    }
                }
                catch
                {
                    // Could not get the client through the IClientManager implementation.
                    
                    context.Rejected();
                    context.SetError("server_error");
                }
            }
            else
            {
                //for my implementation if no client id is provided use only the user/pass 
                context.Validated(clientId);
            }
        }
        public override async Task ValidateClientAuthentication(OAuthValidateClientAuthenticationContext context) {
            var clientId = context.Parameters["client_id"];
            if (!string.IsNullOrWhiteSpace(clientId)) {
                var grantType = context.Parameters["grant_type"];
                var clientSecret = context.Parameters["client_secret"];

                switch (grantType) {
                    case GrantType.Password:
                    case GrantType.ClientCredentials:
                        {
                            /* web application */
                            if (clientSecret == Application.WebApplication.ConsumerSecret) {
                                context.Validated(clientId);
                                return;
                            }

                            /*  mobile application */
                            if (clientSecret == Application.MobileApplication.ConsumerSecret) {
                                context.Validated(clientId);
                                return;
                            }
                        }
                        break;
                    case GrantType.RefreshToken:
                    default:
                        context.Validated(clientId);
                        return;
                }
            }

            context.Rejected();
        }
        public override Task ValidateClientAuthentication(OAuthValidateClientAuthenticationContext context)
        {
            // validate client credentials
            // should be stored securely (salted, hashed, iterated)
            
            string id, secret;
            if (context.TryGetBasicCredentials(out id, out secret))
            {
                var client = _dbContext
                    .ApiClients
                    .AsEnumerable()
                    .SingleOrDefault(c => c.Id.ToString() == id && c.IsBlacklisted == false);

                if (client != null)
                {
                    // need to make the client_id available for later security checks
                    context.OwinContext.Set("as:client_id", client.Id.ToString());
                    //context.OwinContext.Set("as:client_name", client.Name);
                    context.Validated();
                    return Task.FromResult<object>(null);
                }

            }
            context.Rejected();
            return Task.FromResult<object>(null);
        }
        /*We may have additional clients we want to validate again, however, at the moment,
         we expect to serve only 1 client, otherwise we'll need to validate a client api key here.*/
        public override async Task ValidateClientAuthentication(OAuthValidateClientAuthenticationContext context)
        {
            string clientId;
            string clientSecret; //The client secret is ignored as we can't share secrets on web clients
            if (!context.TryGetFormCredentials(out clientId, out clientSecret))
            {
                context.Rejected();
                context.SetError("invalid_client", "The client is not available.");
                return;
            }

            var client = await GetClient(clientId);
            if (client == null || !client.IsActive)
            {
                context.Rejected();
                context.SetError("invalid_client", "The client is not available.");
                return;
            }

            context.Validated(client.ClientId);
        }
        public override async Task ValidateClientAuthentication(OAuthValidateClientAuthenticationContext context)
        {
            // appelé pour valider que le client id et client secret sont valides
            string clientId;
            string clientSecret;
            if (context.TryGetFormCredentials(out clientId, out clientSecret))
            {
                if (clientId == "win8client" && clientSecret == "oauthcadeboite")
                {
                    context.Validated(clientId);
                    return;
                }
            }

            context.Rejected();

        }
        //Validate the client id and client secret
        public override async Task ValidateClientAuthentication(OAuthValidateClientAuthenticationContext context)
        {
            bool validated = false;
            string clientId;
            string clientSecret;
            
            //Try to get the client id and secret from Basic Auth Header
            if(context.TryGetBasicCredentials(out clientId, out clientSecret))
            {
                
                ApplicationUserManager userManager = context.OwinContext.GetUserManager<ApplicationUserManager>();
                ApplicationDbContext dbContext = context.OwinContext.Get<ApplicationDbContext>();
                
                if(!String.IsNullOrEmpty(clientId)){
                    OAuthClient oauthClient = await dbContext.OAuthClients.FirstOrDefaultAsync(oac => oac.ClientId.ToString() == clientId);
                    if (oauthClient != null && oauthClient.Enabled && userManager.PasswordHasher.VerifyHashedPassword(oauthClient.ClientSecretHash, clientSecret)==PasswordVerificationResult.Success)
                    {
                        context.OwinContext.Set<OAuthClient>(OwinClientKey, oauthClient);
                        context.Validated(clientId);
                        validated = true;
                    }
                }
            }

            if (!validated)
            {
                context.SetError("Authentication Failed");
                context.Rejected();
            }

            //return Task.FromResult<object>(null);
        }
Ejemplo n.º 14
0
 private void Refuse(OAuthValidateClientAuthenticationContext context)
 {
     context.SetError("Invalid credentials");
         context.Rejected();
 }
        /// <summary>
        /// Called to validate that the origin of the request is a registered "client_id", and that the correct credentials for that client are
        /// present on the request. If the web application accepts Basic authentication credentials,
        /// context.TryGetBasicCredentials(out clientId, out clientSecret) may be called to acquire those values if present in the request header. If the web
        /// application accepts "client_id" and "client_secret" as form encoded POST parameters,
        /// context.TryGetFormCredentials(out clientId, out clientSecret) may be called to acquire those values if present in the request body.
        /// If context.Validated is not called the request will not proceed further.
        /// </summary>
        /// <param name="context">The context of the event carries information in and results out.</param>
        /// <returns>Task to enable asynchronous execution</returns>
        public override async Task ValidateClientAuthentication(OAuthValidateClientAuthenticationContext context)
        {
            this.options.Logger.DebugFormat("Validating client id and secret");

            string clientId;
            string clientSecret;

            // Validate that redirect uri is specified
            // 'redirect_uri' must be specified for all calls that are not 'client_credentials' grants.
            if (context.Parameters["redirect_uri"] == null && context.Parameters["grant_type"] != "client_credentials")
            {
                context.SetError("invalid_request");

                this.options.Logger.ErrorFormat("Redirect URI was not specified, the token request is not valid");

                return;
            }

            if (context.TryGetBasicCredentials(out clientId, out clientSecret)
                || context.TryGetFormCredentials(out clientId, out clientSecret))
            {
                // Only proceed if client id and client secret is provided
                if (string.IsNullOrEmpty(clientId) || string.IsNullOrEmpty(clientSecret))
                {
                    this.options.Logger.WarnFormat("Client id ({0}) or client secret ({1}) is invalid", clientId, clientSecret);

                    return;
                }

                this.options.Logger.DebugFormat("Authenticating client '{0}'", clientId);

                var client = await this.options.ClientManager.AuthenticateClientCredentialsAsync(clientId, clientSecret);

                if (!client.Identity.IsAuthenticated)
                {
                    context.Rejected();

                    this.options.Logger.WarnFormat("Client '{0}' was not authenticated because the supplied secret did not match", clientId);

                    return;
                }
            }
            else
            {
                context.Rejected();

                this.options.Logger.WarnFormat("Client '{0}' was not authenticated because the provider could not retrieve the client id and client secret from the Authorization header or Form parameters", clientId);

                return;
            }

            context.OwinContext.GetOAuthContext().ClientId = context.ClientId;
            context.OwinContext.GetOAuthContext().RedirectUri = context.Parameters["redirect_uri"];
            context.OwinContext.GetOAuthContext().Scope = context.Parameters["scope"] != null ? context.Parameters["scope"].Split(' ') : null;

            this.options.Logger.DebugFormat("Client '{0}' was successfully authenticated", clientId);

            context.Validated(clientId);
        }
Ejemplo n.º 16
0
        public override async Task ValidateClientAuthentication(OAuthValidateClientAuthenticationContext context)
        {

            try
            {
                string clientId, clientSecret;
                if (!context.TryGetBasicCredentials(out clientId, out clientSecret))
                {
                    context.TryGetFormCredentials(out clientId, out clientSecret);
                }

                App app = null;
                bool exceptionThrown = false;
                try
                {
                    

                   
                        app = await _dbContext.Apps.FirstOrDefaultAsync(c => c.ClientId == clientId && c.ClientSecret == clientSecret);
                    
                    
                }
                catch (Exception exception)
                {
                    exceptionThrown = true;
                }

                if (exceptionThrown)
                {
                    context.Rejected();
                }

                else if (app == null)
                {
                    context.Rejected();
                }
                else if (!app.IsOAuth)
                {
                    context.Rejected();
                }
                else if (!app.IsActive)
                {
                    context.Rejected();
                }
                else
                {
                    // var scopes = context.Parameters["scope"]; //todo: skip if SSO



                    context.OwinContext.Set("sidekick.client.name", app.Username);
                    context.OwinContext.Set("sidekick.client.appId", app.Id);
                    context.OwinContext.Set("sidekick.client.appName", app.Name);
                    context.OwinContext.Set("sidekick.client.meta", app.Meta);
                    context.OwinContext.Set("sidekick.client.istrusted", app.IsTrusted);
                    context.OwinContext.Set("sidekick.client.tokenexpiry", app.AccessTokenExpiry);

                    var scopeList = new List<string>();

                    foreach (var scope in app.AppScopes)
                    {
                        scopeList.Add(scope.OAuthScope.Name);
                    }

                    context.OwinContext.Set("sidekick.client.scopes", scopeList);

                    context.Validated();
                }
            }
            catch (Exception)
            {

                context.Rejected();
            }
        }