PHPackages                             bahuma/oauth2-nextcloud - PHPackages - PHPackages  [Skip to content](#main-content)[PHPackages](/)[Directory](/)[Categories](/categories)[Trending](/trending)[Leaderboard](/leaderboard)[Changelog](/changelog)[Analyze](/analyze)[Collections](/collections)[Log in](/login)[Sign up](/register)

1. [Directory](/)
2. /
3. [Authentication &amp; Authorization](/categories/authentication)
4. /
5. bahuma/oauth2-nextcloud

ActiveLibrary[Authentication &amp; Authorization](/categories/authentication)

bahuma/oauth2-nextcloud
=======================

Nextcloud OAuth 2.0 Client Provider for The PHP League OAuth2-Client

2.1.0(1y ago)626.1k↓38.6%21MITPHPPHP ^7.4||^8.0CI passing

Since Apr 25Pushed 1y ago1 watchersCompare

[ Source](https://github.com/bahuma20/oauth2-nextcloud)[ Packagist](https://packagist.org/packages/bahuma/oauth2-nextcloud)[ RSS](/packages/bahuma-oauth2-nextcloud/feed)WikiDiscussions master Synced 1mo ago

READMEChangelog (4)Dependencies (4)Versions (5)Used By (1)

Nextcloud Provider for OAuth 2.0 Client
=======================================

[](#nextcloud-provider-for-oauth-20-client)

This package provides Nextcloud OAuth 2.0 support for the PHP League's [OAuth 2.0 Client](https://github.com/thephpleague/oauth2-client).

This package is compliant with [PSR-1](https://github.com/php-fig/fig-standards/blob/master/accepted/PSR-1-basic-coding-standard.md), [PSR-2](https://github.com/php-fig/fig-standards/blob/master/accepted/PSR-2-coding-style-guide.md) and [PSR-4](https://github.com/php-fig/fig-standards/blob/master/accepted/PSR-4-autoloader.md). If you notice compliance oversights, please send a patch via pull request.

Requirements
------------

[](#requirements)

The following versions of PHP are supported.

- From PHP 7.4 to PHP 8.4

To use this package, it will be necessary to have a Nextcloud client ID and client secret. These are referred to as `{nextcloud-client-id}` and `{nextcloud-client-secret}`in the documentation.

Please follow the [Nextcloud instructions](https://docs.nextcloud.com/server/latest/admin_manual/configuration_server/oauth2.html#add-an-oauth2-application) to create the required credentials.

Installation
------------

[](#installation)

To install, use composer:

```
composer require bahuma/oauth2-nextcloud
```

Usage
-----

[](#usage)

### Authorization Code Flow

[](#authorization-code-flow)

```
use Bahuma\OAuth2\Client\Provider\Nextcloud;

session_start();

$provider = new Nextcloud([
    'clientId'     => '{nextcloud-client-id}',
    'clientSecret' => '{nextcloud-client-secret}',
    'redirectUri'  => 'https://example.com/callback-url',
    'nextcloudUrl' => 'https://cloud.example.com', // Base URL of your nextcloud instance.
]);

if (!empty($_GET['error'])) {

    // Got an error, probably user denied access
    exit('Got error: ' . htmlspecialchars($_GET['error'], ENT_QUOTES, 'UTF-8'));

} elseif (empty($_GET['code'])) {

    // If we don't have an authorization code then get one
    $authUrl = $provider->getAuthorizationUrl();
    $_SESSION['oauth2state'] = $provider->getState();
    header('Location: ' . $authUrl);
    exit;

} elseif (empty($_GET['state']) || ($_GET['state'] !== $_SESSION['oauth2state'])) {

    // State is invalid, possible CSRF attack in progress
    unset($_SESSION['oauth2state']);
    exit('Invalid state');

} else {

    // Try to get an access token (using the authorization code grant)
    $token = $provider->getAccessToken('authorization_code', [
        'code' => $_GET['code']
    ]);

    // Optional: Now you have a token you can look up a users profile data
    try {

        // We got an access token, let's now get the owner details
        /** @var \Bahuma\OAuth2\Client\Provider\NextcloudResourceOwner $ownerDetails */
        $ownerDetails = $provider->getResourceOwner($token);

        // Use these details to create a new profile
        printf('Hello %s!', $ownerDetails->getEmail());

    } catch (Exception $e) {

        // Failed to get user details
        exit('Something went wrong: ' . $e->getMessage());

    }

    // Use this to interact with an API on the users behalf
    echo $token->getToken();

    // Use this to get a new access token if the old one expires
    echo $token->getRefreshToken();

    // Unix timestamp at which the access token expires
    echo $token->getExpires();
}
```

### Refreshing a Token

[](#refreshing-a-token)

```
$token = $provider->getAccessToken('authorization_code', [
    'code' => $code
]);

// persist the token in a database
$refreshToken = $token->getRefreshToken();
```

Now you have everything you need to refresh an access token using a refresh token:

```
use Bahuma\OAuth2\Client\Provider\Nextcloud;
use League\OAuth2\Client\Grant\RefreshToken;

$provider = new Nextcloud([
    'clientId'     => '{google-client-id}',
    'clientSecret' => '{google-client-secret}',
    'redirectUri'  => 'https://example.com/callback-url',
    'nextcloudUrl' => 'https://cloud.example.com', // Base URL of your nextcloud instance.
]);

$grant = new RefreshToken();
$token = $provider->getAccessToken($grant, ['refresh_token' => $refreshToken]);
```

Scopes
------

[](#scopes)

Nextcloud OAuth2 implementation currently does not support scoped access. This means that every token has full access to the complete account including read and write permission to the stored files. It is essential to store the OAuth2 tokens in a safe way!

Testing
-------

[](#testing)

Tests can be run with:

```
composer test
```

Style checks can be run with:

```
composer check
```

Credits
-------

[](#credits)

- [Max Bachhuber](https://github.com/bahuma20)
- [Aleix Quintana Alsius](https://github.com/aleixq)
- [All Contributors](https://github.com/bahuma/oauth2-nextcloud/contributors)

License
-------

[](#license)

The MIT License (MIT). Please see [License File](https://github.com/thephpleague/oauth2-nextcloud/blob/master/LICENSE) for more information.

###  Health Score

42

—

FairBetter than 90% of packages

Maintenance46

Moderate activity, may be stable

Popularity32

Limited adoption so far

Community13

Small or concentrated contributor base

Maturity64

Established project with proven stability

 Bus Factor1

Top contributor holds 61.9% of commits — single point of failure

How is this calculated?**Maintenance (25%)** — Last commit recency, latest release date, and issue-to-star ratio. Uses a 2-year decay window.

**Popularity (30%)** — Total and monthly downloads, GitHub stars, and forks. Logarithmic scaling prevents top-heavy scores.

**Community (15%)** — Contributors, dependents, forks, watchers, and maintainers. Measures real ecosystem engagement.

**Maturity (30%)** — Project age, version count, PHP version support, and release stability.

###  Release Activity

Cadence

Every ~598 days

Total

4

Last Release

418d ago

Major Versions

1.1.0 → 2.0.02023-05-11

### Community

Maintainers

![](https://www.gravatar.com/avatar/f7a6981f86767d0b4e5760bbff88d49e519d56613f489cf2a8bf8821d1cc6627?d=identicon)[bahuma20](/maintainers/bahuma20)

---

Top Contributors

[![bahuma20](https://avatars.githubusercontent.com/u/5746121?v=4)](https://github.com/bahuma20 "bahuma20 (13 commits)")[![aleixq](https://avatars.githubusercontent.com/u/2495087?v=4)](https://github.com/aleixq "aleixq (8 commits)")

###  Code Quality

TestsPHPUnit

Code StylePHP\_CodeSniffer

### Embed Badge

![Health badge](/badges/bahuma-oauth2-nextcloud/health.svg)

```
[![Health](https://phpackages.com/badges/bahuma-oauth2-nextcloud/health.svg)](https://phpackages.com/packages/bahuma-oauth2-nextcloud)
```

###  Alternatives

[league/oauth2-google

Google OAuth 2.0 Client Provider for The PHP League OAuth2-Client

41721.2M118](/packages/league-oauth2-google)[knpuniversity/oauth2-client-bundle

Integration with league/oauth2-client to provide services

83416.7M61](/packages/knpuniversity-oauth2-client-bundle)[thenetworg/oauth2-azure

Azure Active Directory OAuth 2.0 Client Provider for The PHP League OAuth2-Client

2509.6M48](/packages/thenetworg-oauth2-azure)[stevenmaguire/oauth2-keycloak

Keycloak OAuth 2.0 Client Provider for The PHP League OAuth2-Client

2275.9M27](/packages/stevenmaguire-oauth2-keycloak)[patrickbussmann/oauth2-apple

Sign in with Apple OAuth 2.0 Client Provider for The PHP League OAuth2-Client

1132.5M6](/packages/patrickbussmann-oauth2-apple)[microsoft/kiota-authentication-phpleague

Authentication provider for Kiota using the PHP League OAuth 2.0 client to authenticate against the Microsoft Identity platform

153.2M7](/packages/microsoft-kiota-authentication-phpleague)

PHPackages © 2026

[Directory](/)[Categories](/categories)[Trending](/trending)[Changelog](/changelog)[Analyze](/analyze)
