Code Monkey home page Code Monkey logo

aurelia-auth's Introduction

Hi there 👋

aurelia-auth's People

Contributors

adamwillden avatar alfkonee avatar apboon avatar boazblake avatar chriswait avatar digizen avatar doktordirk avatar efredin avatar fgurtler avatar ghiscoding avatar ielcoro avatar lukechilds avatar markherhold avatar markoburazer avatar martinrebane avatar mbroadst avatar naragato avatar niieani avatar paulvanbladel avatar robertherhold avatar rwoverdijk avatar semigradsky avatar theremix avatar wouth 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

aurelia-auth's Issues

Aurelia Fetch Client Compatibility

I really love this plugin but I would like to know if it's supported in the Aurelia-fetch-client.
If Yes: please provide a short guide on how to integrate it

404 POST after popup window closes

I am getting a 404 after a successfull authentication. The following appears in the console after the authentication popup window closes on the aurelia-auth-sample project

POST http://localhost:9000/ 404 (Not Found)processRequest @ aurelia-http-client.js:275f @ shim.min.js:1415(anonymous function) @ shim.min.js:1423b.exports @ shim.min.js:453b.(anonymous function) @ shim.min.js:1625f @ shim.min.js:1596q @ shim.min.js:1600
aurelia-http-client.js:275 XHR finished loading: POST "http://localhost:9000/".processRequest @ aurelia-http-client.js:275f @ shim.min.js:1415(anonymous function) @ shim.min.js:1423b.exports @ shim.min.js:453b.(anonymous function) @ shim.min.js:1625f @ shim.min.js:1596q @ shim.min.js:1600
oAuth2.js:105 error :undefined
shim.min.js:1444 Unhandled promise rejection HttpResponseMessage {requestMessage: HttpRequestMessage, statusCode: 404, response: "Cannot POST /↵", isSuccess: false, statusText: "Not Found"}(anonymous function) @ shim.min.js:1444b.exports @ shim.min.js:453b.(anonymous function) @ shim.min.js:1625f @ shim.min.js:1596q @ shim.min.js:1600
shim.min.js:1444 Unhandled promise rejection HttpResponseMessage {requestMessage: HttpRequestMessage, statusCode: 404, response: "Cannot POST /↵", isSuccess: false, statusText: "Not Found"}(anonymous function) @ shim.min.js:1444b.exports @ shim.min.js:453b.(anonymous function) @ shim.min.js:1625f @ shim.min.js:1596q @ shim.min.js:1600
shim.min.js:1444 Unhandled promise rejection HttpResponseMessage {requestMessage: HttpRequestMessage, statusCode: 404, response: "Cannot POST /↵", isSuccess: false, statusText: "Not Found"}(anonymous function) @ shim.min.js:1444b.exports @ shim.min.js:453b.(anonymous function) @ shim.min.js:1625f @ shim.min.js:1596q @ shim.min.js:1600

authConfig.js

var config = {
    //our Aurelia App Address
    baseUrl: 'http://localhost:9000/',
    loginUrl:'sessions/create',
    loginRedirect: '#/profile',
    logoutRedirect: '/',
    loginRoute: 'login',
    signupUrl: 'signup',
    profileUrl: '#/profile',
    tokenName: 'id_token',
    providers: {
        localIdentity: {
            clientId: 'javascriptClients',
            authorizationEndpoint: 'https://localhost:44300/core/connect/authorize/',
            redirectUri: 'http://localhost:9000/',
            scope: ['openid','profile', 'email'],
            scopePrefix: '',
            scopeDelimiter: ' ',
            requiredUrlParams: ['scope','nonce'],
            type: '2.0',
            responseType : 'id_token',
            display: 'popup',
            nonce: function() {
                var val = Math.random();
                return encodeURIComponent(val);
            },
            popupOptions: { width: 1020, height: 618 }
        }
    }
}

Add header to login call from config

In the createRequest call, how about allowing users to add a custom header (like Authorization) from config.

** var header = this.auth.getHeader(); **
return this.http.createRequest(loginUrl)
        .asPost()
               ** .withHeader(header.key, header.value) **
        .withContent(content)
        .send()
        .then(response => {
            this.auth.setToken(response);
            return response;
        });

include token header only for specific domains

currently the jwt token is send with every fetch request, even if not required, e.g. within the oauth requests to social providers or any other domain you use fetch for. Proof me wrong but I guess this is bad practice.
What do you think about having kind of a whitelist in the config file, an array of domain-strings for which the token should be set only. In the interceptor then the request url could be matched with this whitelisted domains and the token only set if appropriate. Any thoughts on this?

token not provided - bad request

my app is working just fine but after some time the token is not sent with headers which results in a bad request. Token exists in Local Storage

after installing : jspm install aurelia-auth i get in chrome dev tool: http://localhost:4000/dist/nav-bar.html.js 404 (Not Found)

after installing : jspm install aurelia-auth i get in chrome dev tool: http://localhost:4000/dist/nav-bar.html.js 404 (Not Found) , and i have no idea why suddently this error, it was working before installing the plugin. Tried to uninstall but the error pesrsists, any idea where i should look for to fix this?

the instalation looked like this:
jspm install aurelia-auth
Updating registry cache...
Looking up github:paulvanbladel/aurelia-auth
Looking up npm:aurelia-fetch-client
Looking up npm:aurelia-framework
Looking up npm:aurelia-http-client
Looking up npm:aurelia-router
Looking up npm:core-js
Looking up npm:aurelia-pal
Looking up npm:aurelia-path
Looking up npm:aurelia-binding
Looking up npm:aurelia-dependency-injection
Looking up npm:aurelia-loader
Looking up npm:aurelia-logging
Looking up npm:aurelia-metadata
Looking up npm:aurelia-task-queue
Looking up npm:aurelia-templating
Looking up npm:aurelia-event-aggregator
Looking up npm:aurelia-history
Looking up npm:aurelia-route-recognizer

warn Using local override for npm:[email protected]
Looking up github:systemjs/plugin-json
Looking up github:jspm/nodelibs-fs
Looking up github:jspm/nodelibs-path
Looking up github:jspm/nodelibs-process
Looking up npm:path-browserify
Looking up npm:process
Looking up github:jspm/nodelibs-assert
Looking up npm:assert
Looking up npm:util
Looking up npm:inherits
Looking up github:jspm/nodelibs-util
ok Up to date - aurelia-auth as github:paulvanbladel/aurelia-auth@^0.11.4 (0.11.4)
Installed Forks

                 npm:aurelia-binding 1.0.0-beta.1.0.1 1.0.0-beta.1.0.2
              npm:aurelia-task-queue 1.0.0-beta.1 1.0.0-beta.1.0.1
              npm:aurelia-templating 1.0.0-beta.1 1.0.0-beta.1.0.1

Open id connect: Response mode "Post" issue

@paulvanbladel @RWOverdijk @devscott @Vidarls
Our Open Id connect server by default seems to be posting the data to redirect url. Fiddler shows that data is being posted to the url which it can not accept. error message: 'Cannot POST /'
Any way to get around this? the server supports other response modes too when specified in query. Which one should we use?

this.auth.authenticate('company', false, null)
            .then((response: any) => {
                console.log("Success" + response);
            },
            (error:any) => {
                console.log("Failed response " + error);
            });

Config:

providers = {
        company: {
            name: 'company',
            clientId: 'ourguid',
            authorizationEndpoint: 'https://login.microsoftonline.com/someid/oauth2/authorize',
            redirectUri: this.currentHost(),
            scope: ['profile'],
            scopePrefix: 'openid',
            scopeDelimiter: ' ',
            requiredUrlParams: ['scope', 'nonce', 'state'],
            optionalUrlParams: ['display'],
            responseType: 'id_token',
            state: '#/home',
            type: '2.0',
            nonce: this.getNonce(),
            popupOptions: { width: 1020, height: 618 },
            display: 'popup',
        }
    }

    getNonce() {
        return encodeURIComponent(
            ((Date.now() + Math.random()) * Math.random())
                .toString()
                .replace(".", "")
        );
    }

    currentHost() {
        return window.location.origin || `${window.location.protocol}//${window.location.host}`;
    }

Tag

Sorry, could you also tag this module? If it's taking too much time, you could add me as contributor.

switching between providers can cause authentication failure

I get a failure if I issue calls in this sequence:

  1. authService.authenticate("live", true) => OK
  2. authService.authenticate("google", true) => OK
  3. authService.authenticate("live", true) => KO

The problem, I think, is that the OAuth2 "defaults" member is not reinitialized when calling "open" so in my case a scopePrefix of "openid" left behind by the "google" call is used for "live" which causes it to fail.

I checked in the satellizer sources and an OAuth1/OAuth2 instance is created for each authenticate call so the call to open gets fresh "defaults". The OAuth1/OAuth2 instances are being reused in aurelia-auth. Maybe move the "defaults" initialization to the top of "open" in OAuth1 and OAuth2 ?

Naming

I recommend that you follow the Aurelia "naming standard" and rename it aurelia-auth or perhaps even better, aurelia-token-auth since there might well be other auth plugins (such as JWT etc.) down the line...

Aurelia Pre-Beta Release (11-10-2015) causes aurelia-auth to break

It looks like this breaking change from the Aurelia pre-beta is causing an error in aurelia-auth:

Router Pipeline steps now receive the NavigationInstruction instead of the NavigationContext. Pipeline steps should use instruction.getAllInstructions() and instruction.getAllPreviousInstructions() instead of context.nextInstructions and context.currentInstructions, respectively, to inspect current and previous instructions. - from http://blog.durandal.io/2015/11/10/aurelia-pre-beta-release/

Looks like the AuthorizeStep class needs to be updated accordingly, at minimum. https://github.com/paulvanbladel/aurelia-auth/blob/master/dist/es6/authorizeStep.js

_this.XHRType() of undefined"

Hi , I am using Aurelia_Auth, In that I am called Login(email, password). I got the error _this.XHRType() of undefined; I did the debugging process I got the error at this moment..var xhr = _this.xhr = new _this.XHRType(); Is there any way to resolve this error? "

Integration with Breezejs

Can you provide some guidelines how to integrate it with breezejs and asp.net webapi on server-side.

Example - if I take aurelia-nwind-breeze example (by Jeremy Danyow) how we can integrate this plugin with it.

Adding more API

I would love to have a richer set of methods (functions - not yet sure what is the proper term in ES6 JavaScript) in AuthService class and I am not one of those guys that want to do everything form the scratch, themselves.

Some of the features I need

  • support for user claims (set of claims extensible by the user)
  • user claims merging
  • support for account provisioning including workflow based provisioning.

Comments

  • The guy who wrote Satellizer (Sahat Yalkabov) seems smart (I had several conversations with him few months ago) but I am not sure whether his architecture would support my additional features (I am assuming that your port inherited the original architecture)
  • I care about the Account Management services as defined here without limiting ourselves to this particular vendor of course.

Interested in expanding Aurelia-Auth or should I go on my own?

Inject is not a function

After upgrading to the latest bits that were release today, I am getting the error "Inject is not a function." when aurelia-auth loads.

Push State makes redirect reload complete app on login/logout

Hi Paul,

I have aurelias push state configured on my router config config.options.pushState = true;.

This causes the application to reload instead of simply navigating to the defined routes on login/logout.

Instead, when I use e.g. this.router.navigate('/contents');, the navigation is working without reloads.

In your code I can see you were testing the router navigate. Was it not working?

Another idea would be to decouple setToken() and logout() from redirecting so I can call them directly and do the routing on my own.

Right now, for the login I use the following solution:

  • explicitly set the loginRedirect config to '' so the complete if-else block will be skipped loginRedirect: ''
  • in my signin.js I inject the router and do:
    return this.auth.login(userInfo)
      .then(response => {
        console.log('You signed in successfully.');
        this.router.navigate('/contents');
      })

This fixes the reload of my page and still does a redirect.

However, for the logout, this is no completely working right now. I need to check this again, but when I set logoutRedirect to '' (logoutRedirect: '') it seems like the promise is not resloving. I will reply on this later.

Perhaps I am doing something wrong? Thank you for your reply.

Issue with latest version of Aurelia

aurelia/dialog#78

http://stackoverflow.com/questions/32260529/aurelia-globalizeresources-no-longer-available

Hello. Please see above two links.

Summary: I was forced up update my Aurelia to the latest version to get a dialog plugin to work and it appears to have broken something in regards to your plugin. It revolves around some API change involving globalizeResources to globalResources but simply making that adjustment in index.js of your plugin is not enough to get it to work. Errors is: property call 'some' on undefined. This property call exists in file: authorizeStep.js

Login, token JWT

Hi!

Didn't know where to write the question...so it ended up in issues...sorry :)

I need to have the grant_type: 'password', in the request. Did not know how to use the standard you've created.

So how should it be done?

This is working for me at the moment, but doesn't feel correct...


    login(){
        var loginData = {
            grant_type: 'password',
            username: this.username,
            password: this.password
        };




         return this.http.post(this.authService.config.baseUrl + this.authService.config.loginUrl, $.param(loginData))
            .then(response => {
                //console.log('Got authentication response ' + response.content.access_token);
                // console.log(this.authService);

                if(this.authService.config.storage==='localStorage'){
                    localStorage.setItem(this.authService.config.tokenPrefix ? this.authService.config.tokenPrefix + '_' + this.authService.config.tokenName : this.authService.config.tokenName,response.content.access_token);
                }else{
                    sessionStorage.setItem(this.authService.config.tokenPrefix ? this.authService.config.tokenPrefix + '_' + this.authService.config.tokenName : this.authService.config.tokenName,response.content.access_token);
                }


                if (this.authService.config.loginRedirect) {
                  window.location.href = this.authService.config.loginRedirect;
                } else {    
                  window.location.href = window.encodeURI('/#welcome');
                }

                return response;

            }, error => {
                this.error = 'Login Failed';
            });

    };

Can't post to Oauth2 Service with authService.login()

Currently the way AuthService.Login is implemented it will not post to any .net Oauth2 Service because it strictly requires the post data to be formatted with 'application/x-www-form-urlencoded'.

The current implementation seems really close... but I am unable to get it to work without monkey patching in an alternate to your auth function.

Currently I am patching this in so that I can use the content = arguments[0]; for my url escaped string.

    monkeyPatchAuthService(){
        this.auth.login = function login(email, password) {
                        var _this2 = this;

                        var loginUrl = this.auth.getLoginUrl();
                        var content;

                        if (typeof arguments[1] !== 'string') {
                            content = arguments[0];
                        } else {
                            content = { 'email': email, 'password': password };
                        }

                        return this.http.createRequest(loginUrl).asPost().withContent(content).send().then(function (response) {
                            _this2.auth.setToken(response);
                            return response;
                        });
                    }
    }

After patching that in I can now call the following and it seems to work.

var loginObj = $.param({'username': this.username, 'password': this.password, grant_type: "password"});

        return this.auth.login(loginObj)
        .then(response=>{

Please let me know if you need any other info.

Accept headers for login are incorrect on Firefox

I just started using aurelia-auth (great library!) to authenticate against my own service using JWT.

I managed to make it work using https://github.com/paulvanbladel/aurelia-auth-sample as a base and modifying authConfig.js to meet my needs:

var configForDevelopment = {
    providers: {
            ...
    },
    baseUrl: 'http://localhost:7001/',
    loginUrl: '/api-token-auth/',
    loginRedirect: '/#/',
    profileUrl: '/accounts/me',
    authToken: 'JWT'
};

This works fine on Chrome but not on Firefox. I found the reason for it to be that on Chrome login sends Accept: */* whereas on Firefox it sends Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8. My backend honors HTTP content negotiation and sends back HTML, but your authService assumes it gets JSON back.

I suggest that authService should configure HttpService to send an accept header of application/json, if you expect the response to come in that format (probably in https://github.com/paulvanbladel/aurelia-auth/blob/master/src/authService.js#L62 unless it can be better set globally).

manual build creates different code

i'm having trouble building a copy of aurelia-auth.
after running npm install, jspm install, gulp build, the files in dist/system differ and the pugin fails (orignial plugin works fine)

eg in dist/system/baseConfig.js line 12-14 ib the original repo is

  setters: [function (_authUtils) {
      authUtils = _authUtils['default'];
    }],

changed to

 setters: [function (_authUtils) {
      authUtils = _authUtils.authUtils;
    }],

any ideas what i might do wrong?

Bearer token not sent with request

So I've updated Aurelia and the auth. Before I updated I could do this in the activate:
return this.http.get(this.authService.config.baseUrl + this.api)
.then(response => {
console.log(response)
this.employees = response.content;
});

And the bearer token was sent With the request. Now it's empty. My authConfig haven't been changed. I can also see that my token is in the local Storage.

What have I missed? Something New in the Aurelia update?

Thanks in advance

image

image

"Cannot read property 'message' of null" error when a login fails

I'm using the following code to login:

import {AuthService} from 'aurelia-auth';
import {inject} from 'aurelia-framework';
@inject(AuthService)
export class Signin {

    constructor(auth){
        this.auth = auth;
    };

  username='';
  password='';

  login(){
      return this.auth.login(this.username, this.password)
      .then(response=>{
          console.log("success");
      })
      .catch(err=>{
          console.log("login failure");
      });
  };
}

When the login fails (incorrect email/password) I return a 401 Unauthorized response with the response body being an error message. In this scenario I would expect the err in the catch above to be the response from the server.

Instead I'm seeing this:
error2

Looking into the code I can see authService.js has a console.log statement when it catches an error during login which assumes err.content.message is populated. As this is null on my response it throws a new error instead of the actual server response error.

The fix for this will be to either check if err.content is defined or remove the console.log line (if someone wants to log this to the console they can add the code in their viewmodel).

error

tag

Please make a new tag. Master contains a fix I need (signup. I don't have a displayname or email, but a simple username and password).

How to enable CORS ?

First, thanks for this great piece of code !!
I'm not a node.js expert and I'm started my node server in another port, however I'm getting 401 - http://screencast.com/t/aTYKPs5nZ. Could you advice how I could enable CORS? Or is there anything else that I'm missing ? I tried to add

app.use(function(req, res, next) {
  res.header("Access-Control-Allow-Origin", "*");
  res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
  next();
});

but it didn't work.

getMe() doesn't send Authorization headers

how do i use the auth.getMe() method to send the token in the Authorization headers?

no Authorization Header
it's 404 because i didn't bother creating the route yet before i figure out how to identify the user

here's my authConfig.js

const DEV_CONFIG = {
  loginRedirect: '/#/',
  profileUrl : '/api/oauth/me',
  providers : {
    github : {
      url : '/api/oauth/github',
      clientId : 'xxxxxxxxxxxxxxxxxxxxxx',
      redirectUri: '/api/oauth/cb'
    }
  }
};

if i can get the token being sent in the Authorization header, then i can change 'profileUrl' : 'https://api.github.com/user'

Exception thrown when token is invalid

A corrupted token in local storage is causing an 'Unexpected token' exception when parsed in authentication.js as the decoded value is invalid JSON:

 var base64Url = token.split('.')[1];
            var base64 = base64Url.replace(/-/g, '+').replace(/_/g, '/');
            var exp = JSON.parse(window.atob(base64)).exp;

This causes isAuthenticated() to fail rather than returning false.
All JSON.parse statements should probably have try catch.

Electron

Thank you for publishing awesome library.

Does it support electron ?

It mays not to work well..

Typescript Definition File is not included

I am trying to get Aurelia-auth working in a TS project.

In the app file, I am trying to get this line converted to something that will work in TS:

import HttpClientConfig from 'aurelia-auth/app.httpClient.config';

I created aurelia-auth.d.ts and put this code in it:

 declare module 'aurelia-auth' {
 export class HttpClientConfig {
    configure():any;
    }
}

Then I try to import it:

import {HttpClientConfig} from 'aurelia-auth';

This works as far as the compiler is concerned, but it doesn't actually inject it at runtime.

Send token

How can I send the token along with every request I make? The README says:

The aurelia token will be sent automatically to your API when the user is authenticated.

However, AuthService.isAuthenticated() returns true, and the token is not sent along with my requests. Here's how I make my requests:

this.api.createRequest('/user/me')
      .asGet()
      .send().then(response => {
        this.user = response;
      });

this.api is just HttpClient (aurelia-http-client).

baseUrl setting of HttpClient gets overwritten.

When HttpClient is configured by the user, like the following code, aurelia-auth plugin overwrites baseUrl setting, if its configure method gets called after. The only way to prevent default baseUrl setting to be overwritten, is to make sure that HttpClient's configure method gets called last.

import {HttpClient} from 'aurelia-fetch-client';

@inject(HttpClient)
export class MyClass {

    constructor(http) {
        http.configure(config => {
            config.withBaseUrl('someBaseUrl/');
        });

        this.http = http;
    }

}

Also aurelia-auth plugin doesn't respect any user defined settings in HttpClient, it simply overwrites them all. It would be nice to respect user defined settings of HttpClient.
Possibly, this quick idea will give you a light of what I mean.

Error: inject is not a function

I followed the tutorial to install the plugin but when I add this:

.plugin('paulvanbladel/aurelia-auth', (baseConfig)=>{
         baseConfig.configure(config);
    });

and/or this:

import {AuthService} from 'paulvanbladel/aurelia-auth';
import {inject} from 'aurelia-framework';
@inject(AuthService)

I get the error Error: inject is not a function . When I call the plugin there is a problem on:

/* storage.js file, line 98 */
Storage = inject(BaseConfig)(Storage) || Storage;

or on any file that call the inject function. I tried to clear the jspm cache and install all the dependencies again, but it does not solve the problem.

Is an aurelia-auth problem, mine or aurelia-framework?

Thanks for any help

Pass authConfig directly to plugin call (remove function declaration)

Could the aurelia-auth code take the configuration directly as follows:

import authConfig from './authConfig';
export function configure(aurelia) {
  aurelia.use
    .standardConfiguration()
    .developmentLogging()
    .plugin('aurelia-auth', authConfig);

  aurelia.start().then(() => aurelia.setRoot());
}

Rather than the function we have to pass in at the moment?

import authConfig from './authConfig';
export function configure(aurelia) {
  aurelia.use
    .standardConfiguration()
    .developmentLogging()
    .plugin('aurelia-auth', (baseConfig) => {
         baseConfig.configure(authConfig);
    });
  aurelia.start().then(a => a.setRoot());
}

Or does what I'm proposing already work?

Custom Config for http-client

Just wondering if there is a way to configure the http client to add "x.withInterceptor(new ResponseInterceptor())" for it so I get handle any response errors globally instead of handling them on each call.

I didn't find anything that allowed for customization, wondering if I just am missing it, and if not, if you have any plans to build it in?

I think getPayload should be moved from utility Authentication class to main interface

In my opinion, any non-trivial use-case for JWT authentication likely involves pulling data out of the token by the client. This can involve the specific permissions granted in the application, the username, the first name, or whatever else the server chooses to store in the token.

There's already a function that extracts the data, Authentication.getPayload(). I think this should be moved into the declared interface as the heavier cousin of "isAuthenticated()".

What do you think?

Nav bar isAuthenticated not filtering routes

Hi, I'm stuck with this issue and cannot explain why it is not working as expected.

nav-bar.js

import {bindable} from 'aurelia-framework';
import {inject} from 'aurelia-framework';
import {AuthService} from 'aurelia-auth';

@inject(AuthService)

export class NavBar {
  // User isn't authenticated by default
  _isAuthenticated = false;
  @bindable router = null;

  constructor(auth) {
    this.auth = auth;
  };

  // We can check if the user is authenticated
  // to conditionally hide or show nav bar items
  get isAuthenticated() {
    return this.auth.isAuthenticated();
  };
}

nav-bar.html

<template bindable="router">
  <nav class="navbar navbar-default navbar-fixed-top" role="navigation">
    <div class="navbar-header">
      <button type="button" class="navbar-toggle" data-toggle="collapse" data-target="#bs-example-navbar-collapse-1">
        <span class="sr-only">Toggle Navigation</span>
        <span class="icon-bar"></span>
        <span class="icon-bar"></span>
        <span class="icon-bar"></span>
      </button>
      <a class="navbar-brand" href="#">
        <i class="fa fa-home"></i>
        <span>${router.title}</span>
      </a>
    </div>

    <div class="collapse navbar-collapse" id="bs-example-navbar-collapse-1">
      <ul class="nav navbar-nav">
        <li repeat.for="row of router.navigation | authFilter: isAuthenticated" class="${row.isActive ? 'active' : ''}">
          <a data-toggle="collapse" data-target="#bs-example-navbar-collapse-1.in" href.bind="row.href">${row.title}</a>
        </li>
      </ul>

      <ul if.bind="!isAuthenticated" class="nav navbar-nav navbar-right">
        <li><a href="/#/login">Login</a></li>
        <li><a href="/#/signup">Signup</a></li>
      </ul>

      <ul if.bind="isAuthenticated" class="nav navbar-nav navbar-right">
        <li><a href="/#/logout">Logout</a></li>
      </ul>

      <ul class="nav navbar-nav navbar-right">
        <li class="loader" if.bind="router.isNavigating">
          <i class="fa fa-spinner fa-spin fa-2x"></i>
        </li>
      </ul>
    </div>
  </nav>
</template>

Even after the login the isAuthenticated method always gives a false value.

This is the auth-config.js and the token is present with the correct name in the localStorage

// Specific settings for our application's
// authentication context. These will override
// the default settings provided by aureliauth

var config = {

  // Our Node API is being served from localhost:3001
  baseUrl: 'http://localhost:9393',
  // The API specifies that new users register at the POST /users enpoint.
  signupUrl: 'signup',
  // Logins happen at the POST /sessions/create endpoint.
  loginUrl: 'login',
  // The API serves its tokens with a key of id_token which differs from
  // aureliauth's standard.
  tokenPrefix: 'aurelia',
  tokenName: 'id_token',
  // Once logged in, we want to redirect the user to the welcome view.
  loginRedirect: '#/welcome',

}

export default config;

Overridden loginRoute is not used when checking if a user is logged in

When changing the default config for the login route from /login to /signin, I noticed the AuthorizeStep will always redirect to login instead of using the value in the config.

The issue seems to be a hard coded 'login' in the code. Instead it should use the config to get the login redirect route.
https://github.com/paulvanbladel/aurelia-auth/blob/master/src/authorizeStep.js

 if (!isLoggedIn) {
        return next.cancel(new Redirect('login'));
      }

For now I've just changed my sign in page route to be 'login' which works around this.

Exposing getToken();

I was thinking about exposing the getToken() method to be an available function, but was wondering if there is a reason it's not, if there is security reasons as to why it's not?

I am trying to download a file from my server and in order to do that I have to link it in the href, but I also need to verify that the user is authenticated so I was going to put the token in the query string?

so when the user clicks on

<a href="/server/downloads/.txt" id="wineMenu">Wine Menu</a>

I want it to download the response from the following call, which needs the token in the auth middleware.

router.get('/:file(*)', auth, function(req, res){
  var file = 'wine-menu.txt'
    , path = __dirname + '/files/' + file;
  res.download(path);
});

Microsoft Azure active directory support

First thanks for this resource as it is very well put together. I am learning Aurelia to build a website that will be located on Azure, which I imagine will be very common. Azure has a strong and well support authentication solution, which is Azure active directory. I am learn about this token based solution and provided some links below.

Is it practical and would you consider adding support for Azure active directory to aurelia-auth. Azure active directory provides solutions for Auth 2.0 Facebook/Yahoo, so I don't understand if there is an overlap.

http://blogs.msdn.com/b/brunoterkaly/archive/2014/03/03/introduction-to-windows-azure-active-directory.aspx
http://www.andrewconnell.com/azure-ad-asp-net-mvc-walk-through-implementing-adal-owin
http://justazure.com/azure-active-directory-part-1-introduction/

Thanks again...

getPayload raise "Failed to execute 'atob' on Window: The string to be decoded is not correctly encoded."

I found when getPayload was called with special token string that include more than one '-' or '/', it raise an exception: Failed to execute 'atob' on Window: The string to be decoded is not correctly encoded.
Example:
the encoded text of Chinese '贾翼' is '6LS-57-8'.

Maybe there is a bug at this line:
https://github.com/paulvanbladel/aurelia-auth/blob/master/src/authentication.js#L42
It's only replace the first '-' or '/' character in whole string.

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.