> ## Documentation Index
> Fetch the complete documentation index at: https://mintlify.com/wazuh/wazuh-dashboard-plugins/llms.txt
> Use this file to discover all available pages before exploring further.

# Security Components API

> React components for security policies and access control

The Security components provide interfaces for managing security policies, user permissions, role-based access control, and security events.

## Security Main

Main security interface component for security policy management.

**Location:** `plugins/main/public/components/security/main.tsx`

### Usage

```typescript theme={null}
import React from 'react';
import { Security } from '../components/security/main';

function App() {
  return <Security />;
}
```

The Security component provides access to:

* Security events and alerts
* RBAC policy management
* User and role management
* Security configuration
* Audit logs

## Security Events

### SecurityEventsTable

Displays security events and alerts with filtering and search.

**Props:**

**filters** `object`

Filters to apply to events

**properties**

**timeRange** `object`

Time range for events

**properties**

**from** `string`

Start time (e.g., "now-24h")

**to** `string`

End time (e.g., "now")

**level** `number`

Minimum alert level

**rule.groups** `string[]`

Filter by rule groups

**agent.id** `string`

Filter by agent ID

**onEventClick** `(event: SecurityEvent) =\> void`

Callback when an event is clicked

**Usage:**

```typescript theme={null}
import React, { useState } from 'react';
import { SecurityEventsTable } from '../components/security/events/security-events-table';

function SecurityMonitoring() {
  const [selectedEvent, setSelectedEvent] = useState(null);
  
  return (
    <div>
      <SecurityEventsTable
        filters={{
          timeRange: { from: 'now-24h', to: 'now' },
          level: 7,
        }}
        onEventClick={setSelectedEvent}
      />
      
      {selectedEvent && (
        <EventDetails event={selectedEvent} />
      )}
    </div>
  );
}
```

#### SecurityEvent Type

```typescript theme={null}
interface SecurityEvent {
  id: string;
  timestamp: string;
  agent: {
    id: string;
    name: string;
    ip?: string;
  };
  rule: {
    id: number;
    description: string;
    level: number;
    groups: string[];
    mitre?: {
      id: string[];
      tactic: string[];
      technique: string[];
    };
  };
  data?: {
    srcip?: string;
    srcport?: number;
    dstip?: string;
    dstport?: number;
    protocol?: string;
    action?: string;
  };
  decoder?: {
    name: string;
    parent?: string;
  };
  location?: string;
  full_log?: string;
}
```

## RBAC Components

### RolesTable

Manage security roles and permissions.

**Props:**

**onSelectRole** `(role: Role) =\> void`

Callback when a role is selected

**onEditRole** `(role: Role) =\> void`

Callback to edit role

**onDeleteRole** `(role: Role) =\> void`

Callback to delete role

**Usage:**

```typescript theme={null}
import React, { useState } from 'react';
import { RolesTable } from '../components/security/roles/roles-table';
import { EuiButton } from '@elastic/eui';

function RolesManagement() {
  const [selectedRole, setSelectedRole] = useState(null);
  const [showEditModal, setShowEditModal] = useState(false);
  
  const handleEditRole = (role) => {
    setSelectedRole(role);
    setShowEditModal(true);
  };
  
  const handleDeleteRole = async (role) => {
    if (confirm(`Delete role ${role.name}?`)) {
      try {
        await WzRequest.apiReq(
          'DELETE',
          `/security/roles/${role.id}`,
          {}
        );
        // Refresh roles list
      } catch (error) {
        console.error('Failed to delete role:', error);
      }
    }
  };
  
  return (
    <div>
      <RolesTable
        onSelectRole={setSelectedRole}
        onEditRole={handleEditRole}
        onDeleteRole={handleDeleteRole}
      />
    </div>
  );
}
```

#### Role Type

```typescript theme={null}
interface Role {
  id: number;
  name: string;
  description?: string;
  permissions: Permission[];
  policies?: Policy[];
  rules?: Rule[];
}

interface Permission {
  resource: string;
  actions: string[];
  conditions?: object;
}
```

### UsersTable

Manage security users and role assignments.

**Props:**

**onSelectUser** `(user: User) =\> void`

Callback when a user is selected

**onEditUser** `(user: User) =\> void`

Callback to edit user

**Usage:**

```typescript theme={null}
import React from 'react';
import { UsersTable } from '../components/security/users/users-table';

function UsersManagement() {
  return (
    <UsersTable
      onSelectUser={(user) => {
        console.log('Selected user:', user);
      }}
      onEditUser={(user) => {
        // Open edit modal
      }}
    />
  );
}
```

#### User Type

```typescript theme={null}
interface User {
  username: string;
  roles: string[];
  allow_run_as?: boolean;
  backend_roles?: string[];
}
```

### PoliciesTable

Manage security policies.

**Props:**

**onSelectPolicy** `(policy: Policy) =\> void`

Callback when a policy is selected

**Usage:**

```typescript theme={null}
import React from 'react';
import { PoliciesTable } from '../components/security/policies/policies-table';

function PoliciesManagement() {
  return (
    <PoliciesTable
      onSelectPolicy={(policy) => {
        // View policy details
      }}
    />
  );
}
```

#### Policy Type

```typescript theme={null}
interface Policy {
  id: number;
  name: string;
  policy: {
    actions: string[];
    resources: string[];
    effect: 'allow' | 'deny';
  };
}
```

## Role Editor

### RoleEditor

Form component for creating and editing roles.

**Props:**

**role** `Role`

Existing role to edit (omit for new role)

**onSave** `(role: Role) =\> void` *required*

Callback when role is saved

**onCancel** `() =\> void` *required*

Callback when editing is cancelled

**Usage:**

```typescript theme={null}
import React, { useState } from 'react';
import { RoleEditor } from '../components/security/roles/role-editor';
import { EuiModal, EuiModalHeader, EuiModalBody } from '@elastic/eui';

function RoleEditModal({ role, onClose, onSuccess }) {
  const handleSave = async (updatedRole) => {
    try {
      const method = role ? 'PUT' : 'POST';
      const path = role 
        ? `/security/roles/${role.id}` 
        : '/security/roles';
      
      await WzRequest.apiReq(method, path, { body: updatedRole });
      onSuccess();
      onClose();
    } catch (error) {
      console.error('Failed to save role:', error);
    }
  };
  
  return (
    <EuiModal onClose={onClose}>
      <EuiModalHeader>
        <h2>{role ? 'Edit Role' : 'Create Role'}</h2>
      </EuiModalHeader>
      <EuiModalBody>
        <RoleEditor
          role={role}
          onSave={handleSave}
          onCancel={onClose}
        />
      </EuiModalBody>
    </EuiModal>
  );
}
```

## Permission Selector

### PermissionSelector

Component for selecting resource permissions.

**Props:**

**permissions** `Permission[]` *required*

Current permissions

**onChange** `(permissions: Permission[]) =\> void` *required*

Callback when permissions change

**availableResources** `string[]`

List of available resource types

**Usage:**

```typescript theme={null}
import React, { useState } from 'react';
import { PermissionSelector } from '../components/security/permissions/permission-selector';

function RolePermissions() {
  const [permissions, setPermissions] = useState([]);
  
  const availableResources = [
    'agent:id',
    'group:id',
    'rule:file',
    'decoder:file',
    '*:*',
  ];
  
  return (
    <PermissionSelector
      permissions={permissions}
      onChange={setPermissions}
      availableResources={availableResources}
    />
  );
}
```

## Security Audit

### AuditLogsTable

Displays security audit logs.

**Props:**

**filters** `object`

Filters for audit logs

**properties**

**user** `string`

Filter by username

**action** `string`

Filter by action type

**timeRange** `object`

Time range filter

**Usage:**

```typescript theme={null}
import React from 'react';
import { AuditLogsTable } from '../components/security/audit/audit-logs-table';

function SecurityAudit() {
  return (
    <AuditLogsTable
      filters={{
        timeRange: { from: 'now-7d', to: 'now' },
        action: 'security:role:update',
      }}
    />
  );
}
```

## Complete Example

Full security management interface:

```typescript theme={null}
import React, { useState } from 'react';
import {
  EuiPage,
  EuiPageBody,
  EuiPageContent,
  EuiTabbedContent,
  EuiButton,
  EuiSpacer,
  EuiFlexGroup,
  EuiFlexItem,
} from '@elastic/eui';
import { RolesTable } from '../components/security/roles/roles-table';
import { UsersTable } from '../components/security/users/users-table';
import { PoliciesTable } from '../components/security/policies/policies-table';
import { AuditLogsTable } from '../components/security/audit/audit-logs-table';
import { RoleEditor } from '../components/security/roles/role-editor';

function SecurityManagement() {
  const [selectedTab, setSelectedTab] = useState('roles');
  const [showRoleEditor, setShowRoleEditor] = useState(false);
  const [editingRole, setEditingRole] = useState(null);
  
  const handleEditRole = (role) => {
    setEditingRole(role);
    setShowRoleEditor(true);
  };
  
  const handleCreateRole = () => {
    setEditingRole(null);
    setShowRoleEditor(true);
  };
  
  const tabs = [
    {
      id: 'roles',
      name: 'Roles',
      content: (
        <>
          <EuiSpacer />
          <EuiFlexGroup justifyContent="flexEnd">
            <EuiFlexItem grow={false}>
              <EuiButton
                fill
                iconType="plusInCircle"
                onClick={handleCreateRole}
              >
                Create role
              </EuiButton>
            </EuiFlexItem>
          </EuiFlexGroup>
          <EuiSpacer />
          <RolesTable
            onEditRole={handleEditRole}
            onDeleteRole={async (role) => {
              // Handle delete
            }}
          />
        </>
      ),
    },
    {
      id: 'users',
      name: 'Users',
      content: (
        <>
          <EuiSpacer />
          <UsersTable
            onEditUser={(user) => {
              // Handle edit
            }}
          />
        </>
      ),
    },
    {
      id: 'policies',
      name: 'Policies',
      content: (
        <>
          <EuiSpacer />
          <PoliciesTable
            onSelectPolicy={(policy) => {
              console.log('Selected policy:', policy);
            }}
          />
        </>
      ),
    },
    {
      id: 'audit',
      name: 'Audit',
      content: (
        <>
          <EuiSpacer />
          <AuditLogsTable
            filters={{
              timeRange: { from: 'now-7d', to: 'now' },
            }}
          />
        </>
      ),
    },
  ];
  
  return (
    <EuiPage>
      <EuiPageBody>
        <EuiPageContent>
          <EuiTabbedContent
            tabs={tabs}
            selectedTab={tabs.find(t => t.id === selectedTab)}
            onTabClick={(tab) => setSelectedTab(tab.id)}
          />
        </EuiPageContent>
      </EuiPageBody>
      
      {showRoleEditor && (
        <RoleEditor
          role={editingRole}
          onSave={(role) => {
            // Save role
            setShowRoleEditor(false);
          }}
          onCancel={() => setShowRoleEditor(false)}
        />
      )}
    </EuiPage>
  );
}

export default SecurityManagement;
```

## Utility Functions

### checkPermission()

Check if current user has a specific permission.

```typescript theme={null}
import { checkPermission } from '../utils/security';

const canEditRoles = await checkPermission('security:role:update');

if (canEditRoles) {
  // Show edit button
}
```

### hasRole()

Check if current user has a specific role.

```typescript theme={null}
import { hasRole } from '../utils/security';

const isAdmin = await hasRole('administrator');
```

### getCurrentUser()

Get current user information.

```typescript theme={null}
import { getCurrentUser } from '../utils/security';

const user = await getCurrentUser();
console.log(`Logged in as: ${user.username}`);
```

## Best Practices

> **Check Permissions Before Rendering**
>
> Verify user permissions before showing UI elements:
>
> ```typescript theme={null}
> const [canEdit, setCanEdit] = useState(false);
>
> useEffect(() => {
>   checkPermission('security:role:update').then(setCanEdit);
> }, []);
>
> return (
>   <div>
>     {canEdit && <EditButton />}
>   </div>
> );
> ```

> **Validate Role Assignments**
>
> Ensure roles exist before assigning to users:
>
> ```typescript theme={null}
> const assignRole = async (userId, roleId) => {
>   const role = await fetchRole(roleId);
>   if (!role) {
>     throw new Error('Role not found');
>   }
>   await assignRoleToUser(userId, roleId);
> };
> ```

> **Log Security Actions**
>
> Always log security-related actions for audit:
>
> ```typescript theme={null}
> const deleteRole = async (roleId) => {
>   await WzRequest.apiReq('DELETE', `/security/roles/${roleId}`, {});
>   // Action is automatically logged by the API
> };
> ```

## Related Resources

> **[Settings Components](/api/components/settings)**
>
> Settings and configuration

> **[RBAC Guide](/api/components/security)**
>
> Role-based access control

> **[Authentication](/configuration/authentication)**
>
> Authentication configuration

> **[Wazuh Core API](/api/wazuh-core)**
>
> Security services API


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.