Giter Club home page Giter Club logo

vue-authenticate's Introduction

[WARNING]: README file is currently in process of rewrite and will be released soon.

vue-authenticate

Join the chat at https://gitter.im/vuejs-auth/vue-authenticate

vue-authenticate is easily configurable solution for Vue.js that provides local login/registration as well as Social login using Github, Facebook, Google and other OAuth providers.

The best part about this library is that it is not strictly coupled to one request handling library like vue-axios. You will be able to use it with different libraries.

For now it is tested to work with vue-resource and axios (using vue-axios wrapper).

WARNING: From version 1.3.0 default request library is axios using vue-axios wrapper plugin.

This library was inspired by well known authentication library for Angular called Satellizer developed by Sahat Yalkabov. They share almost identical configuration and API so you can easily switch from Angular to Vue.js project.

Supported OAuth providers and configurations

  1. Facebook (https://github.com/dgrubelic/vue-authenticate/blob/master/src/options.js#L21)
  2. Google (https://github.com/dgrubelic/vue-authenticate/blob/master/src/options.js#L34)
  3. Github (https://github.com/dgrubelic/vue-authenticate/blob/master/src/options.js#L49)
  4. Instagram (https://github.com/dgrubelic/vue-authenticate/blob/master/src/options.js#L61)
  5. Twitter (https://github.com/dgrubelic/vue-authenticate/blob/master/src/options.js#L72)
  6. Bitbucket (https://github.com/dgrubelic/vue-authenticate/blob/master/src/options.js#L81)
  7. LinkedIn (https://github.com/dgrubelic/vue-authenticate/blob/master/src/options.js#L93)
  8. Microsoft Live (https://github.com/dgrubelic/vue-authenticate/blob/master/src/options.js#L106)

Installation

npm install vue-authenticate

Usage

import Vue from 'vue'
import VueAxios from 'vue-axios'
import VueAuthenticate from 'vue-authenticate'
import axios from 'axios';

Vue.use(VueAxios, axios)
Vue.use(VueAuthenticate, {
  baseUrl: 'http://localhost:3000', // Your API domain
  
  providers: {
    github: {
      clientId: '',
      redirectUri: 'http://localhost:8080/auth/callback' // Your client app URL
    }
  }
})

Email & password login and registration

new Vue({
  methods: {
    login: function () {
      this.$auth.login({ email, password }).then(function () {
        // Execute application logic after successful login
      })
    },

    register: function () {
      this.$auth.register({ name, email, password }).then(function () {
        // Execute application logic after successful registration
      })
    }
  }
})
<button @click="login()">Login</button>
<button @click="register()">Register</button>

Social account authentication

new Vue({
  methods: {
    authenticate: function (provider) {
      this.$auth.authenticate(provider).then(function () {
        // Execute application logic after successful social authentication
      })
    }
  }
})
<button @click="authenticate('github')">auth Github</button>
<button @click="authenticate('facebook')">auth Facebook</button>
<button @click="authenticate('google')">auth Google</button>
<button @click="authenticate('twitter')">auth Twitter</button>

Vuex authentication

Import and initialize all required libraries

// ES6 example
import Vue from 'vue'
import Vuex from 'vuex'
import VueAxios from 'vue-axios'
import { VueAuthenticate } from 'vue-authenticate'
import axios from 'axios';

Vue.use(Vuex)
Vue.use(VueAxios, axios)

const vueAuth = new VueAuthenticate(Vue.prototype.$http, {
  baseUrl: 'http://localhost:4000'
})
// CommonJS example
var Vue = require('vue')
var Vuex = require('vuex')
var VueAxios = require('vue-axios')
var VueAuthenticate = require('vue-authenticate')
var axios = require('axios');

Vue.use(Vuex)
Vue.use(VueAxios, axios)

// ES5, CommonJS example
var vueAuth = VueAuthenticate.factory(Vue.prototype.$http, {
  baseUrl: 'http://localhost:4000'
})

Once you have created VueAuthenticate instance, you can use it in Vuex store like this:

export default new Vuex.Store({
  
  // You can use it as state property
  state{
    isAuthenticated: false
  },

  // You can use it as a state getter function (probably the best solution)
  getters: {
    isAuthenticated () {
      return vueAuth.isAuthenticated()
    }
  },

  // Mutation for when you use it as state property
  mutations: {
    isAuthenticated (state, payload) {
      state.isAuthenticated = payload.isAuthenticated
    }
  },

  actions: {

    // Perform VueAuthenticate login using Vuex actions
    login (context, payload) {

      vueAuth.login(payload.user, payload.requestOptions).then((response) => {
        context.commit('isAuthenticated', {
          isAuthenticated: vueAuth.isAuthenticated()
        })
      })

    }
  }
})

Later in Vue component, you can dispatch Vuex state action like this

// You define your store logic here
import store from './store.js'

new Vue({
  store,

  computed: {
    isAuthenticated: function () {
      return this.$store.getters.isAuthenticated()
    }
  },

  methods: {
    login () {
      this.$store.dispatch('login', { user, requestOptions })
    }
  }
})

Custom request and response interceptors

You can easily setup custom request and response interceptors if you use different request handling library.

Important: You must set both request and response interceptors at all times.

/**
* This is example for request and response interceptors for axios library
*/

Vue.use(VueAuthenticate, {
  bindRequestInterceptor: function () {
    this.$http.interceptors.request.use((config) => {
      if (this.isAuthenticated()) {
        config.headers['Authorization'] = [
          this.options.tokenType, this.getToken()
        ].join(' ')
      } else {
        delete config.headers['Authorization']
      }
      return config
    })
  },

  bindResponseInterceptor: function () {
    this.$http.interceptors.response.use((response) => {
      this.setToken(response)
      return response
    })
  }
})

License

The MIT License (MIT)

Copyright (c) 2017 Davor Grubelić

Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

vue-authenticate's People

Contributors

dgrubelic avatar gitter-badger avatar ryancw avatar satterly 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  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

vue-authenticate's Issues

axios didnt work

I get Error

if (!this.$http) {
throw new Error('Request handler instance not found')
}

Facebook login error

Hi,

First of all, great solution. It's just what I was looking for.
I have a question regarding integration. I ran it and I get a error saying this:

Possible Unhandled Promise Rejection: Error: Authentication error occurred
Stack trace:
authenticate/</<@webpack-internal:///45:1285:14

I go the same when I did the integration based on the readme of vue-authenticate. My assumption is that I am not responding as expected on the callback url.

On the server side call Facebook does reply with all good, no issue, http 200.

What is the expected response there? Or, even better, have you seen the error before?

I am currently checking the code of vue-authenticate and do a step by step debug to try to figure it out, just wanted to start a thread here while I do that.

Fix bad assignment causing Vue.js minify error

ERROR in static/js/vendor.f26d5b56df0cc7f19039.js from UglifyJs Invalid assignment [./~/vue-authenticate/src/utils.js:27,0] [static/js/vendor.f26d5b56df0cc7f19039.js:9359,72]

This is caused by camelCase() regex callback function in utils.jsfile.

webpack build error

ERROR in static/js/0.74a7ac117d3159b549af.js from UglifyJs Unexpected token: name (joined) [./~/vue-authenticate/src/utils.js:92,0][static/js/0.74a7ac117d3159b549af.js:133,6]

let normalize = function (str) {
return str
.replace(/[/]+/g, '/')
.replace(//?/g, '?')
.replace(//#/g, '#')
.replace(/://g, '://');
};
return normalize(joined);


Thank you

how to read user data

letsay I have provider like this..

 google: {
      clientId: 'SOMENUMBER.apps.googleusercontent.com',
      redirectUri: 'http://localhost:8080/auth/callback' // Your client app URL
    }

and method like this..

	 authenticate(provider) {
		 this.$auth.logout();
            this.response = null
			this.$auth.authenticate(provider).then(function (authResponse) {
				console.log('authcalled');
				// Execute application logic after successful social authentication
			})
	   }

but after login I select google account it want to go
/auth/google
no matter what i do, how do pick user data response in js client.
Do I really need server part at client app?
and how to read user data?

Save profile data on login

Lots of backends give the profile data back with the login response (token). I'm not sure how this would be the best to implement and even if it would be appropriate within vue-authenticate. Maybe with a hook?

This is more of an approach and opinion question.
I can always do a new call to fetch the profile, but that'd be a bit of a waste.

Can't get Google id_token

Hi,

I'm trying to use vue-authenticate to get the id_token from google, so that i could get the user email after right after he signs through google (without querying another google API for that).

I can't get the user email (via google) from the access_token because its not a JWT token.

When i'm trying to change the responseTpe to id_token i'm getting an error.

Do you have a workaround for it?

The exception i'm getting:
Possible Unhandled Promise Rejection: Error: Authentication error occurred
at eval (vue-authenticate.es2015.js?26cf:1284)
at

Thanks.

Grant Type = Password

I'm trying to use the Register/Login features to authenticate my client to my Server but I can't seem to be able to set grant type to password and Ideas where do I set it up.

Unable to get it working with axios

I followed the instructions for adding axios, but can not get it to work.
The problem is that this.$http is undefined. Vue is pretty new to me, but it might be that "this" is the problem?
When I replace the example interceptor code this.$http to Vue.axios, the interceptor does not throw errors anymore, but the lib does (again with this.$http being undefined).

My layout is just like with vue-authenticate-site. Any help is appreciated.

https://gist.github.com/philippeluickx/1632139a90294aced85830dec3e915b3

Looking at https://github.com/imcvampire/vue-axios#usage

This wrapper bind axios to Vue or this if you're using single file component.

Is there any way to hook this.$http globally?

No body in POST

I'm trying to get this to run. I used sattelizer before and loved it and the integration with vuex seems nice.

I got to the point where I can submit a POST request to the backend, but there's not body. Nothing is being sent.
Similar with the https://github.com/dgrubelic/vue-authenticate-site demo.

I am literally following the example codes.

Browserify: VueAuthenticate is not a constructor

This:

import Vue from 'vue'
import { VueAuthenticate } from 'vue-authenticate'

console.log("VueAuthenticate",VueAuthenticate); // undefined

const vueAuthInstance = new VueAuthenticate(Vue.http, {

gives this error:

ncaught TypeError: _vueAuthenticate.VueAuthenticate is not a constructor

If I import the whole module import VueAuthenticate from vue-authenticate, I receive a Vue plugin object, which isn't a factory according to a similar issue. What am I doing wrong?

auth Facebook issue

Possible Unhandled Promise Rejection: Error: Authentication failed??
After the success of the callback.
What's the problem?

thank you!

Improve documentation

They documentation needs definitely to be more clear and have much better structure how to use this library. For example, I struggle to find how and where would I receive my authorization code. Also what does authenticate exactly do? open up a popup? what?

POST to server to save MongoDB and GET JWT token

I'm using Vuex and after authenticate (context, payload), I'd like to do a POST to my server to save the user.

For Facebook, I can use graph API, send the access token to get profile IDs.

But I'm stuck on where to put this logic in Vue.

Anyone care to share some solution?

Object.defineProperties called on non-object

Hi, I'm trying to use vue-authenticate in my application.
I followed the documentation and did:
(I use axios with vue-axios)

import axios from 'axios'
import VueAxios from 'vue-axios'
import { VueAuthenticate } from 'vue-authenticate'

Vue.use(VueAxios, axios);
Vue.use(VueAuthenticate, {
    baseUrl: 'auth',
	bindRequestInterceptor() {
        this.$http.interceptors.request.use((config) => {
            if (this.isAuthenticated()) {
                config.headers['Authorization'] = [
                this.options.tokenType, this.getToken()
                ].join(' ');
            } else {
                delete config.headers['Authorization']
            }
            return config;
        })
    },
 
    bindResponseInterceptor() {
        this.$http.interceptors.response.use((response) => {
            this.setToken(response);
            return response;
        });
    }
});

But when I run it: (I compile it with Laravel Mix with webpack)
I get:
Uncaught TypeError: Object.defineProperties called on non-object at Function.defineProperties (<anonymous>) at VueAuthenticate (app.js:6408) at Function.Vue.use (vendor.js:16924) at Object.<anonymous> (app.js:1239) at __webpack_require__ (manifest.js:53) at Object.<anonymous> (app.js:8508) at __webpack_require__ (manifest.js:53) at webpackJsonpCallback (manifest.js:24) at app.js:1

Electron support / server removal

Do you think that wrapping your project in Electron could remove server's part.
If I understand, server.js acts as a proxy to relay post messages to providers, because CORS are not allowed from client to provider's domain.
Right ?

If so, electron support could be a great feature.
The electron-oauth-github-vue project could be a source of inspiration.

Working with cordova

Has anybody managed to get this working in cordova, I cant seem to get InAppBrowser to redirect to the app :(

vue-authenticate doesn't send data

Hi, I'm trying to perform register action:

this.$auth.register(this.register).then((response) => {
				console.log('register');
			});

But I don't see any data sent to server in Chrome network developer tools
When I do axios normal request I can see the data that I transfer.

The request has been made, but no data sent

I also tried with normal object, nothing changed

Interceptor not working.

Thanks for this excellent library.
I'm currently connecting vue-authenticate with IdentityServer (Oauth2 and I'm using the Authorization CODE flow) and I'm at the point where I receive a valid bearer token from the IdentityServer. The token is stored in local storage with key name: vue-authenticate.vueauth_token.

the problem I'm facing is that the token is not sent automatically on each request towards the API.
I'm using vue-resource, so did i understand correctly that no explicit configuration is necessary ?

This is my main.js, Am I doing something wrong?

import Vue from 'vue'
import Quasar from 'quasar'
import router from './router'
import vuelidate from 'vuelidate'
import VueResource from 'vue-resource'
import VueAuthenticate from 'vue-authenticate'
Vue.use(Quasar) // Install Quasar Framework
Vue.use(vuelidate)
Vue.use(VueResource)

Vue.use(VueAuthenticate, {
  baseUrl: 'http://localhost:8080',
  providers: {
    identSrv: {
      name: 'identSrv',
      url: 'Token/Exchange',
      authorizationEndpoint: 'http://localhost:5000/connect/authorize', 
      redirectUri: window.location.origin || window.location.protocol + '//' + window.location.host,
      scope: ['profile', 'openid', 'MyApi'],
      responseType: 'code',
      scopePrefix: '',
      scopeDelimiter: ' ',
      requiredUrlParams: ['scope', 'nonce'],
      optionalUrlParams: ['display', 'state'],
      state: function () {
        var val = ((Date.now() + Math.random()) * Math.random()).toString().replace('.', '')
        return encodeURIComponent(val)
      },
      display: 'popup',
      oauthType: '2.0',
      clientId: 'PanelButlerVueJs',

      nonce: function () {
        var val = ((Date.now() + Math.random()) * Math.random()).toString().replace('.', '')
        return encodeURIComponent(val)
      },
      popupOptions: { width: 452, height: 633 }
    }
  }
})

404 error

I am trying to work with the library but I keep getting the error POST http://localhost:3000/auth/register 404 (Not Found). I even tried cloning the original repository but it is the same I can't register or login

Doesn't work when browsing in private

I haven't looked deep enough but if vue-authenticate does rely on the localStorage, if the user is browsing in private mode (e.g. chrome incognito) he will never be able to authenticate.

Different browsers do private mode differently, but chrome for instance won't share localStorage data between tabs/windows.

Any workaround?

Some calrifications

Could you please clarify how this library works, a small introduction in the docs would be great.

Some thoughts & questions a developer could have:

  • Where will user data be saved?
  • What about routing?
  • Possibility for listening to events when user is logged/unlogged?
  • Could this be combined with https://auth0.com/ ?

Vue is not defined in services/auth.js

According to your vue-authenticate-site project I can make service to instate new VueAuthenticate object and later import somewhere else. Problem is, that Vue is not defined here. If I console.log(Vue) it says, that it's a constructor. Should I make new Vue object?

My services/auth.js:

import Vue from 'vue'
import VueResource from 'vue-resource'
import VueAuthenticate from 'vue-authenticate'
Vue.use(VueResource)

const vueAuthInstance = new VueAuthenticate(Vue.http, {
  baseUrl: 'http://localhost:8000',
  loginUrl: '/oauth/token'
})

export default vueAuthInstance

In main.js I have Vue of course.

new Vue({
  el: '#app',
  router,
  i18n,
  store
});

Not working on mobile browsers

I have set up an application to use vue-authenticate

  • it works on Desktop browsers (I can log in using Facebook and get to the /me route)
  • it does not work when trying to do the same on mobile

What I get instead is a new tab with the same URL

You can give it a try here

**** UPDATE: This is not an issue with the library. The problem was that I was visiting the http version of the side and not the https one.

I am closing this

Refresh Token

Most auth implementations use a short lived access token and a longer living refresh token in order to securely maintain the user logged in.
Basically the refresh token is used to generate a new access token once it has expired, and this is done without having to ask the user for login credentials again.
I found a detailed explanation in the vue-auth package.
Does this package support this in any way?

How to disable popup window?

There appears to be a providers option called display: 'popup' along with popupOptions: { width: 452: height: 633 } but there is no way to disable the popup window.

Is this a planned feature?

Vuex authentication error

I'm following the 'Vuex authentication' example.

If I use, as per the ES6 example import { VueAuthenticate } from 'vue-authenticate' I get this error:

index.js?e9c9:7 Uncaught TypeError: __WEBPACK_IMPORTED_MODULE_2_vue_authenticate__.VueAuthenticate is not a constructor

Feature request

Add more providers like
linkedin, instagram,live.. and generic oauth1 and oauth2.

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.