Giter VIP home page Giter VIP logo

hapi-auth-bearer-token's People

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar

hapi-auth-bearer-token's Issues

Add support for authorization payload

In hapi authorization scheme is expected to return authenticate function, however the data stored in payload is then not available to the user. But the scheme can also return payload function which then can be used to use payload data during authorization.

I needed this functionality in one of the projects, therefore I already wrote the necessary code: #18
(however I didn't dig into the plugin structure, so maybe this can be (and should) written in other fashion)

Error 500 on invalid token

A request with an invalid token results in

{"statusCode":500,"error":"Internal Server Error","message":"An internal server error occurred"}

due to the line

            return h.unauthenticated(settings.unauthorized(message, settings.tokenType), { credentials, artifacts });

if is is changed to

            return h.unauthenticated(settings.unauthorized(message), { credentials, artifacts });

the statusCode is 401 as it should be.

Exception when allowChaining is true and the strategies are defined via default auth value

In our use case, we are trying to define two auth strategies to be validated one before other. Defining hapi-auth-bearer-token validation as the first one, we have seen that it is possible using the flag allowChaining. If the bearer token received in not a valid token, try the second one before saying that the token is not valid.

server.auth.strategy('simple', 'bearer-access-token', { allowChaining: true, validateFunc });
server.auth.strategy('jwt', 'jwt', jwtValidation);

It we define the strategies in each route, it works as we expected:

{
      method: 'GET',
      options: {
        auth: {
          strategies: ['simple', 'jwt'],
        },
     }
}

But if we try to define the strategies as the default ones, we face an exception:

server.auth.default({ strategies: ['simple', 'jwt'] });

The exception comes from the following line of the scheme definition:

const message = (settings.allowChaining && request.route.settings.auth.strategies.length > 1) ? null : 'Bad token';

strategies is undefined.

Could we add support for default option when we define multiple strategies ?

access to request in validate function?

would you be willing to entertain access to the request object in the validate function? either by changing the method signature or using call to bind request to this?

the scenario that i'm envisioning grants different access to different paths based on the bearer token.

thanks!

Suppres error stack thrown when unauthorized

Hi,
I am getting a lot of error stack in log whenever unauthorized attempt is made and I am wondering if there is a way to handle those error or suppress the verbose error log.

So this return callback(null, false); will produce the below

Debug: auth, unauthenticated, error, simple
    Error: Bad token
    at ... /node_modules/hapi-auth-bearer-token/lib/index.js:72:39

Make option allowQueryToken false by default.

When this module was created it was just more for allowing token parse by query token than header, but usage and configurability has grown since and should be treated as more secure by default now. As a result, all options for extra areas to parse security tokens should be specifically opt-in so the module is locked down to only header auth by default.

Double validation error

auth: {
strategies: ['admin','user']
},
The problem I met was the first admin to verify, but the second user was invalid.

Expose the bearer token validator to the server?

Hey thanks for this incredible plugin, I was wondering if it was possible to expose the validator logic to the hapi server. I have found useful to extend this module functionality for example with token validation functionality, to move all the token validation away into a plugin. Bell already does that.

What do you think? I can help with that if it is something that makes sense for you.

How to customize own error?

Hello,
I have used hapi-auth-bearer-token, it is working, but I want to ask something, is it possible to generate our own error message once authentication failed? instead of returning messages like this
{ "statusCode": 401, "error": "Unauthorized", "message": "Bad token", "attributes": { "error": "Bad token" }
if it is possible how? thanks.

An in-range update of hapi is breaking the build 🚨

Version 16.3.0 of hapi just got published.

Branch Build failing 🚨
Dependency hapi
Current Version 16.2.0
Type devDependency

This version is covered by your current version range and after updating it in your project the build failed.

As hapi is β€œonly” a devDependency of this project it might not break production or downstream projects, but β€œonly” your build or test tools – preventing new deploys or publishes.

I recommend you give this issue a high priority. I’m sure you can resolve this πŸ’ͺ

Status Details
  • ❌ continuous-integration/travis-ci/push The Travis CI build failed Details

Commits

The new version differs by 20 commits.

  • 1a41f15 Merge pull request #3479 from AJamesPhillips/docs-16.1.1
  • 3d4f0fc Merge pull request #3461 from hapijs/socket-destroy
  • ba95396 Merge pull request #3441 from kanongil/revise-normalize
  • 279def5 Cleanup for #3409
  • 241d7b0 Merge pull request #3409 from gordysc/master
  • d2de2e7 Merge pull request #3504 from kanongil/fix-flaky-test
  • 6469604 Fix flaky test from #3472
  • 081f365 Simplify request host update
  • ca1b9aa Update host info on request.setUrl(). Closes #3430
  • c315706 Fix several request.url property issues
  • eb0a606 Minor changes to docs
  • 760f433 Add partition and dropOnError to API docs
  • 79720b9 Partially revert c88266e5
  • 2d2dfaf Add link to server cache options
  • 8da535a Docs update Might instead of May. Add other response methods of hold, send, takeover

There are 20 commits in total.

See the full diff

Not sure how things should work exactly?

There is a collection of frequently asked questions and of course you may always ask my humans.


Your Greenkeeper Bot 🌴

An in-range update of joi is breaking the build 🚨

Version 13.5.0 of joi was just published.

Branch Build failing 🚨
Dependency joi
Current Version 13.4.0
Type dependency

This version is covered by your current version range and after updating it in your project the build failed.

joi is a direct dependency of this project, and it is very likely causing it to break. If other packages depend on yours, this update is probably also breaking those in turn.

Status Details
  • ❌ continuous-integration/travis-ci/push: The Travis CI build could not complete due to an error (Details).

Commits

The new version differs by 21 commits.

  • 63492d4 13.5.0
  • 334c1e3 Cleanup for #1532.
  • 3372df0 Merge pull request #1532 from rokoroku/patch-1
  • 3414eb7 Update documentation for string.trim([enabled])
  • 0a82b61 Add assertion for string.trim()
  • bcc5f12 Cleanup for #1510.
  • 8b39221 Merge pull request #1510 from Shudrum/dataUri
  • 2391f72 Cleanup for #1487.
  • 7aa0df0 Merge pull request #1487 from BolajiOlajide/ft-allow-square-brackets-param-url-validator
  • 37d3588 Add createError documentation. Fixes #999.
  • 77012b2 Add enabled flag to string.trim()
  • 8eefd0d Don't initialize options uselessly
  • 52fd99b Padding option added to dataUri like base64
  • 840eaad Move the dataUri tests after the base64 one
  • 83eb8eb Merge pull request #1511 from WesTyler/unique_ignoreUndefined_#1498

There are 21 commits in total.

See the full diff

FAQ and help

There is a collection of frequently asked questions. If those don’t help, you can always ask the humans behind Greenkeeper.


Your Greenkeeper Bot 🌴

Error: Unknown authentication strategy simple in /

Copy & paste the example on the README and run it with node

Hapi v15.1.1

apparently now register truly runs async, so trying to register routes before it finishes to register the auth strategy fails, could you update your example?

An in-range update of boom is breaking the build 🚨

The dependency boom was updated from 7.2.0 to 7.2.1.

🚨 View failing branch.

This version is covered by your current version range and after updating it in your project the build failed.

boom is a direct dependency of this project, and it is very likely causing it to break. If other packages depend on yours, this update is probably also breaking those in turn.

Status Details
  • ❌ continuous-integration/travis-ci/push: The Travis CI build failed (Details).

Commits

The new version differs by 4 commits.

See the full diff

FAQ and help

There is a collection of frequently asked questions. If those don’t help, you can always ask the humans behind Greenkeeper.


Your Greenkeeper Bot 🌴

Error: Unknown authentication strategy

I am trying to use this module to enable bearer token on my app. However, I am getting the error shown in the title.

I have been stuck for days now. Hoping anyone could help me.

I have user.js route

module.exports = [{
    'method' : 'GET',
    'path' : '/v1/users',
    'config' : {
        'handler' : function (request, reply) {
            User.find(function (error, data) {
                if (!error) {
                    reply(data)
                        .code(200)
                }
            });
        },
        'auth' : 'simple'
    }
}];

Now, inside my server.js,

Server.register([{
    'register' : require('hapi-auth-bearer-token')
}, {
    'register' : require('./api')
}], function (error) {
    if (!error) {
        Server.auth.strategy('simple', 'bearer-access-token', {
            'validateFunc' : function (token, callback) {
                if (token === "1234") {
                    callback(null, true, {
                        'token' : token
                    })
                } else {
                    callback(null, false, {
                        'token' : token
                    })
                }
            }
        });

        Server.start(function () {
            console.log('info', 'Server running at ' + Server.info.uri);
        });
    }
});

But I get Error: Unknown authentication strategy: simple in path: /v1/users

Complete error message:

    at Object.exports.assert (/var/nodevagrant/project/Interest/node_modules/hapi/node_modules/hoek/lib/index.js:663:11)
    at /var/nodevagrant/project/Interest/node_modules/hapi/lib/auth.js:139:14
    at Array.forEach (native)
    at internals.Auth._setupRoute (/var/nodevagrant/project/Interest/node_modules/hapi/lib/auth.js:136:24)
    at new module.exports.internals.Route (/var/nodevagrant/project/Interest/node_modules/hapi/lib/route.js:131:47)
    at internals.Connection._addRoute (/var/nodevagrant/project/Interest/node_modules/hapi/lib/connection.js:342:17)
    at internals.Connection._route (/var/nodevagrant/project/Interest/node_modules/hapi/lib/connection.js:334:18)
    at internals.Plugin._apply (/var/nodevagrant/project/Interest/node_modules/hapi/lib/plugin.js:432:14)
    at internals.Plugin.route (/var/nodevagrant/project/Interest/node_modules/hapi/lib/plugin.js:407:10)
    at Object.exports.register (/var/nodevagrant/project/Interest/api/index.js:8:9)

Npm fails to load plugin. Fails with: The header content contains invalid characters

I am new to npm and node. I was following an example in hapi.js in Action and ran into this error. I don't know if it is just because I downloaded the latest Node and NPE and there is a compatibility issue or if there might some mistake in the code.

npm ERR! Linux 4.2.0-27-generic
npm ERR! argv "/usr/bin/nodejs" "/usr/bin/npm" "install" "–-save" "hapi-auth-bearer-token"
npm ERR! node v5.6.0
npm ERR! npm v3.6.0

npm ERR! The header content contains invalid characters

Can't use auth with CORS

Here's my route:

    syncImage: {
        handler: function(req, reply) {
            server.methods.uploadImage(req, reply);
        },
        payload:{
            maxBytes:209715200,
            output:'stream',
            parse: false
        },
        auth: 'simple',
        cors: {
            origin: ['*'],
            credentials: true,
            matchOrigin: false
        },
        id: 'syncImage'
    },

And in the client:

            var form = document.getElementById("imageForm");
            var formData = new FormData(form);
            var imageInput = document.getElementById("imageInput");
            var file = imageInput.files[0];
            formData.append('file', file);

            var xhr = new XMLHttpRequest();
            if ('withCredentials' in xhr) {
              xhr.open('POST', form.getAttribute('action'), true);
              xhr.setRequestHeader("Authorization", "Bearer 1234");
              xhr.withCredentials = "true";
              xhr.onreadystatechange = function (aEvt) {
                if (xhr.readyState == 4) {
                   if(xhr.status == 200) {
                      if (xhr.responseText === 'isFileOk') {
                        isFileUploaded = true;
                        imagePath = 'http://localhost:3000/uploads/' + file.name;
                        $('#saveOrder').removeAttr('disabled');
                        $('#wrapper').css('display', 'none');  
                      }
                   } else {
                    isFileUploaded = false;
                     alert("Error !");
                   }
                }
              }
              xhr.send(formData);
              return false;
            }

Am I missing something?

Regards

reply().code(500) is not supported

Hello.

I have a pb when i pass a error (boom) in callback of validateFunc

if (error) {
    return callback(error, false, null);
}

trow a error

Debug: hapi, internal, implementation, error
    TypeError: Cannot call method 'code' of undefined
    at /var/myproject/node_modules/hapi-auth-bearer-token/lib/index.js:47:119

and when a console.log reply i can't find code function

{ [Function]
  _root: [Function],
  view: [Function],
  file: [Function],
  proxy: [Function],
  close: [Function],
  state: [Function],
  unstate: [Function],
  redirect: [Function] }

I make something wrong ?

An in-range update of hapi is breaking the build 🚨

The devDependency hapi was updated from 17.6.0 to 17.6.1.

🚨 View failing branch.

This version is covered by your current version range and after updating it in your project the build failed.

hapi is a devDependency of this project. It might not break your production code or affect downstream projects, but probably breaks your build or test tools, which may prevent deploying or publishing.

Status Details
  • ❌ continuous-integration/travis-ci/push: The Travis CI build failed (Details).

Commits

The new version differs by 6 commits.

  • 6ebf21c Add node 11
  • 082e5d8 override install
  • e16e5e1 17.6.1
  • 6da7a97 Update deps. Closes #3833. Closes #3834. Closes #3835. Closes #3836. Closes #3837. Closes #3838. Closes #3839. Closes #3840. Closes #3841. Closes #3841. Closes #3842. Closes #3843. Closes #3844. Closes #3845. Closes #3846. Closes #3847. Closes #3848. Closes #3850. Closes #3851. Closes #3852. Closes #3853. Closes #3854. Closes #3855. Closes #3856
  • 7ffd301 Tweak test
  • ec1c830 Tweak test

See the full diff

FAQ and help

There is a collection of frequently asked questions. If those don’t help, you can always ask the humans behind Greenkeeper.


Your Greenkeeper Bot 🌴

Use joi schema to validate the authentication options.

github.com/hapijs/joi makes schemas much more readable, easier to test and reduce the likelihood of unintended bugs.

When this module was first written, it had one or two options, meaning it didn't really need a joi schema. This has since grown and it would now be worth adding a joi schema and validate this when registering an auth method.

Note: This doesn't add any performance hit per request, only on auth scheme registration, as the auth schema will only be validated when schema is registered.

This issue for new contributors, myself and @AdriVanHoudt are available to help work through this PR

An in-range update of joi is breaking the build 🚨

Version 13.1.0 of joi was just published.

Branch Build failing 🚨
Dependency joi
Current Version 13.0.2
Type dependency

This version is covered by your current version range and after updating it in your project the build failed.

joi is a direct dependency of this project, and it is very likely causing it to break. If other packages depend on yours, this update is probably also breaking those in turn.

Status Details
  • ❌ continuous-integration/travis-ci/push The Travis CI build could not complete due to an error Details

Commits

The new version differs by 7 commits.

  • e2498c6 13.1.0
  • 2cc5c28 Merge pull request #1386 from choffmeister/fix-object-pattern
  • 90c53ea Merge pull request #1389 from fauzanhilmi/master
  • b7b40d7 Fix typo in string.min & string.length docs
  • b992da4 Fix object pattern in combination with empty
  • 1075980 Fix messages documentation on key/label
  • cc53881 Add .editorconfig .npmrc and .nvmrc

See the full diff

FAQ and help

There is a collection of frequently asked questions. If those don’t help, you can always ask the humans behind Greenkeeper.


Your Greenkeeper Bot 🌴

Undefined token passed to validate function

In version 4.3.1 with default options, I noticed that when the Authorization header is just Bearer, the token parameter that is passed to the validate function is undefined. Looking through the code, it seems to me that this is the case for current master as well. Although this behavior is reasonable, I wonder if it would be more appropriate to reply with Boom.unauthorized? I don't see how not having a token should ever result in a successful authentication, so it would be convenient for the middleware to handle that case.

"Error 500, invalid token, data null" when recalling the previous token in Alamofire

I save my login token with UserDefault. Here is the code :

            AF.request(encodeURL, method: .post, parameters: nil, headers: headers, interceptor: nil)
            .responseString { response  in
                
                switch response.result{
                case .success(_):
                    if let json = response.value{
                        UserDefaults.standard.set(json, forKey: "token")
                        print("token saved \(json)")
                        // print((json as! [String : AnyObject]))
                        let homePage = self.storyboard?.instantiateViewController(identifier: "dashboard") as! HalamanUtama
                        self.navigationController?.pushViewController(homePage, animated: true)
                             
                    }
                    break
                case .failure(let error) :
                    print([error as! Error])
                    break
                    
                }
        }

I didn't make an Interceptor class(retry and adapt) func due to the the token is not expired yet. Then, I called the token that I've already saved before in this class. Here is the code :

       AF.request(url, method: .get, parameters: parameters, encoding: URLEncoding.default).responseJSON { (response) in
        switch response.result{
                           case .success(_):
                               if let json = response.value{
                                let defaults = UserDefaults.standard
                                defaults.value(forKey: "token")
                                   print("token saved \(json)")
                                   
                               }
                               break
                           case .failure(let error) :
                               print([error as! Error])
                               break
                               
                           }
    }

I got an error message : "error : 500, invalid token, data null". what's wrong with my code?

Strategy chaining

Currently it is not possible to chain strategies.
hapi docs: If the err does not include a message but does include a scheme name (e.g. Boom.unauthorized(null, 'Custom')), additional strategies will be attempted in order of preference. (under https://github.com/hapijs/hapi/blob/master/API.md#serverauthschemename-scheme)
And since on !isValid there is an unauthorized error with message, hapi will not try other strategies (

return reply(Boom.unauthorized('Bad token', options.tokenType), { credentials, artifacts });
)

Am I correct or am I just doing something wrong?

(background: as you may now I wrote https://github.com/Salesflare/hapi-auth-bearer-simple but now we do have a need for query param functionallity and at that point the gap seems to close to have 2 versions of this scheme type ;) )

An in-range update of hapi is breaking the build 🚨

Version 16.5.0 of hapi just got published.

Branch Build failing 🚨
Dependency hapi
Current Version 16.4.3
Type devDependency

This version is covered by your current version range and after updating it in your project the build failed.

As hapi is β€œonly” a devDependency of this project it might not break production or downstream projects, but β€œonly” your build or test tools – preventing new deploys or publishes.

I recommend you give this issue a high priority. I’m sure you can resolve this πŸ’ͺ

Status Details
  • ❌ continuous-integration/travis-ci/push The Travis CI build failed Details

Commits

The new version differs by 44 commits.

  • c89269a Update statehood. Closes #3551
  • 89e2b20 Update content. Closes #3550
  • ae12c40 Drain request stream on special handlers. Closes #3480
  • 355e8eb Switch to use Boom.boomify()
  • 5269898 Update boom. Closes #3548
  • f1709a3 Update joi. Closes #3545
  • f818228 Update deps. Closes #3543. Closes #3544
  • 2afa365 Handle emitter errors in request lifecycle. Closes #3464
  • 0f70551 Optimize request emitter creation. Closes #3532
  • 23d83dd Update podium. Closes #3542
  • d54e4f6 Update hoek. Closes #3541
  • 52a03b1 Cleanup for #3539
  • b947831 Merge pull request #3539 from jeff-kilbride/feature/payload_failAction_custom_handler
  • 9f8ea61 16.5.0
  • 832ed3d Merge pull request #3526 from hapijs/wildcard-debug

There are 44 commits in total.

See the full diff

Not sure how things should work exactly?

There is a collection of frequently asked questions and of course you may always ask my humans.


Your Greenkeeper Bot 🌴

An in-range update of code is breaking the build 🚨

Version 4.1.0 of code just got published.

Branch Build failing 🚨
Dependency code
Current Version 4.0.0
Type devDependency

This version is covered by your current version range and after updating it in your project the build failed.

As code is β€œonly” a devDependency of this project it might not break production or downstream projects, but β€œonly” your build or test tools – preventing new deploys or publishes.

I recommend you give this issue a high priority. I’m sure you can resolve this πŸ’ͺ

Status Details
  • ❌ continuous-integration/travis-ci/push The Travis CI build failed Details

Commits

The new version differs by 7 commits.

  • 2559673 v4.1.0
  • 38df73b print expected value in assertion messages
  • df0113b update dependencies and test Node 8
  • 461fdb1 add link to Hoek.contain() from includes()
  • 3d9dfc3 add NaN() assertion
  • d6f7d4b test Node v7 on travis
  • c11a9d3 update dependencies

See the full diff

Not sure how things should work exactly?

There is a collection of frequently asked questions and of course you may always ask my humans.


Your Greenkeeper Bot 🌴

Support for Multiple Authorization header fields

I have a need to support multiple Authorization header fields. e.g.

Authorization: FD AF6C74D1-BBB2-4171-8EE3-7BE9356EB018; Bearer 12345678

The current code only allows a single authorization field: Authorization: Bearer xxx

v6 Release Notes

hapi-auth-bearer-token

Important Note: v6 Drops support for hapi < v17 and Node < 8, due to the nature of the hapi v17 rewrite: hapijs/hapi#3658.

breaking changes:

  • hapi versions below v17 are no longer support from version 6 of this module.
  • validateFunc is renamed to validate. The Func suffix was an old convention to signify a function to be passed in here. This much cleaner and less intimidating to new users.
  • unauthorizedFunc is renamed to unauthorized. Same reasoning as validateFunc.
  • validate function signature function (token, callback) becomes [async] function(request, token, h).
    • validate must now return an object containing the auth details, as opposed to passing this information via callback used in previous versions. There is an example of this in the project README
    • The request object has been added to the function signature as previously request could only be accessed via this to avoid breaking changes. This was inconsistent and has been fixed in this release.

Please note: as part of changes with in hapi v17, server.auth.default('simple'); must now be used when setting a default auth strategy. Default strategies can no longer be set when calling server.auth.strategy. Please be careful with this.

if validation fails, please make credentials object to be optional

Lets assume in the validate function the validity is proven to be wrong. The plugin still expects a credentials object to be passed even if isValid:false.
Even though the function is called with the response toolkit, using something like return h.response().code(401) does not work as expected.

Can user info be passed from tokeninfo call to hapi plugins which are seneca modules?

Please find the code below. The plugins we are using as modules have seneca routes. In validateFunc we are calling tokeninfo where we get user's info. We need help to understand how to pass the user's info over to the plugins/modules.


server.register(plugins, (err) => {

         server.auth.strategy('simple', 'bearer-access-token', true, {
             allowQueryToken: true, 
             allowMultipleHeaders: false, 
             accessTokenName: 'token',    
             validateFunc: function (token, callback) {    
               Wreck.get(TOKEN_URL+'/tokeninfo?access_token=' + token,
               { json: 'force' }, function (err, response, payload) {    
                 if(response.statusCode == 200) {
/*********************/
//here i got the user id/info 
//but how to pass it into plugins as it is in callback  function?
                   return callback(null, true, { token: token });
                 } else {
                   return callback(null, false, { token: token });
                 }
               });
           }
             });
       });

Thank you in advance if you can please help.

An in-range update of code is breaking the build 🚨

The devDependency code was updated from 5.2.0 to 5.2.1.

🚨 View failing branch.

This version is covered by your current version range and after updating it in your project the build failed.

code is a devDependency of this project. It might not break your production code or affect downstream projects, but probably breaks your build or test tools, which may prevent deploying or publishing.

Status Details
  • ❌ continuous-integration/travis-ci/push: The Travis CI build failed (Details).

Commits

The new version differs by 3 commits.

  • b458d13 v5.2.1
  • 03d7b92 update deps and test on node 11
  • 0dfe00e Add the correct thrownAt() location when using expect().to.reject()

See the full diff

FAQ and help

There is a collection of frequently asked questions. If those don’t help, you can always ask the humans behind Greenkeeper.


Your Greenkeeper Bot 🌴

The validation method is crashing when calling from mongoDb

Sorry to bother am new Hapijs and am trying your plugin using mongo as back end when i look for the user using User.findById in the validation method i get this exception:tried everything but here i am.

Debug: internal, implementation, error 
TypeError: Property '_next' of object function (err, response, data) {

    reply._data = data;                 // Held for later
    return reply.response(err !== null && err !== undefined ? err : response);
} is not a function
at Function.internals.continue (E:\newCode\webApps\node_modules\hapi\lib\reply.js:102:10)
at E:\newCode\webApps\node_modules\hapi-auth-bearer-token\lib\index.js:65:42
at Promise.<anonymous> (E:\newCode\webApps\app\utils\autho.js:18:32)
at Promise.<anonymous> (E:\newCode\webApps\node_modules\mongoose\node_modules\mpromise\lib\promise.js:177:8)
at Promise.emit (events.js:95:17)
at Promise.emit (E:\newCode\webApps\node_modules\mongoose\node_modules\mpromise\lib\promise.js:84:38)
at Promise.fulfill (E:\newCode\webApps\node_modules\mongoose\node_modules\mpromise\lib\promise.js:97:20)
at E:\newCode\webApps\node_modules\mongoose\lib\query.js:1394:13
at model.Document.init (E:\newCode\webApps\node_modules\mongoose\lib\document.js:250:11)
at completeOne (E:\newCode\webApps\node_modules\mongoose\lib\query.js:1392:10)

This the method used in the validation

    function (token, callback) {
    if (token) {
        try {
            var decodedToken = jwt.decode(token, config.secretToken);
            if (decodedToken.exp && decodedToken.exp <= Date.now()) {
                return callback(null, false);
            }
            User.findById(decodedToken.iss, '_id uName',
                function (err, users) {
                    if (!err) {
                        return callback(null, true, users);
                    }
                });

        } catch (err) {
            return callback(null, false);
        }
    }
    return callback(null, false);
    }

Thanks

Required plugin

Hi,

Thanks for your project I appreciate it πŸ‘πŸ» I have a problem getting it to work though, I'm trying to add authentication to an existing API Hapi project. This is my implementation of server.register:

server.register(
  [
    inert,
    vision,
    {
      register: hapiSwagger,
      options: swaggerOptions
    },
    authBearer
  ],
  function (error) {
    server.auth.strategy('simple', 'bearer-access-token', {
      allowQueryToken: true,
      validate: async (request, token, h) => {

        // TODO: Validate token
        const isValid = token === '1234';
        const credentials = { token };
        const artifacts = { test: 'info' };
        return { isValid, credentials, artifacts };
      }
    });
    server.auth.default('simple');
  }
);

And this is the error I'm getting:

if (plugin.register.register) {                             // Required plugin
                            ^

TypeError: Cannot read property 'register' of undefined
    at module.exports.internals.Server.internals.Plugin.register

I hope you can help me out.
Cheers

can we skip some routes from authentication

Hello,

we are using AuthBearer plugin for authentication. can we skip some routes from the authetication?
something like

auth{
strategy: ""
} 

or
auth : false

Thanks in advance.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    πŸ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. πŸ“ŠπŸ“ˆπŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❀️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.