Code Monkey home page Code Monkey logo

oauth2-client-js's Introduction

OAuth2 Client

Build Status Coverage Status Latest version Join the chat at https://gitter.im/zalando/oauth2-client-js

OAuth2 Client is a library to help you handle OAuth2 access and request tokens. It's for browser-only use (it came about because it was used for a single-page application), so it only includes the OAuth2 Implicit Grant flow.

Context/What OAuth2 Client Does

OAuth2 Client enables you to work with OAuth2-compliant APIs directly from the (browser) JS app. It encapsulates the gritty RFC parts, but leaves enough flexibility to be usable with any JS framework.

Others have created JavaScript OAuth 2.0 libraries like JSO, but OAuth2 Client makes fewer assumptions about how your application works (where the token is needed/used, when a redirect is desirable, etc.). It also makes handling of scopes very simple.

To-Do/Contribute

This project is looking primarily for users, but contributors are also welcome. If you'd like to help, here are some open to-do's:

  • Remove refresh token support
  • Add other grant flows that a non-confidential client is allowed to use
  • Write docs

Installation

NPM:

npm i --save @zalando/oauth2-client-js  

Bower:

bower install --save oauth2-client-js

Usage

A “provider” manages your tokens and knows how to handle responses from the authorization endpoint. Create a new provider like this:

var OAuth = require('@zalando/oauth2-client-js');
var google = new OAuth.Provider({
    id: 'google',   // required
    authorization_url: 'https://google.com/auth' // required
});

By default a provider will use the localStorage to save its tokens, but with storage you can pass anything that adheres to the Storage API.

Most of the time you will want to do two things: Request new tokens and check whether there are tokens available.

Requesting Tokens

To get a new access token, redirect the user to the authorization endpoint. The full URI is constructed like this:

// Create a new request
var request = new OAuth.Request({
    client_id: 'my_client_id',  // required
    redirect_uri: 'http://my.server.com/auth-answer'
});

// Give it to the provider
var uri = google.requestToken(request);

// Later we need to check if the response was expected
// so save the request
google.remember(request);

// Do the redirect
window.location.href = uri;

The auth endpoint will redirect the user back to the redirect_uri and encode its response in the URI fragment. Since your application completely lost its state by now, you may want to pass metadata to the request. It will be stored along with the request and loaded later on. E.g. your current application route could go in there.

To parse the response out of the uri, do it like this:

var response = google.parse(window.location.hash);

This will either throw an error (e.g. when the state property doesn’t match both in request and response) or return the response. It will have metadata from the request on it. Access and refresh tokens are now available on the provider.

Refresh Tokens

They are not in the RFC spec, but you can use them as well (if your server supports them). To issue a refresh request:

var uri = google.refreshToken();
yourHttpLibrary
    .get(uri)
    .then(function(response) {
        google.handleRefresh(response.body);
        // your tokens are now diamonds
        // ehm, up to date.
    });

Get Tokens

google.getAccessToken() and google.getRefreshToken().

License

Apache 2.0 as stated in the LICENSE.

oauth2-client-js's People

Contributors

deteam avatar fokusferit avatar fragsalat avatar gitter-badger avatar lapanti avatar leoaref avatar lietu avatar marcbachmann avatar prayerslayer avatar schlessera avatar

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  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

oauth2-client-js's Issues

ReferenceError: window is not defined

we are getting window is not defined error as below.

ReferenceError: window is not defined at new Provider (webpack:///./src/provider.js?:42:86) at Object.<anonymous> (/home/Demo-App/demo/tmp/webpack:/src/routes/requireAuthentication.js:10:20) at webpack_require (/home/Demo-App/demo/tmp/webpack:/webpack/bootstrap 4f5669005e928a572010:19:1) at Object.exports.__esModule (/home/Demo-App/demo/tmp/webpack:/src/routes.js:15:1) at webpack_require (/home/Demo-App/demo/tmp/webpack:/webpack/bootstrap 4f5669005e928a572010:19:1) at Object.<anonymous> (/home/Demo-App/demo/tmp/webpack:/server.babel.js:9:1) at webpack_require (/home/Demo-App/demo/tmp/webpack:/webpack/bootstrap 4f5669005e928a572010:19:1) at Object.<anonymous> (/home/Demo-App/demo/tmp/bundle.js:50:19) at webpack_require (/home/Demo-App/demo/tmp/webpack:/webpack/bootstrap 4f5669005e928a572010:19:1) at /home/Demo-App/demo/tmp/webpack:/webpack/bootstrap 4f5669005e928a572010:39:1

I receive a window is not defined error at

var provider = new OAuth.Provider({ 
id: 'google', // required 
authorization_url: 'https://google.com/auth' // required
 }); 

our package json versions are as below.

"oauth2-client-js": "0.0.15", 
"react": "^15.4.0", 
"react-dom": "^15.4.0"

need to get the response as json.

Hello sir, i am using your package in vue cli 3 and trying to get data form github. But the problem is it returning response as html/text. How can i get the response as json?

Looking for new maintainer

I'm stepping down as a maintainer of this project, anyone wants to take over? It has around ~150 downloads/month and room for improvement (support for APIs not conforming to OAuth2 RFC, more grant flows).

Need some help

Trying to use the Javascript library as client side javascript and using the example:

var OAuth = require('@zalando/oauth2-client-js');
var google = new OAuth.Provider({
id: 'google', // required
authorization_url: 'https://google.com/auth' // required
});

But you cannot use require on client side javascript - am I missing something?

README.md is wrong

var response = google.parse(window.location.href);

Should use window.location.hash instead of window.location.href

Cannot set response_type

Hi, the authorization endpoint I am working with need to set response_type as "id_token token".
However I found the request I sent only had "token". Then I find out that in your OAuthImplicitRequest constructor, the response_type is overwrote to be "config.response_type = 'token';". It doesn't set nonce either. Would you consider to change it?

Clean up localStorage

After retrieving the access token, the client should forget the state, stored in the localStorage. This doesn't seem to work always (open https://yourturn.stups.zalan.do/ and look into the localStorage in the Browser's console, I have 83 state objects stored). Could you implement some sort of cleanup? In one of our projects I use the following:

let localStorage = window.localStorage;
for (let [key] of Object.entries(localStorage)) {
        if (key.startsWith(provider.id)) {
            window.localStorage.removeItem(key);
        }
}

Publish new version to npm

The most recent version of this library published to npmjs.org is v0.0.15, which is from May 2015. Releases
v0.0.16 and v0.0.17 are tagged in the source repo, but they were never published.

Can we please get a new version published to npm? Thanks.

Create TypeScript declaration files

As a user of TypeScript I would really like to be able to use this library with strong typing.

If it's okay with you guys I am willing to try and make the declaration files

Missing Resource Owner Password Credentials flow

According to the rfc, the ROPC flow can also be used when there is a high degree of trust between the resource owner and the client, as it's the case with a first-party app, where the use of an implicit flow would hurt UX. OAuth2-client lacks this ROPC flow.

Remove devtool: eval from distribution

At the moment, the distribution is built with eval, making minification in userland impossible. devtool: 'eval' should be removed, or enabled only for a development build

I am willing to attempt a PR. Also, do you think it is a good idea to update to Webpack 3 at the same time? I could do that also

Cleaning up localStorage

Remembering a request will create an entry in localStorage with the key as the concatenation of provider ID and state (uuid)
Only when the user completes the login flow, the entry is cleaned automatically by the library. If the user drops out of the login process and comes back later, a new request will be remembered and the old entry remains, thus gradually fill up localStorage

Could you give a recommended solution for this?

Accept optional values through constructor config

For all of the config keys, the provided values should be used instead of the default ones, if they were present in the config.

This way, something like the 'state' can be set to a specific value, instead of being "hardcoded".

Need help with response_type

Hello,

Im trying to get a quick oauth mock flow working and currently having issues with the response_type, here is the output of running oauth2-client-js:

Running on http://localhost:8282
        expected Client ID: dummy-client-id
        expected Client Secret: dummy-client-secret
        authorization endpoint: /auth/request/path
        access token endpoint: /access/token/request
        redirect URLs: http://mysite.test/#!/user/login/callback
GET /auth/request/path?response_type=token&scope=&client_id=dummy-client-id&redirect_uri=http%3A%2F%2Fmysite.test%2Fuser%2Flogin%2Fcallback&state=7acfebb1-c2d7-42ff-9cc3-925fa77d3a9b 401 Authorization: - Debug info: Error: expected response_type: "code" but actual: "token" Redirect: -

The website ends up of course in a 401. And this is how I'm building the redirect uri:

const provider = new OAuth.Provider({
    id: 'fake',  
    authorization_url: 'http://localhost:8282/auth/request/path'
});

const request = new OAuth.Request({
    client_id: 'dummy-client-id', 
    redirect_uri: 'http://mysite.test/user/login'
    , response_type: 'token'
})

const uri = provider.requestToken(request);
provider.remember(request);
window.location.href = uri;

Perhaps related to #28 but any clue on how to set this to code? or have the library accept token as its hardcoded in https://github.com/zalando-stups/oauth2-client-js/blob/master/src/request.js#L25

LinkedIn require's response_type to be "code"

When I try and use this with linked I get an error in the response hash.

Decoded for readability.

error=unsupported_response_type
error_description=We only support a response_type of "code" but you passed "token"

LinkedIn only works with code but the response type is hardcoded to token in request.js. If response types were configurable would this package work with the type code?

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.