> ## Documentation Index
> Fetch the complete documentation index at: https://docs-unity.molca.id/llms.txt
> Use this file to discover all available pages before exploring further.

# AuthManager

> User authentication, token validation, secure credential storage, and auto-injection of auth headers.

**Namespace:** `Molca.Networking.Auth`\
**File:** `Packages/com.molca.core/Runtime/Networking/Auth/AuthManager.cs`\
**Interface:** `IAuthManager`\
**Type:** `RuntimeSubsystem` (child of [RuntimeManager](/core/runtime-manager) prefab)

## When to use

Use `AuthManager` when your app needs user authentication with token-based session management. It handles login/logout, cached token validation on startup, and automatic auth header injection on outgoing HTTP requests via `AuthTokenInterceptor`.

## Role

* **Login** — `LoginAsync(username, password)` authenticates via a configured `HttpRequestAsset`, persists the encrypted user data to `SecureStorage`.
* **Cached token validation** — `TryValidateCachedToken()` loads persisted credentials and validates against the server.
* **Auto-injection** — `AuthTokenInterceptor` automatically adds the auth token header to every outgoing `IHttpClient` request.
* **Guest login** — `GuestLogin(data)` creates an unauthenticated session for anonymous users.
* **Logout** — `LogoutAsync()` clears local state and notifies the server.

## Inspector configuration

| Field                   | Type               | Purpose                                       |
| ----------------------- | ------------------ | --------------------------------------------- |
| `_validateTokenRequest` | `HttpRequestAsset` | Request config for token validation endpoint. |
| `_loginRequest`         | `HttpRequestAsset` | Request config for login endpoint.            |
| `_logoutRequest`        | `HttpRequestAsset` | Request config for logout endpoint.           |
| `_user`                 | `AuthUser`         | User data holder (ScriptableObject).          |
| `authUserPath`          | `string`           | Base path for user-specific API calls.        |
| `authTokenKey`          | `string`           | Header key name for the auth token.           |

## API Reference

| Member                   | Signature                                                      | Description                                                                                |
| ------------------------ | -------------------------------------------------------------- | ------------------------------------------------------------------------------------------ |
| `AuthToken`              | `string AuthToken { get; }`                                    | The current bearer/auth token.                                                             |
| `User`                   | `AuthUser User { get; }`                                       | The current authenticated user object.                                                     |
| `IsAuthenticated`        | `bool IsAuthenticated { get; }`                                | Whether a user is currently authenticated.                                                 |
| `HasCachedToken`         | `bool HasCachedToken { get; }`                                 | Whether a persisted token exists in `SecureStorage`.                                       |
| `LoginAsync`             | `Awaitable<bool> LoginAsync(string username, string password)` | Authenticate with credentials. Persists user data on success.                              |
| `LogoutAsync`            | `Awaitable<bool> LogoutAsync()`                                | Log out and clear local credentials. Always succeeds locally even if server request fails. |
| `TryValidateCachedToken` | `Awaitable<bool> TryValidateCachedToken()`                     | Validate the persisted token against the server. Clears data if invalid.                   |
| `GuestLogin`             | `void GuestLogin(IAuthUserData data)`                          | Create an anonymous/guest session.                                                         |
| `GetUserData<T>`         | `T GetUserData<T>() where T : IAuthUserData`                   | Get user data cast to a specific type.                                                     |
| `TryApplyToken`          | `[Obsolete] bool TryApplyToken(HttpRequest request)`           | Legacy — auth headers are now injected automatically.                                      |

## Code

```csharp theme={null}
using Molca;
using Molca.Networking.Auth;
using UnityEngine;

public class LoginController : MonoBehaviour
{
    [Inject] private AuthManager _auth;

    private async void Start()
    {
        await RuntimeManager.WaitForInitialization();

        // Try restoring a cached session
        if (_auth.HasCachedToken)
        {
            bool valid = await _auth.TryValidateCachedToken();
            if (valid)
            {
                Debug.Log("Session restored");
                return;
            }
        }
    }

    public async void OnLogin(string username, string password)
    {
        bool success = await _auth.LoginAsync(username, password);
        if (success)
            Debug.Log($"Logged in as {_auth.User.GetUserId()}");
    }

    public async void OnLogout()
    {
        await _auth.LogoutAsync();
    }
}
```

## Events

`AuthManager` dispatches typed events through `EventDispatcher`:

* `AuthEvents.LoggedIn` — fired after successful login/guest login with `AuthLoggedInEventData`
* `AuthEvents.LoggedOut` — fired after logout/clear with `AuthLoggedOutEventData`

## Troubleshooting

* **`TryValidateCachedToken` returns false:** the cached token has expired or the server endpoint is unreachable. User must log in again.
* **Auth header not sent on requests:** ensure `authTokenKey` matches the header name the server expects. The interceptor fires automatically on requests built through `IHttpClient`.

## Related

* [HttpClient](/core/http-client) — underlying transport; auth headers injected automatically
* [IHttpRequestInterceptor](/core/http-client) — `AuthTokenInterceptor` implements this
* [SecureStorage](/core/secure-storage) — encrypted local credential persistence
