Integrate with DSM Web Authentication

After integrating your application into Synology DSM, you may want to perform an authentication check to ensure only logged-in users can access the page.

To check whether a user has logged in, run the CGI command in below.

/usr/syno/synoman/webman/modules/authenticate.cgi

The “authenticate.cgi” will output the user name if the user has logged in. There will be no output if the user has not been authenticated.

Below is an example:

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <strings.h>

/**
 * Check whether user is logged in. 
 * 
 * If user has logged in, put the username into "user".
 * 
 * @param user    The buffer for get username
 * @param bufsize The buffer size of user
 * 
 * @return 0: User not logged in or error
 *         1: User logged in. The user name is written to given "user"
 */
int IsUserLogin(char *user, int bufsize)
{
    FILE *fp = NULL;
    char buf[1024];
    int login = 0;

    bzero(user, bufsize);

    fp = popen("/usr/syno/synoman/webman/modules/authenticate.cgi", "r");
    if (!fp) {
        return 0;
    }
    bzero(buf, sizeof(buf));
    fread(buf, 1024, 1, fp);


    if (strlen(buf) > 0) {
        snprintf(user, bufsize, "%s", buf);
        login = 1;
    }
    pclose(fp);

    return login;
}

int main(int argc, char **argv)
{
    char user[256];

    printf("Content-type: text/html\r\n\r\n");
    if (IsUserLogin(user, sizeof(user)) == 1) {
        printf("User is authenticated. Name: %s\n", user);
    } else {
        printf("User is not authenticated.\n");
    }
    return 0;
}

DSM might require a random value called SynoToken to prevent a CSRF(cross-site request forgery) attack after 4.3. When CSRF protection is enabled in the control panel, you must append SynoToken to the query string or header of the HTTP request.

In the query string:

http://192.168.1.1:5000/webman/3rdparty/DownloadStation/webUI/downloadman.cgi?SynoToken=9WuK4Cf50Vw7Q

In the request header:

X-SYNO-TOKEN:9WuK4Cf50Vw7Q

The value of SynoToken can be obtained from login.cgi if the user is logged in.

Request:

http://192.168.1.1:5000/webman/login.cgi

Response:

{"SynoToken": "9WuK4Cf50Vw7Q", "result": "success", "success": true}

If your application is based on ExtJs of DSM, please include dsmtoken.cgi in your header section.

<header>
 <script src="/webman/dsmtoken.cgi" > </script>
</header>

Once the dsmtoken.cgi is included, Ext.Ajax.Request, Ext.data.Connection, Ext.form.basicForm and Ext.urlAppend will append SynoToken to the HTTP request automatically.

<script>
 Ext.Ajax.Request({ … }) // add SynoToken at event 'beforerequest'
 Ext.data.Connection({ … }) // add SynoToken at event 'beforerequet'
 new Ext.form.basicForm({ … }) // add SynoToken at event 'beforeaction'
// Ext.urlAppend will add SynoToken internally
 url = Ext.urlAppend('http://192.168.1.1', Ext.urlEncode({ … }));
</script>