lundi 25 juillet 2016

ember js custom REST authorization with json web tokens

there have been different kinds of posts about nodejs + emberjs + jwt, but none of them i found helpful, i am really new to SPAs.

This probably is duplicate question, but please, how can you set up authorization in emberjs.

Scenario what i am using is from "http://ift.tt/22XE0pU"

So my backend is nodeJS

var express = require('express');
var app = express();
var fs = require('fs');
var cookieParser = require('cookie-parser');
var session = require('express-session');
var FileStore = require('session-file-store')(session);
var bodyParser=require('body-parser');
var mysql = require('mysql');
var jwt = require('jsonwebtoken');
var expressJwt = require('express-jwt');

app.use(function(req, res, next) {
    res.setHeader('Access-Control-Allow-Origin', 'http://localhost:4200');
    res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
    res.header('Access-Control-Allow-Methods', 'POST, GET, PUT, DELETE, OPTIONS');
    next();
});
var secret='secret key here';
app.use('/api', expressJwt({secret: secret}));
app.use(function(req,res,next){
        console.log(req._parsedUrl._raw);
        next();
})
app.use(cookieParser());
// parse application/x-www-form-urlencoded 
app.use(bodyParser.urlencoded({ extended: false }))

// parse application/json 
app.use(bodyParser.json())

app.get('/', function (req, res) {
    res.send(fs.readFileSync('./dist/index.html','utf-8'));
});
app.use(express.static('./dist'));

app.get('/api/notes',function(req,res){
    res.send('secret code');
});


app.post('/authenticate', function (req, res) {
    //TODO validate req.body.username and req.body.password
    //if is invalid, return 401
    console.log(req.body);

    if (!(req.body.username === 'root' && req.body.password === 'root')) {
            res.send(401, 'Wrong user or password');
            return;
    }

    var profile = {
            first_name: 'John',
            last_name: 'Doe',
            email: 'john@doe.com',
            id: 123
    };

    // We are sending the profile inside the token
    var token = jwt.sign(profile, secret, { 
        expiresIn: 1440 // expires in 24 hours
    });
    res.json({ token: token });
});

app.listen(8989, function () {
    console.log('node port:8989');
});

Ember config:

ENV['ember-simple-auth-token'] = {
    serverTokenEndpoint: server_name+'/authenticate',
    serverTokenRefreshEndpoint: server_name+'/authenticate/refresh',
    identificationField: 'username',
    passwordField: 'password',
    tokenPropertyName: 'token',
    authorizationPrefix: 'Bearer ',
    authorizationHeaderName: 'Authorization',
    headers: {},
};

adapter/application.js

import RESTAdapter from 'ember-data/adapters/json-api';
import DS from 'ember-data';
import DataAdapterMixin from 'ember-simple-auth/mixins/data-adapter-mixin';


export default DS.RESTAdapter.extend(DataAdapterMixin,{
namespace: 'api',
host: 'http://localhost:8989',
authorizer:'type:authorize'

});

controllers/login.js

import Ember from 'ember';

export default Ember.Controller.extend({
    session: Ember.inject.service(),

    actions: {
        authenticate: function(username,password) {
            var credentials =     this.getProperties('identification','password');
            console.log(credentials);
            var authenticator = 'authenticator:token';
            this.get('session').authenticate(authenticator, credentials);
        }
    }
});

What i am getting from ember is

ember.debug.js:31321 TypeError: Cannot read property 'authorize' of undefined
    at Class.authorize (session.js:217)
    at Class.hash.beforeSend (data-adapter-mixin.js:78)
    at Function.ajax (jquery.js:8614)
    at Class._ajaxRequest (rest.js:939)
    at rest.js:929
    at Object.initializePromise (ember.debug.js:51552)
    at new Promise (ember.debug.js:53147)
    at Class.ajax (rest.js:891)
    at Class.findAll (rest.js:413)
    at _findAll (finders.js:136)

So when i want to authorize through nodejs with "'/authenticate'" i get my token back, but next request doesn't seem to use this token propertly or can't find it, that where the error cames in, i guess it requires some store like cookies, but how to implement it?

It would be so great if someone could provide FULL example of authorization, because something doesn't just work and it is hard to tell what is the problem.




Aucun commentaire:

Enregistrer un commentaire