Code Monkey home page Code Monkey logo

vuejsoidcclient's Introduction

vuejsoidcclient

Project vueJs with oidc-client library

Create the development environment

Npm:
https://nodejs.org/en/download/

Npm Version Control on Windows:
https://github.com/felixrieseberg/npm-windows-upgrade

Npm Version Control on Linux:
https://github.com/creationix/nvm

Technology Version

Version of npm used in the project: 6.5.0
Version of oidc-client: 1.6.1

Identity Provider

The configuration for the examples are based on running IdentityServer4 on localhost. A ready-to-go reference implementation for testing purposes can be found at IdentityServer4AndApi.

Documentation

Oidc-Client:
https://github.com/IdentityModel/oidc-client-js/wiki

Build Setup

# install dependencies
npm install

# serve with hot reload at localhost:8080
npm run dev

# build for production with minification
npm run prod

Connection with identity provider

Change the parameters of the variable mgr of the script SecurityService.js to the values of your identity provider.

var mgr = new Oidc.UserManager({
  userStore: new Oidc.WebStorageStateStore(),  
  authority: 'https://localhost:44321',
  client_id: 'vuejsclient',
  redirect_uri: window.location.origin + '/static/callback.html',
  response_type: 'id_token token',
  scope: 'openid profile address roles identityserver4api country subscriptionlevel offline_access',
  post_logout_redirect_uri: window.location.origin + '/index.html',
  silent_redirect_uri: window.location.origin + '/static/silent-renew.html',
  accessTokenExpiringNotificationTime: 10,
  automaticSilentRenew: true,
  filterProtocolClaims: true,
  loadUserInfo: true
})

The script SecurityService.js contains triggers and methods from the oidc-client library.

API

The script ApiService.js is responsible for making requests to an API using the libraries oidc-client and axios

The baseUrl constant receives the static part of the API Url.

const baseUrl = 'https://localhost:44390/api/';

The defineHeaderAxios() method appends the access teken to the axios head.

async defineHeaderAxios () {
    await user.getAcessToken().then(
      acessToken => {
        axios.defaults.headers.common['Authorization'] = 'Bearer ' + acessToken
      }, err => {
        console.log(err)
      })  
  }

The getAll() method makes a get request. It receives as a parameter a string that will be concatenated with the baseUrl constant by forming the API Url.

async getAll(api){
    await this.defineHeaderAxios() 
    return axios
      .get(baseUrl + api)
      .then(response => response.data)
      .catch(err => {
        console.log(err);
      })
  }

Route protection

The script index.js is responsible for managing the application routes using the vue router. Each route has a field called meta. Meta receives two parameters: requiresAuth and role.

  • requiresAuth[Bollean]: Responsible for protecting the route
  • role[String]: Users with this role will be allowed to access the route
{
  path: '/payinguser',
  name: 'PayingUser',
  component: PayingUser,
  meta: {
	requiresAuth: true,
	role: ['PayingUser']
  }
},
{
  path: '/freeuser',
  name: 'FreeUser',
  component: FreeUser,
  meta: {
	requiresAuth: true,
	role: ['FreeUser']
  }
}

At each transition of routes in the application, the router.beforeEach() method of the script index.js is called. This method checks whether the user who is logged in is allowed to access the route. It does this by comparing the role of the user and the role of the route.

router.beforeEach((to, from, next) => {
  const requiresAuth = to.matched.some(record => record.meta.requiresAuth);
  if (requiresAuth) {
      mgr.getRole().then(
        sucess => {
          if (to.meta.role == sucess){
            next();
          }else {
            next('/accessdenied');
          }
        },
        err => {
          console.log(err);
        }
      );    
  } else {
    next();
  }
});

vuejsoidcclient's People

Contributors

joaojosefilho 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

vuejsoidcclient's Issues

How to use Multiple Roles

if I need use two or more roles in vue-roter,How to confing?

if I use role: ['Role1','Role2'],when logged user's role is Role2,It will denied access to this router。Thanks

{
      path:'/value',
      name:'value',
      component:Value,
      meta: {
        requiresAuth: true,
        role: ['Role1','Role2']
      }
    },

如何实现Role1或Role2任意一个角色的用户登陆,都可以具有访问权限,感谢

silent renew control

how can you decrease the renew interval?
currently silent-renew.html is being hit every second and I tried to put automaticSilentRenew=false
but nothing changes, also I've tried to silentRequestTimeout to increase but it seemed no efect.

Acess Token

Is there a reason that Access Token is spelled "Acess Token" everywhere?

the img directory is unable to locate

when i run this project, it appear this situation:
image

I find is the source is the "webpack.config.base.js":
image

I think you may forget to delete the code

How do you initiate the flow from another page (that is not app.vue?)

Hi there.

Firstly thank you for the example project. I have been playing with it and it integrates flawlessly with my IS4 implementation! 😃

What I want to do is add a new home page with a 'login' button. When a user clicks the login button, it instigates the implicit flow (exactly like the project) and they get directed to the 'home' page (url/home).

I tried to:

  • Start the flow by moving mounted logic into a function so I can call it programmatically - this did not work, as I suspect the mounted life cycle gets called multiple times and mapping a function to a 'login button' is not enough

I then tried:

  • move the logic from app.vue into a new component i.e. login.vue.
  • add login button to app.vue which links to login.vue (via router-link) and leave the rest untouched

Modify app.vue to have a link:

<template>
  <div>
      <div id="app">
         <router-link to="/login">Login</router-link>
        <router-view/>
      </div>
  </div>
</template>

Then in my routes:

{
    path: "/login",
    name: "Login",
    component: Login
},
{
    path: "/dashboard",
    name: "Home",
    component: Home
}

Now I'm unsure on how to progress from here and I'm wondering (after a few attempts) if I am just overcomplicating things...

Is there a simple/obvious way to just have a login page which then kicks off the flow?
Thanks in advance 😄

Funcionamento no internet Explore 11

Essa na verdade é uma dúvida!

O seu projeto está funcionamento corretamente no IE 11 ?
Usei a sua implementação como base para utilizar dentro do Quasar Framework, porém recentemente tive que testa-lo no IE 11 e Edge, e recebo erros no console como por exemplo :
image

Debbuguei um pouco mais no edge e cheguei aqui:
image

Porém não consigo afirmar corretamente o que utiliza esta propriedade, ou se parte do OIDC não está passando pelo processo de polyfill do babel.

UserInfo Endpoint not called

Correct me if I am wrong but it would seem that in your set up the UserInfo endpoint is not called. You have loadUserInfo: true in your Oidc.UserManager options in SecruityService.js but this has no effect because it is the UserManager instance in callback.html which deals with the signIn response. Should the loadUserInfo: true go in the callback.html UserManager instead?

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.