{"_id":"550ada9e921b7d0d0022888e","project":"550a379f635c660d00527fd8","__v":8,"version":{"_id":"550ada9d921b7d0d00228876","forked_from":"550a3b2542fff40d00ae5ffb","project":"550a379f635c660d00527fd8","__v":3,"createdAt":"2015-03-19T14:18:05.245Z","releaseDate":"2015-03-19T14:18:05.245Z","categories":["550ada9d921b7d0d00228877","550ada9d921b7d0d00228878","550ada9d921b7d0d00228879","550ada9d921b7d0d0022887a","550ada9d921b7d0d0022887b","550ada9d921b7d0d0022887c","550ada9d921b7d0d0022887d","5523e61e71c0542100993493","55246f72ccc28a0d0062c560"],"is_deprecated":false,"is_hidden":false,"is_beta":false,"is_stable":true,"codename":"","version_clean":"3.0.0","version":"3.0.0"},"category":{"_id":"550ada9d921b7d0d00228878","version":"550ada9d921b7d0d00228876","__v":4,"pages":["550ada9e921b7d0d0022888c","550ada9e921b7d0d0022888d","550ada9e921b7d0d0022888e","550ada9e921b7d0d0022888f","55121961a575b32f007c79f1","55297f32b316811900149fac","5595b553f4437019002888fc"],"project":"550a379f635c660d00527fd8","sync":{"url":"","isSync":false},"reference":false,"createdAt":"2015-03-19T02:45:48.278Z","from_sync":false,"order":2,"slug":"authentication","title":"Authentication"},"user":"550a378e635c660d00527fd7","updates":[],"next":{"pages":[],"description":""},"createdAt":"2015-03-19T02:53:13.855Z","link_external":false,"link_url":"","githubsync":"","sync_unique":"","hidden":false,"api":{"results":{"codes":[]},"auth":"required","params":[],"url":""},"isReference":false,"order":3,"body":"[block:callout]\n{\n  \"type\": \"info\",\n  \"body\": \"- Application must be of type **explicit** or **installed**.\\n- Should only be used with a web server (or a client that can keep a secret *secret*).\\n\\nRead the [OAuth Overview](doc:oauth-overview) for more information.\",\n  \"title\": \"Requirements & Notes\"\n}\n[/block]\nUnlike [Script based OAuth](doc:oauth-script), Explicit OAuth can not authenticate using a username & password. The main difference is that the program must wait for a user of the application to authenticate with reddit and get back an authorization code before moving on.\n\n## Initial Config\n\nIn the initial config, provide the OAuth settings for an application:\n[block:code]\n{\n  \"codes\": [\n    {\n      \"code\": \"var Snoocore = require('snoocore');\\n\\nvar reddit = new Snoocore({\\n  userAgent: 'your apps user agent',\\n  oauth: { \\n    type: 'explicit', // required when using explicit OAuth\\n    mobile: true, // defaults to false.\\n    duration: 'permanent', // defaults to 'temporary'\\n    key: 'client_id from reddit', \\n    // A secret is only needed if your app is type 'web'\\n    secret: 'client_secret from reddit', \\n    redirectUri: 'redirectUri set for your app',\\n    // make sure to set all the scopes you need.\\n    scope: [ 'flair', 'identity' ] \\n  }\\n});\\t\",\n      \"language\": \"javascript\"\n    }\n  ]\n}\n[/block]\n### `oauth.secret`\n\nThis is only needed for web applications. Leave it an empty string, or leave it out all together for installed applications.\n\n### `oauth.mobile` \n\nOptional. Set mobile to true to send the user to the mobile reddit website for authentication.\n\n### `oauth.duration`\n\nIf the goal of the application is to do long term tasks (more than an hour) set this value to `'permanent'`.\n\nRead the section on [authorization](https://github.com/reddit/reddit/wiki/OAuth2#authorization) in the reddit OAuth documentation for more information.\n\n\n## Getting the authentication URL\n[block:code]\n{\n  \"codes\": [\n    {\n      \"code\": \"var state = 'foobar';\\nvar authUrl = reddit.getAuthUrl(state);\",\n      \"language\": \"javascript\"\n    }\n  ]\n}\n[/block]\nFor CSRF prevention, set a `state`. This field is optional. Read more on this below.\n\n## Handling the response\n\nAfter the user visits the URL that `reddit.getAuthUrl` generates, they will be presented with the option to allow or deny the app. After they allow (or deny) the application, reddit will redirect the user back to the given `redirectUri` (set in the initial config)  with the following url parameters:\n\n - **error** - something went wrong with the request\n - **code** - the `authorizationCode` (used below)\n - **state** - should be the same string that was set in the `reddit.getAuthUrl` function (if it was set).\n\nTo handle this redirect from reddit, there needs to be something up and running (e.g. a web server) at the `redirectUri` to intercept the above values and interpret them.\n\nFor CSRF prevention, check that the `state` in the url parameters is the same as the `state` specified when generating the authentication url in `reddit.getAuthUrl`.\n\n## Authenticating with the returned code\n\nWith the `authorizationCode` in the response from reddit, make one more call to get back authorization data:\n[block:code]\n{\n  \"codes\": [\n    {\n      \"code\": \"var AUTHORIZATION_CODE = '??'; /* url parameter \\\"code\\\", see above */\\nvar RETURNED_STATE = '??'; /* url parameter \\\"state\\\", see above */\\n\\n// Exit if the state given is invalid. This is an optional\\n// check, but is recommended if you set a state in \\n// `reddit.getExplicitAuthUrl`\\nif (RETURNED_STATE !== state) {\\n  console.error('State is not the same as the one set!');\\n  process.exit(1);\\t\\t\\t\\t\\t\\t\\t\\t\\t\\t\\t\\t\\t\\t\\t\\t  \\n}\\n\\n// Authenticate with reddit by passing in the authorization code from the response\\nreddit.auth(AUTHORIZATION_CODE).then(function(refreshToken) {\\n  // The refreshToken will be defined if in the initial\\n  // config `duration: 'permanent'`\\n  // Otherwise if using a 'temporary' duration it can be ignored.\\n  \\n  // Make an OAuth call to show that it is working\\n  return reddit('/api/v1/me').get();\\n})\\n.then(function(data) {\\n  console.log(data); // Log the response\\n});\",\n      \"language\": \"javascript\"\n    }\n  ]\n}\n[/block]\nSnoocore is now successfully authenticated with OAuth.\n\n## Refresh Tokens & Re-Authenticating\n\nIf the goal is to have an app that will run for more than an hour set `duration: 'permanent'` in the OAuth section of the initial config. This will allow Snoocore to automatically refresh the `access_token` when it expires after an hour of continuous use.\n\nHowever, the refresh token is not persistent. If an application stops and starts, Snoocore will need to be provided a refresh token via `reddit.refresh`.\n\nWhen authenticating for the first time with `reddit.auth` (see previous section) it will provide a refreshToken. \n[block:code]\n{\n  \"codes\": [\n    {\n      \"code\": \"reddit.auth(AUTHORIZATION_CODE).then(function(REFRESH_TOKEN) {\\n  // Save the REFRESH_TOKEN to a database / etc. for use\\n  // in `reddit.refresh` at a later time.\\n});\",\n      \"language\": \"javascript\"\n    }\n  ]\n}\n[/block]\nWhenever you want to authenticate with that user in the future call:\n[block:code]\n{\n  \"codes\": [\n    {\n      \"code\": \"reddit.refresh(SAVED_REFRESH_TOKEN).then(function() {\\n  // we are authenticated, make a call\\n  return reddit('/api/v1/me').get();\\n});\",\n      \"language\": \"javascript\"\n    }\n  ]\n}\n[/block]\nThere won't be a need to use the `reddit.auth` call to authenticate a user again unless they have revoked access to the application.\n\n## De-Authenticating\n\n**Revoking the access token**\n\nA function `reddit.deauth` is provided which will revoke the `access_token` for the current authenticated user.\n[block:code]\n{\n  \"codes\": [\n    {\n      \"code\": \"var deauthPromise = reddit.deauth();\",\n      \"language\": \"javascript\"\n    }\n  ]\n}\n[/block]\nGenerally it is a good idea to call this every time the application is finished with the users data. To re-authenticate call `reddit.refresh` (see previous section).\n\n**Revoking the refresh token**\n\nTo revoke the `refresh_token`, pass in the current refresh token in:\n[block:code]\n{\n  \"codes\": [\n    {\n      \"code\": \"var deauthPromise = reddit.deauth(REFRESH_TOKEN);\",\n      \"language\": \"javascript\"\n    }\n  ]\n}\n[/block]\nNote that this will revoke all `access_tokens` associated with this refresh token. It will not be possible to use the current refresh token to get new access_tokens (e.g. re-authenticate with `reddit.refresh`).\n\n### Renewing authentication for `duration: 'temporary'`\n\nIf the app does not use `duration: \"permanent\"` then it will **not** have a refresh token available when authenticating. It is possible to listen for an event and have the user re-authenticate with the application. For more information on this view the [Events](doc:events) documentation.","excerpt":"","slug":"oauth-explicit","type":"basic","title":"Explicit based OAuth"}

Explicit based OAuth


[block:callout] { "type": "info", "body": "- Application must be of type **explicit** or **installed**.\n- Should only be used with a web server (or a client that can keep a secret *secret*).\n\nRead the [OAuth Overview](doc:oauth-overview) for more information.", "title": "Requirements & Notes" } [/block] Unlike [Script based OAuth](doc:oauth-script), Explicit OAuth can not authenticate using a username & password. The main difference is that the program must wait for a user of the application to authenticate with reddit and get back an authorization code before moving on. ## Initial Config In the initial config, provide the OAuth settings for an application: [block:code] { "codes": [ { "code": "var Snoocore = require('snoocore');\n\nvar reddit = new Snoocore({\n userAgent: 'your apps user agent',\n oauth: { \n type: 'explicit', // required when using explicit OAuth\n mobile: true, // defaults to false.\n duration: 'permanent', // defaults to 'temporary'\n key: 'client_id from reddit', \n // A secret is only needed if your app is type 'web'\n secret: 'client_secret from reddit', \n redirectUri: 'redirectUri set for your app',\n // make sure to set all the scopes you need.\n scope: [ 'flair', 'identity' ] \n }\n});\t", "language": "javascript" } ] } [/block] ### `oauth.secret` This is only needed for web applications. Leave it an empty string, or leave it out all together for installed applications. ### `oauth.mobile` Optional. Set mobile to true to send the user to the mobile reddit website for authentication. ### `oauth.duration` If the goal of the application is to do long term tasks (more than an hour) set this value to `'permanent'`. Read the section on [authorization](https://github.com/reddit/reddit/wiki/OAuth2#authorization) in the reddit OAuth documentation for more information. ## Getting the authentication URL [block:code] { "codes": [ { "code": "var state = 'foobar';\nvar authUrl = reddit.getAuthUrl(state);", "language": "javascript" } ] } [/block] For CSRF prevention, set a `state`. This field is optional. Read more on this below. ## Handling the response After the user visits the URL that `reddit.getAuthUrl` generates, they will be presented with the option to allow or deny the app. After they allow (or deny) the application, reddit will redirect the user back to the given `redirectUri` (set in the initial config) with the following url parameters: - **error** - something went wrong with the request - **code** - the `authorizationCode` (used below) - **state** - should be the same string that was set in the `reddit.getAuthUrl` function (if it was set). To handle this redirect from reddit, there needs to be something up and running (e.g. a web server) at the `redirectUri` to intercept the above values and interpret them. For CSRF prevention, check that the `state` in the url parameters is the same as the `state` specified when generating the authentication url in `reddit.getAuthUrl`. ## Authenticating with the returned code With the `authorizationCode` in the response from reddit, make one more call to get back authorization data: [block:code] { "codes": [ { "code": "var AUTHORIZATION_CODE = '??'; /* url parameter \"code\", see above */\nvar RETURNED_STATE = '??'; /* url parameter \"state\", see above */\n\n// Exit if the state given is invalid. This is an optional\n// check, but is recommended if you set a state in \n// `reddit.getExplicitAuthUrl`\nif (RETURNED_STATE !== state) {\n console.error('State is not the same as the one set!');\n process.exit(1);\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t \n}\n\n// Authenticate with reddit by passing in the authorization code from the response\nreddit.auth(AUTHORIZATION_CODE).then(function(refreshToken) {\n // The refreshToken will be defined if in the initial\n // config `duration: 'permanent'`\n // Otherwise if using a 'temporary' duration it can be ignored.\n \n // Make an OAuth call to show that it is working\n return reddit('/api/v1/me').get();\n})\n.then(function(data) {\n console.log(data); // Log the response\n});", "language": "javascript" } ] } [/block] Snoocore is now successfully authenticated with OAuth. ## Refresh Tokens & Re-Authenticating If the goal is to have an app that will run for more than an hour set `duration: 'permanent'` in the OAuth section of the initial config. This will allow Snoocore to automatically refresh the `access_token` when it expires after an hour of continuous use. However, the refresh token is not persistent. If an application stops and starts, Snoocore will need to be provided a refresh token via `reddit.refresh`. When authenticating for the first time with `reddit.auth` (see previous section) it will provide a refreshToken. [block:code] { "codes": [ { "code": "reddit.auth(AUTHORIZATION_CODE).then(function(REFRESH_TOKEN) {\n // Save the REFRESH_TOKEN to a database / etc. for use\n // in `reddit.refresh` at a later time.\n});", "language": "javascript" } ] } [/block] Whenever you want to authenticate with that user in the future call: [block:code] { "codes": [ { "code": "reddit.refresh(SAVED_REFRESH_TOKEN).then(function() {\n // we are authenticated, make a call\n return reddit('/api/v1/me').get();\n});", "language": "javascript" } ] } [/block] There won't be a need to use the `reddit.auth` call to authenticate a user again unless they have revoked access to the application. ## De-Authenticating **Revoking the access token** A function `reddit.deauth` is provided which will revoke the `access_token` for the current authenticated user. [block:code] { "codes": [ { "code": "var deauthPromise = reddit.deauth();", "language": "javascript" } ] } [/block] Generally it is a good idea to call this every time the application is finished with the users data. To re-authenticate call `reddit.refresh` (see previous section). **Revoking the refresh token** To revoke the `refresh_token`, pass in the current refresh token in: [block:code] { "codes": [ { "code": "var deauthPromise = reddit.deauth(REFRESH_TOKEN);", "language": "javascript" } ] } [/block] Note that this will revoke all `access_tokens` associated with this refresh token. It will not be possible to use the current refresh token to get new access_tokens (e.g. re-authenticate with `reddit.refresh`). ### Renewing authentication for `duration: 'temporary'` If the app does not use `duration: "permanent"` then it will **not** have a refresh token available when authenticating. It is possible to listen for an event and have the user re-authenticate with the application. For more information on this view the [Events](doc:events) documentation.