Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Adding authentication via JSON REST API #134

Open
wants to merge 4 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
54 changes: 54 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -214,7 +214,61 @@ Add the following to your `config.php`:

**⚠⚠ Warning:** If you need to set *5 (Hashed Password in Database)* to false, your Prosody Instance is storing passwords in plaintext. This is insecure and not recommended. We highly recommend that you change your Prosody configuration to protect the passwords of your Prosody users. ⚠⚠

REST
----
Authenticate Nextcloud users against a REST JSON authentication API.

### Configuration
The parameters are `URL, alwaysAssignDisplayname`. If you set the last parameter to `true`, the display name of the user will be replaced *each* time the users performs a login.

Add the following to your `config.php`:
```
'user_backends' => array (
0 => array (
'class' => 'OC_User_REST',
'arguments' => array (
0 => 'https://URLofyourRESTserver',
1 => false
),
),
),
```
### Dependencies
You need to have `php-curl` installed to use this authentication method.

### REST endpoints
* This script perfoms an authentication via a POST JSON REST Request.
* To use this method, you need to implement a single REST endpoint:
* Path: /_nextcloud/user_external/v1/authenticate
* Method: POST
* Body as JSON UTF8:
```
{
"user": {
"id": "UserID",
"password": "enteredPassword"
}
}
```
* If the transmitted credentials are correct, your JSON answer should be:
```
{
"auth": {
"success": true,
"id": "UserID",
"displayName": "Display Name to Store",
"groups": ["group1","group2"]
}
}
```
* If the Authentication fails, your JSON answer should be:
```
{
"auth": {
"success": false
}
}
```
Alternatives
------------
Other extensions allow connecting to external user databases directly via SQL, which may be faster:
Expand Down
1 change: 1 addition & 0 deletions appinfo/app.php
Original file line number Diff line number Diff line change
Expand Up @@ -5,3 +5,4 @@
OC::$CLASSPATH['OC_User_BasicAuth']='user_external/lib/basicauth.php';
OC::$CLASSPATH['OC_User_SSH']='user_external/lib/ssh.php';
OC::$CLASSPATH['OC_User_XMPP']='user_external/lib/xmpp.php';
OC::$CLASSPATH['OC_User_REST']='user_external/lib/rest.php';
16 changes: 14 additions & 2 deletions lib/base.php
Original file line number Diff line number Diff line change
Expand Up @@ -172,7 +172,7 @@ public function setDisplayName($uid, $displayName) {
* @param string $uid The username
* @param array $groups Groups to add the user to on creation
*
* @return void
* @return string the uid as stored in the db.
*/
protected function storeUser($uid, $groups = []) {
if (!$this->userExists($uid)) {
Expand All @@ -190,7 +190,19 @@ protected function storeUser($uid, $groups = []) {
\OC::$server->getGroupManager()->createGroup($group)->addUser($createduser);
}
}
}
return $uid;
} else {
$connection = \OC::$server->getDatabaseConnection();
$query = \OC::$server->getDatabaseConnection()->getQueryBuilder();
$query->select('uid')
->from('users_external')
->where($query->expr()->iLike('uid', $query->createNamedParameter($connection->escapeLikeParameter($uid))))
->andWhere($query->expr()->eq('backend', $query->createNamedParameter($this->backend)));
$result = $query->execute();
$db_uid = $result->fetchColumn();
$result->closeCursor();
return $db_uid;
}
}

/**
Expand Down
118 changes: 118 additions & 0 deletions lib/rest.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,118 @@
<?php
/**
* Copyright (c) 2020 Michael Schindler <mich.schindl@gmail.com>
* Copyright (c) 2019 Lutz Freitag <lutz.freitag@gottliebtfreitag.de>
* This file is licensed under the Affero General Public License version 3 or
* later.
* See the COPYING-README file.
*/


/**
* This script perfoms an authentication via a POST JSON REST Request.
* To use this method, you need to implement a single REST endpoint:
* Path: /_nextcloud/user_external/v1/authenticate
* Method: POST
* Body as JSON UTF-8:
*
* {
* "user": {
* "id": "UserID",
* "password": "enteredPassword"
* }
* }
*
* If the transmitted credentials are correct, your JSON answer should be:
*
* {
* "auth": {
* "success": true,
* "id": "UserID",
* "displayName": "Display Name to Store",
* "groups": ["group1","group2"]
* }
* }
*
* If the Authentication fails, your JSON answer should be:
*
* {
* "auth": {
* "success": false
* }
* }
*
*/

use OCP\AppFramework\Http;

class OC_User_REST extends \OCA\user_external\Base {

private $authUrl;
private $alwaysAssignDisplayname;

public function __construct($authUrl,$alwaysAssignDisplayname) {
parent::__construct($authUrl,$alwaysAssignDisplayname);
$this->authUrl = $authUrl;
$this->alwaysAssignDisplayname = $alwaysAssignDisplayname;
}

/**
* Check if the password is correct without logging in the user
*
* @param string $uid The username
* @param string $password The password
*
* @return string $uid The username
*/
public function checkPassword($uid, $password) {
$postdata = json_encode(array("user"=>array("id"=>$uid,"password"=>$password)));

$client = \OC::$server->getHTTPClientService()->newClient();
try {
$response = $client->post($this->authUrl."/_nextcloud/user_external/v1/authenticate", [
'body' => $postdata,
'timeout' => 10,
'connect_timeout' => 10,
]);
$result = json_decode($response->getBody(),true);
} catch (\GuzzleHttp\Exception\RequestException $e) {
if($e->getCode() === Http::STATUS_UNAUTHORIZED || $e->getCode() === Http::STATUS_FORBIDDEN) {
OC::$server->getLogger()->error(
'ERROR: Resource on REST server is forbidden on: '.$this->authUrl,
['app' => 'user_external']
);
} elseif($e->getCode() === Http::STATUS_NOT_FOUND) {
OC::$server->getLogger()->error(
'ERROR: REST Server sent 404 on: '.$this->authUrl,
['app' => 'user_external']
);
} else {
OC::$server->getLogger()->error(
'ERROR: Unknown request error on: '.$this->authUrl,
['app' => 'user_external']
);
}
$result = false;
}

if(is_array($result)) {
if($result['auth']['success']===true) {
$user_exists = $this->userExists($result['auth']['id']);
$uid = $this->storeUser($result['auth']['id'],$result['auth']['groups']);
if(key_exists("displayName",$result['auth']) && (($user_exists && $this->alwaysAssignDisplayname) || (!$user_exists))) {
$this->setDisplayName($result['auth']['id'],$result['auth']['displayName']);
}
//return $result['auth']['id'];
return $uid;
} else {
return false;
}
} elseif($result===false) {
OC::$server->getLogger()->error(
'ERROR: Not possible to connect to REST Url: '.$this->authUrl,
['app' => 'user_external']
);
}
return false;
}
}