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

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

            if (context.ClientId == null)
            {
                context.SetError("invalid_clientId", "client_Id is not set");
                return Task.FromResult<object>(null);
            }

            var resource = ResourceStore.FindResource(context.ClientId);

            if (resource == null)
            {
                context.SetError("invalid_clientId", string.Format("Invalid client_id '{0}'", context.ClientId));
                return Task.FromResult<object>(null);
            }

            context.Validated();
            return Task.FromResult<object>(null);
        }
        public override Task ValidateClientAuthentication(OAuthValidateClientAuthenticationContext context)
        {
            string clientId = string.Empty;
            string clientSecret = string.Empty;
            Client client = null;

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

            if (context.ClientId == null)
            {
                //Remove the comments from the below line context.SetError, and invalidate context 
                //if you want to force sending clientId/secrects once obtain access tokens. 
                context.Validated();
                //context.SetError("invalid_clientId", "ClientId should be sent.");
                return Task.FromResult<object>(null);
            }

            using (AuthRepository _repo = new AuthRepository())
            {
                client = _repo.FindClient(context.ClientId);
            }

            if (client == null)
            {
                context.SetError("invalid_clientId", string.Format("Client '{0}' is not registered in the system.", context.ClientId));
                return Task.FromResult<object>(null);
            }

            if (client.ApplicationType == ApplicationTypes.NativeConfidential)
            {
                if (string.IsNullOrWhiteSpace(clientSecret))
                {
                    context.SetError("invalid_clientId", "Client secret should be sent.");
                    return Task.FromResult<object>(null);
                }
                else
                {
                    if (client.Secret != HashHelper.GetHash(clientSecret))
                    {
                        context.SetError("invalid_clientId", "Client secret is invalid.");
                        return Task.FromResult<object>(null);
                    }
                }
            }

            if (!client.Active)
            {
                context.SetError("invalid_clientId", "Client is inactive.");
                return Task.FromResult<object>(null);
            }

            context.OwinContext.Set<string>("as:clientAllowedOrigin", client.AllowedOrigin);
            context.OwinContext.Set<string>("as:clientRefreshTokenLifeTime", client.RefreshTokenLifeTime.ToString());

            context.Validated();
            return Task.FromResult<object>(null);
        }
        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);
        }
        public override Task ValidateClientAuthentication(OAuthValidateClientAuthenticationContext context)
        {
            string AuthorizeSecretKey = context.Parameters["authorizeSecretKey"];
            if (AuthorizeSecretKey != AValues.AuthorizeSecretKey)
            {
                context.SetError("invalid_clientId", string.Format("SecretKey '{0}' is not true.", AuthorizeSecretKey));
                return Task.FromResult<object>(null);
            }

            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.Validated();
                return Task.FromResult<object>(null);
            }

            UserViewModel user = RedisHelp.GetLoginUserCache(int.Parse(context.ClientId));
            if (user == null)
            {
                context.SetError("invalid_clientId", string.Format("Client '{0}' is not registered in the system.", context.ClientId));
                return Task.FromResult<object>(null);
            }

            context.Validated();
            return Task.FromResult<object>(null);
        }
Ejemplo n.º 5
0
        /// <summary>
        /// responsible for validating if the Resource server (audience) is already registered in our Authorization server by reading the client_id value from the request
        /// </summary>
        /// <param name="context"></param>
        /// <returns></returns>
        public override Task ValidateClientAuthentication(OAuthValidateClientAuthenticationContext context)
        {
            string clientId;
            string clientSecret;

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

            if (context.ClientId == null && String.IsNullOrWhiteSpace(clientId))
            {
                context.SetError("invalid_clientId", "client_Id is not set");
            }
            else if (!context.HasError)
            {
                var audience = AudiencesStore.Instance.FindAudience(context.ClientId);
                if (audience == null)
                {
                  context.SetError("invalid_clientId", String.Format("Client '{0}' is not registered in the system.", context.ClientId));
                }
                else
                {
                    context.OwinContext.Set("as:clientId", clientId);
                    context.OwinContext.Set("as:clientAllowedOrigin", audience.AllowedOrigin);
                    context.Validated();
                }
            }
            return Task.FromResult<object>(null);
        }
Ejemplo n.º 6
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();
            }

        }
Ejemplo n.º 7
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);
        }
        public override Task ValidateClientAuthentication(OAuthValidateClientAuthenticationContext context)
        {
            string clientId;
            string clientSecret;

            //first try to get the client details from the Authorization Basic header
            if (!context.TryGetBasicCredentials(out clientId, out clientSecret))
            {
                //no details in the Authorization Header so try to find matching post values
                context.TryGetFormCredentials(out clientId, out clientSecret);
            }

            if (string.IsNullOrWhiteSpace(clientId) || string.IsNullOrWhiteSpace(clientSecret))
            {
                context.SetError("client_not_authorized", "invalid client details");
                return Task.FromResult<object>(null);
            }

            var dataLayer = new RepoManager(new DataLayerDapper()).DataLayer;
            var audienceDto = dataLayer.GetAudience(clientId);

            if (audienceDto == null || !clientSecret.Equals(audienceDto.Secret))
            {
                context.SetError("unauthorized_client", "unauthorized client");
                return Task.FromResult<object>(null);
            }

            context.Validated();
            return Task.FromResult<object>(null);
        }
        public override Task ValidateClientAuthentication(OAuthValidateClientAuthenticationContext context)
        {
            string clientId = string.Empty;
            string clientSecret = string.Empty;
            string symmetricKeyAsBase64 = string.Empty;

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

            if (context.ClientId == null)
            {
                context.SetError("invalid_clientId", "client_Id is not set");
                return Task.FromResult<object>(null);
            }

            var audience = AudiencesStore.FindAudience(context.ClientId);

            if (audience == null)
            {
                context.SetError("invalid_clientId", string.Format("Invalid client_id '{0}'", context.ClientId));
                return Task.FromResult<object>(null);
            }

            context.Validated();
            return Task.FromResult<object>(null);
        }
Ejemplo n.º 10
0
        public override Task ValidateClientAuthentication(OAuthValidateClientAuthenticationContext ctx)
        {
            string clientId = string.Empty;
            string clientSecret = string.Empty;
            Client client = null;

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

            if(ctx.ClientId == null)
            {
                ctx.SetError("No clientId specified ! ");
                return Task.FromResult<object>(null);
            }

            using(AuthRepository _repo = new AuthRepository())
            {
                client = _repo.FindClient(clientId);
            }

            if(client == null)
            {
                ctx.SetError("clientId not found !");
                return Task.FromResult<object>(null);
            }

            if (client.ApplicationType == ApplicationTypes.Native)
            {
                if (string.IsNullOrWhiteSpace(clientSecret))
                {
                    ctx.SetError("invalid_clientId", "Client secret should be sent.");
                    return Task.FromResult<object>(null);
                }
                else
                {
                    if (client.Secret != GetHash(clientSecret)) 
                    {
                        ctx.SetError("invalid_clientId", "Client secret is invalid.");
                        return Task.FromResult<object>(null);
                    }
                }
            }

            if (!client.Active)
            {
                ctx.SetError("invalid_clientId", "Client is inactive.");
                return Task.FromResult<object>(null);
            }

            ctx.OwinContext.Set<string>("as:clientAllowedOrigin", client.AllowedOrigin);
            ctx.OwinContext.Set<string>("as:clientRefreshTokenLifeTime", client.RefreshTokenLifeTime.ToString());

            ctx.Validated();
            return Task.FromResult<object>(null);


        }
        /// <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 Task ValidateClientAuthentication(OAuthValidateClientAuthenticationContext context)
        {

            string clientId = string.Empty;
            string clientSecret = string.Empty;
            AuthorizedClient authorizedClient = null;

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

            if (context.ClientId == null)
            {
                context.SetError("invalid_clientId", "ClientId should be sent.");
                return Task.FromResult<object>(null);
            }

            using (var repo = new AuthRepository())
                authorizedClient = repo.FindAuthorizedClient(context.ClientId);

            if (authorizedClient == null)
            {
                context.SetError("invalid_clientId", string.Format("Client '{0}' is not registered in the system.", context.ClientId));
                return Task.FromResult<object>(null);
            }

            if (authorizedClient.ApplicationType == ApplicationTypes.NativeConfidential)
            {
                if (string.IsNullOrWhiteSpace(clientSecret))
                {
                    context.SetError("invalid_clientId", "Client secret should be sent.");
                    return Task.FromResult<object>(null);
                }
                else
                {
                    if (authorizedClient.Secret != HashHelper.GetHash(clientSecret))
                    {
                        context.SetError("invalid_clientId", "Client secret is invalid.");
                        return Task.FromResult<object>(null);
                    }
                }
            }

            if (!authorizedClient.Active)
            {
                context.SetError("invalid_clientId", "Client is inactive.");
                return Task.FromResult<object>(null);
            }

            context.OwinContext.Set<string>("as:clientAllowedOrigin", authorizedClient.AllowedOrigin);
            context.OwinContext.Set<string>("as:clientRefreshTokenLifeTime", authorizedClient.RefreshTokenLifeTime.ToString());

            context.Validated();
            return Task.FromResult<object>(null);
        }
        public override Task ValidateClientAuthentication(OAuthValidateClientAuthenticationContext context)
        {
            string clientId;
            string clientSecret;
            OAuthClient client = null;

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

            if (context.ClientId == null)
            {
                context.SetError("invalid_clientId", "ClientId should be sent.");
                return Task.FromResult<object>(null);
            }

            var clientService = mobSocialEngine.ActiveEngine.Resolve<IClientService>();
            client = clientService.FirstOrDefault(x => x.Guid == clientId);

            if (client == null)
            {
                context.SetError("invalid_clientId", $"Client '{context.ClientId}' is not registered in the system.");
                return Task.FromResult<object>(null);
            }
            //native applications should also pass client secret
            if (client.ApplicationType == ApplicationType.NativeConfidential || client.ApplicationType == ApplicationType.NativeFullControl)
            {
                if (string.IsNullOrWhiteSpace(clientSecret))
                {
                    context.SetError("invalid_clientId", "Client secret should be sent.");
                    return Task.FromResult<object>(null);
                }
                else
                {
                    if (client.Secret != Helper.GetHash(clientSecret))
                    {
                        context.SetError("invalid_clientId", "Client secret is invalid.");
                        return Task.FromResult<object>(null);
                    }
                }
            }

            if (!client.Active)
            {
                context.SetError("invalid_clientId", "Client is inactive.");
                return Task.FromResult<object>(null);
            }

            context.OwinContext.Set<string>("as:clientAllowedOrigin", client.AllowedOrigin);
            context.OwinContext.Set<string>("as:clientRefreshTokenLifeTime", client.RefreshTokenLifeTime.ToString());

            context.Validated();
            return Task.FromResult<object>(null);
        }
        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)
        {
            string clientId, clientSecret;
            if (!context.TryGetBasicCredentials(out clientId, out clientSecret))
            {
                context.TryGetFormCredentials(out clientId, out clientSecret);
            }

            if (clientId == null)
            {
                context.SetError("client_id_not_found", "ClientID should be sent.");
                return;
            }

            var clientApplication = await _userRepository.FindClientAsync(clientId);
            if (clientApplication == null)
            {
                context.SetError("invalid_client_id", string.Format("Client '{0}' is not registered in the system.", clientId));
                return;
            }

            // Only native apps are supposed to contain a secret
            // Javascript apps cannot store the secret safely anyway
            if (clientApplication.ApplicationType == ApplicationType.NativeConfidential)
            {
                if (string.IsNullOrWhiteSpace(clientSecret))
                {
                    context.SetError("client_secret_not_found", "Client secret should be sent.");
                    return;
                }

                if (clientApplication.Secret != AuthorizationHelpers.GetHash(clientSecret))
                {
                    context.SetError("invalid_client_secret", "Client secret is invalid");
                    return;
                }
            }

            if (!clientApplication.IsActive)
            {
                context.SetError("client_inactive", "Client is inactive");
                return;
            }

            context.OwinContext.Set("as:clientAllowedOrigin", clientApplication.AllowedOrigin);
            context.OwinContext.Set("as:clientRefreshTokenLifetime", clientApplication.RefreshTokenLifeTime.ToString());
            context.Validated();
        }
 /// <summary>
 /// 验证Client Credentials[client_id与client_secret]
 /// </summary>
 /// <param name="context"></param>
 /// <returns></returns>
 public override async Task ValidateClientAuthentication(OAuthValidateClientAuthenticationContext context)
 {
     //http://localhost:48339/token
     //grant_type=client_credentials&client_id=irving&client_secret=123456&scope=user order
     /*
     grant_type     授与方式(固定为 “client_credentials”)
     client_id 	   分配的调用oauth的应用端ID
     client_secret  分配的调用oaut的应用端Secret
     scope 	       授权权限。以空格分隔的权限列表,若不传递此参数,代表请求用户的默认权限
     */
     //validate client credentials should be stored securely (salted, hashed, iterated)
     string clientId;
     string clientSecret;
     //context.TryGetBasicCredentials(out clientId, out clientSecret);
     context.TryGetFormCredentials(out clientId, out clientSecret);
     //验证用户名密码
     var clientValid = await _clientAuthorizationService.ValidateClientAuthorizationSecretAsync(clientId, clientSecret);
     if (!clientValid)
     {
         //Flurl 404 问题
         //context.Response.StatusCode = Convert.ToInt32(HttpStatusCode.OK);
         //context.Rejected();
         context.SetError(AbpConstants.InvalidClient, AbpConstants.InvalidClientErrorDescription);
         return;
     }
     //need to make the client_id available for later security checks
     context.OwinContext.Set<string>("as:client_id", clientId);
     context.Validated(clientId);
 }
        public override async Task ValidateClientAuthentication(OAuthValidateClientAuthenticationContext context)
        {
            string clientId;
            string clientSecret;

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

            if (string.IsNullOrWhiteSpace(clientId))
            {
                context.SetError("invalid_clientId", "client_id is not set.");
                await Task.FromResult<object>(null);
                return;
            }
            //TODO: get authClient (application) from db in future
            var authClient = new AuthClientService().Get(clientId);

            // auth client is null
            if (authClient == null)
            {
                context.SetError("invalid_clientId", "client_id is not valid.");
                await Task.FromResult<object>(null);
                return;
            }

            // authclient is enabled
            if (!authClient.Enabled)
            {
                context.SetError("invalid_clientId", "client_id is not valid.");
                await Task.FromResult<object>(null);
                return;
            }

            // make sure secret isn't null or empty
            if (string.IsNullOrWhiteSpace(clientSecret))
            {
                context.SetError("invalid_clientId", "Client secret should be sent.");
                await Task.FromResult<object>(null);
                return;
            }

            // make sure secret matches
            if (clientSecret != authClient.Base64Secret)
            {
                context.SetError("invalid_clientId", "Client secret is invalid.");
                await Task.FromResult<object>(null);
                return;
            }

            context.OwinContext.Set("authClient", authClient);

            context.Validated();

            await 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 Task ValidateClientAuthentication(OAuthValidateClientAuthenticationContext context)
        {
            string clientId = string.Empty;
            string clientSecret = string.Empty;
            Client client = null;

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

            if (context.ClientId == null)
            {
                context.SetError("invalid_clientId", "ClientId should be sent.");
                return Task.FromResult<object>(null);
            }

            using (AuthRepository _repo = new AuthRepository())
            {
                client = _repo.FindClient(context.ClientId);
            }

            if (client == null)
            {
                context.SetError("invalid_clientId", string.Format("Client '{0}' is not registered in the system.", context.ClientId));
                return Task.FromResult<object>(null);
            }

            if (!client.Active)
            {
                context.SetError("invalid_clientId", "Client is inactive.");
                return Task.FromResult<object>(null);
            }

            context.OwinContext.Set<string>("as:clientAllowedOrigin", client.AllowedOrigin);
            context.OwinContext.Set<string>("as:clientRefreshTokenLifeTime", client.RefreshTokenLifeTime.ToString());

            context.Validated();
            return Task.FromResult<object>(null);
        }
        public override Task ValidateClientAuthentication(OAuthValidateClientAuthenticationContext context)
        {
            string clientId = string.Empty;
            string clientSecret = string.Empty;
            DataLayer.Entities.User.IdentityClients client = null;

            if (!context.TryGetBasicCredentials(out clientId, out clientSecret))
            {
                context.TryGetFormCredentials(out clientId, out clientSecret);
            }
            // make sure the clientId is sent
            if (context.ClientId == null)
            {
                context.SetError("invalid_clientId", "ClientId should be sent");
                return Task.FromResult<object>(null);
            }

            // check if the client is registered
            BusinessLogic.Identity.IdentityClients clientObj = new BusinessLogic.Identity.IdentityClients();
            client = clientObj.GetByID(context.ClientId);

            if (client == null)
            {
                context.SetError("invalid_clientId", string.Format("Client '{0}' is not registered.", context.ClientId));
                return Task.FromResult<object>(null);
            }

            if (!client.active)
            {
                context.SetError("invalid_clientId", "Client is not active");
            }

            context.OwinContext.Set<string>("as:clientAllowedOrigin", client.allowedOrigin);
            context.OwinContext.Set<string>("as:cleintRefreshTokenLifeTime", client.refreshTokenLifetime.ToString());

            context.Validated();
            return Task.FromResult<object>(null);
        }
Ejemplo n.º 22
0
        public override Task ValidateClientAuthentication(OAuthValidateClientAuthenticationContext context)
        {
            string clientId;
            string clientSecret;

            if (!context.TryGetBasicCredentials(out clientId, out clientSecret))
            {
                context.TryGetFormCredentials(out clientId, out clientSecret);
            }
            if (clientId == null)
            {
                context.SetError("invalid_clientId", "clientId is not set");
                return Task.FromResult<object>(null);
            }
            var audience = AudienceStore.FindAudience(clientId);
            if (audience == null || clientSecret != audience.Secret)
            {
                context.SetError("invalid_clientId", $"Invalid Client ID {clientId}");
                return Task.FromResult<object>(null);
            }
            context.Validated();
            return Task.FromResult<object>(null);
        }
 /// <summary>
 /// 验证请求中的客户端Id与客户端密钥的合法性
 /// </summary>
 /// <param name="context"></param>
 /// <returns></returns>
 public override async Task ValidateClientAuthentication(OAuthValidateClientAuthenticationContext context)
 {
     string clientId, clientSecret;
     context.TryGetBasicCredentials(out clientId, out clientSecret);
     //判断客户端Id与客户端密钥的合法性,不合法的拦截
     bool validated = await _clientValidator.Validate(clientId, clientSecret);
     if (!validated)
     {
         context.SetError("invalid_client", "client is not valid.");
         return;
     }
     context.Validated(clientId);
     await base.ValidateClientAuthentication(context);
 }
        public override Task ValidateClientAuthentication(OAuthValidateClientAuthenticationContext context)
        {
            if (context.ClientId == null)
            {
                List<string> allowedOrigins = new List<string>() { "*" };
                context.OwinContext.Set<List<string>>("as:clientAllowedOrigins", allowedOrigins);

                context.Validated();
                return Task.FromResult<object>(null);
            }


            context.SetError("invalid_clientId", "Client secret is invalid.");
            return Task.FromResult<object>(null);
        }
        /// <summary>
        /// 验证 client 信息
        /// </summary>
        public override async Task ValidateClientAuthentication(OAuthValidateClientAuthenticationContext context)
        {
            string clientId;
            string clientSecret;
            if (!context.TryGetBasicCredentials(out clientId, out clientSecret))
            {
                context.TryGetFormCredentials(out clientId, out clientSecret);
            }

            if (clientId != "shoy" || clientSecret != "123456")
            {
                context.SetError("invalid_client", "client or clientSecret is not valid");
                return;
            }
            context.Validated();
        }
        /// <summary>
        ///     验证客户端
        /// </summary>
        /// <param name="context"></param>
        /// <returns></returns>
        public override async Task ValidateClientAuthentication(OAuthValidateClientAuthenticationContext context)
        {
            string clientId;
            string clientSecret;
            context.TryGetFormCredentials(out clientId, out clientSecret);
            //context.TryGetBasicCredentials(out clientId, out clientSecret); //Basic认证

            //TODO:读库,验证
            if (clientId != "malfy" && clientSecret != "111111")
            {
                context.SetError("invalid_client", "client is not valid");
                return;
            }
            context.OwinContext.Set("as:client_id", clientId);
            context.Validated(clientId);
        }
 /// <summary>
 /// 验证客户端 [Authorization Basic Base64(clientId:clientSecret)|Authorization: Basic 5zsd8ewF0MqapsWmDwFmQmeF0Mf2gJkW]
 /// </summary>
 /// <param name="context"></param>
 /// <returns></returns>
 public override async Task ValidateClientAuthentication(OAuthValidateClientAuthenticationContext context)
 {
     //validate client credentials should be stored securely (salted, hashed, iterated)
     string clientId;
     string clientSecret;
     context.TryGetBasicCredentials(out clientId, out clientSecret);
     var clientValid = await _clientAuthorizationService.ValidateClientAuthorizationSecretAsync(clientId, clientSecret);
     if (!clientValid)
     {
         //context.Rejected();
         context.SetError(AbpConstants.InvalidClient, AbpConstants.InvalidClientErrorDescription);
         return;
     }
     //need to make the client_id available for later security checks
     context.OwinContext.Set<string>("as:client_id", clientId);
     context.OwinContext.Set<string>("as:refresh_token_time", "36000");
     context.Validated(clientId);
 }
        public override async Task ValidateClientAuthentication(OAuthValidateClientAuthenticationContext context)
        {

            string cid, csecret;

            if (context.TryGetFormCredentials(out cid, out csecret))
            {
                if (IdentityProviders.AcceptedOauthClients.Any( ip => ip.Key == cid && ip.Value == csecret))
                {

                    context.Validated(cid);
                }
                else
                {
                    context.SetError("Invalid Client");
                }
            }
            await Task.FromResult<object>(null);
        }
Ejemplo n.º 29
0
    public override async Task ValidateClientAuthentication(OAuthValidateClientAuthenticationContext context) {
      string clientIdValue = string.Empty;
      string clientSecret = string.Empty;
      int clientId = 0;

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

      if (string.IsNullOrWhiteSpace(clientIdValue)) {
        context.SetError("invalid_clientId", "Client id should be sent");
        return;
      }

      if (!int.TryParse(clientIdValue, out clientId)) {
        context.SetError("invalid_clientId", "Client id is invalid");
        return;
      }

      var authenticationClient = new AuthenticationClient();
      var client = await authenticationClient.GetClient(new GetClientRequest { ClientId = clientId });

      if (client == null || !client.IsSuccess || client.Client == null) {
        context.SetError("invalid_clientId", string.Format("Client '{0}' is not registered in the system", clientId));
        return;
      }

      if (client.Client.ApplicationType == ApplicationType.NativeConfidential) {
        if (string.IsNullOrWhiteSpace(clientSecret)) {
          context.SetError("invalid_clientId", "Client secret should be sent");
          return;
        } else if (!PasswordHelper.VerifyPassword(clientSecret, client.Client.Secret)) {
          context.SetError("invalid_clientId", "Client secret is invalid");
          return;
        }
        if (!client.Client.Active) {
          context.SetError("invalid_cliendId", "Client is inactive");
          return;
        }
      }

      context.OwinContext.Set<string>("as:clientAllowedOrigin", client.Client.AllowedOrigin);
      context.OwinContext.Set<string>("as:clientRefreshTokenLifeTime", client.Client.RefreshTokenLifeTime.ToString());

      context.Validated();
    }
        /// <summary>
        /// Methode qui permet la validation du Service AKA Client web ou mobile, via le client_id et optionnellement le client_secret.
        /// </summary>
        /// <param name="context">Le context de la requête et d'autre information utiles à la gestion du service</param>
        /// <returns></returns>
        public override async Task ValidateClientAuthentication(OAuthValidateClientAuthenticationContext context)
        {
            string client_id = string.Empty;
            string client_secret = string.Empty;

            if (!context.TryGetBasicCredentials(out client_id, out client_secret))
            {
                context.TryGetFormCredentials(out client_id, out client_secret);
            }
            Service service = null;
            try
            {
                service = await AuthenticationTools.GetServiceActiveAndExists(context.OwinContext.Get<ManahostManagerDAL>(), context.ClientId, client_secret);
            }
            catch (AuthenticationToolsException e)
            {
                context.SetError(e.Key, e.Value);
                return;
            }
            context.OwinContext.Set<string>(GenericNames.OWIN_CONTEXT_CORS, service.AllowedOrigin);
            context.OwinContext.Set<int>(GenericNames.OWIN_CONTEXT_REFRESH_TOKEN_LIFETIME, service.RefreshTokenLifeTime);
            context.Validated();
        }
        private async Task InvokeTokenEndpointAsync()
        {
            DateTimeOffset currentUtc = Options.SystemClock.UtcNow;

            // remove milliseconds in case they don't round-trip
            currentUtc = currentUtc.Subtract(TimeSpan.FromMilliseconds(currentUtc.Millisecond));

            IFormCollection form = await Request.ReadFormAsync();

            var clientContext = new OAuthValidateClientAuthenticationContext(
                Context,
                Options,
                form);

            await Options.Provider.ValidateClientAuthentication(clientContext);

            if (!clientContext.IsValidated)
            {
                _logger.WriteError("clientID is not valid.");
                if (!clientContext.HasError)
                {
                    clientContext.SetError(Constants.Errors.InvalidClient);
                }
                await SendErrorAsJsonAsync(clientContext);

                return;
            }

            var tokenEndpointRequest = new TokenEndpointRequest(form);

            var validatingContext = new OAuthValidateTokenRequestContext(Context, Options, tokenEndpointRequest, clientContext);

            AuthenticationTicket ticket = null;

            if (tokenEndpointRequest.IsAuthorizationCodeGrantType)
            {
                // Authorization Code Grant http://tools.ietf.org/html/rfc6749#section-4.1
                // Access Token Request http://tools.ietf.org/html/rfc6749#section-4.1.3
                ticket = await InvokeTokenEndpointAuthorizationCodeGrantAsync(validatingContext, currentUtc);
            }
            else if (tokenEndpointRequest.IsResourceOwnerPasswordCredentialsGrantType)
            {
                // Resource Owner Password Credentials Grant http://tools.ietf.org/html/rfc6749#section-4.3
                // Access Token Request http://tools.ietf.org/html/rfc6749#section-4.3.2
                ticket = await InvokeTokenEndpointResourceOwnerPasswordCredentialsGrantAsync(validatingContext, currentUtc);
            }
            else if (tokenEndpointRequest.IsClientCredentialsGrantType)
            {
                // Client Credentials Grant http://tools.ietf.org/html/rfc6749#section-4.4
                // Access Token Request http://tools.ietf.org/html/rfc6749#section-4.4.2
                ticket = await InvokeTokenEndpointClientCredentialsGrantAsync(validatingContext, currentUtc);
            }
            else if (tokenEndpointRequest.IsRefreshTokenGrantType)
            {
                // Refreshing an Access Token
                // http://tools.ietf.org/html/rfc6749#section-6
                ticket = await InvokeTokenEndpointRefreshTokenGrantAsync(validatingContext, currentUtc);
            }
            else if (tokenEndpointRequest.IsCustomExtensionGrantType)
            {
                // Defining New Authorization Grant Types
                // http://tools.ietf.org/html/rfc6749#section-8.3
                ticket = await InvokeTokenEndpointCustomGrantAsync(validatingContext, currentUtc);
            }
            else
            {
                // Error Response http://tools.ietf.org/html/rfc6749#section-5.2
                // The authorization grant type is not supported by the
                // authorization server.
                _logger.WriteError("grant type is not recognized");
                validatingContext.SetError(Constants.Errors.UnsupportedGrantType);
            }

            if (ticket == null)
            {
                await SendErrorAsJsonAsync(validatingContext);

                return;
            }

            ticket.Properties.IssuedUtc  = currentUtc;
            ticket.Properties.ExpiresUtc = currentUtc.Add(Options.AccessTokenExpireTimeSpan);

            var tokenEndpointContext = new OAuthTokenEndpointContext(
                Context,
                Options,
                ticket,
                tokenEndpointRequest);

            await Options.Provider.TokenEndpoint(tokenEndpointContext);

            if (tokenEndpointContext.TokenIssued)
            {
                ticket = new AuthenticationTicket(
                    tokenEndpointContext.Identity,
                    tokenEndpointContext.Properties);
            }
            else
            {
                _logger.WriteError("Token was not issued to tokenEndpointContext");
                validatingContext.SetError(Constants.Errors.InvalidGrant);
                await SendErrorAsJsonAsync(validatingContext);

                return;
            }

            var accessTokenContext = new AuthenticationTokenCreateContext(
                Context,
                Options.AccessTokenFormat,
                ticket);

            await Options.AccessTokenProvider.CreateAsync(accessTokenContext);

            string accessToken = accessTokenContext.Token;

            if (string.IsNullOrEmpty(accessToken))
            {
                accessToken = accessTokenContext.SerializeTicket();
            }
            DateTimeOffset?accessTokenExpiresUtc = ticket.Properties.ExpiresUtc;

            var refreshTokenCreateContext = new AuthenticationTokenCreateContext(
                Context,
                Options.RefreshTokenFormat,
                accessTokenContext.Ticket);
            await Options.RefreshTokenProvider.CreateAsync(refreshTokenCreateContext);

            string refreshToken = refreshTokenCreateContext.Token;

            var memory = new MemoryStream();

            byte[] body;
            using (var writer = new JsonTextWriter(new StreamWriter(memory)))
            {
                writer.WriteStartObject();
                writer.WritePropertyName(Constants.Parameters.AccessToken);
                writer.WriteValue(accessToken);
                writer.WritePropertyName(Constants.Parameters.TokenType);
                writer.WriteValue(Constants.TokenTypes.Bearer);
                if (accessTokenExpiresUtc.HasValue)
                {
                    TimeSpan?expiresTimeSpan = accessTokenExpiresUtc - currentUtc;
                    var      expiresIn       = (long)expiresTimeSpan.Value.TotalSeconds;
                    if (expiresIn > 0)
                    {
                        writer.WritePropertyName(Constants.Parameters.ExpiresIn);
                        writer.WriteValue(expiresIn);
                    }
                }
                if (!String.IsNullOrEmpty(refreshToken))
                {
                    writer.WritePropertyName(Constants.Parameters.RefreshToken);
                    writer.WriteValue(refreshToken);
                }
                foreach (var additionalResponseParameter in tokenEndpointContext.AdditionalResponseParameters)
                {
                    writer.WritePropertyName(additionalResponseParameter.Key);
                    writer.WriteValue(additionalResponseParameter.Value);
                }
                writer.WriteEndObject();
                writer.Flush();
                body = memory.ToArray();
            }
            Response.ContentType = "application/json;charset=UTF-8";
            Response.Headers.Set("Cache-Control", "no-cache");
            Response.Headers.Set("Pragma", "no-cache");
            Response.Headers.Set("Expires", "-1");
            Response.ContentLength = memory.ToArray().Length;
            await Response.WriteAsync(body, Request.CallCancelled);
        }