Thursday, March 29, 2018

Angular 2 Authentication: Protecting Private Content

In this article, we’ll add authentication to our Angular application and learn how we can protect sections from our application from unauthorized access.

This article is part 5 of the SitePoint Angular 2+ Tutorial on how to create a CRUD App with the Angular CLI.

  1. Part 0 — The Ultimate Angular CLI Reference Guide
  2. Part 1 — Getting our first version of the Todo application up and running
  3. Part 2 — Creating separate components to display a list of todos and a single todo
  4. Part 3 — Update the Todo service to communicate with a REST API
  5. Part 4 — Use Angular router to resolve data
  6. Part 5 — Add authentication to protect private content

In part 1 we learned how to get our Todo application up and running and deploy it to GitHub pages. This worked just fine but, unfortunately, the whole app was crammed into a single component.

In part 2 we examined a more modular component architecture and learned how to break this single component into a structured tree of smaller components that are easier to understand, reuse and maintain.

In part 3 we updated our application to communicate with a REST API backend using RxJS and Angular’s HTTP service.

In part 4, we introduced Angular Router and learned how the router updates our application when the browser URL changes and how we can use the router to resolve data from our backend API.

Don’t worry! You don’t need to have followed part 1, 2, 3 or 4 of this tutorial, for five to make sense. You can simply grab a copy of our repo, check out the code from part 4, and use that as a starting point. This is explained in more detail below.

Up and Running

Make sure you have the latest version of the Angular CLI installed. If you don’t, you can install it with the following command:

npm install -g @angular/cli@latest

If you need to remove a previous version of the Angular CLI, you can run this:

npm uninstall -g @angular/cli angular-cli
npm cache clean
npm install -g @angular/cli@latest

After that, you’ll need a copy of the code from part 4. This is available at https://github.com/sitepoint-editors/angular-todo-app. Each article in this series has a corresponding tag in the repository so you can switch back and forth between the different states of the application.

The code that we ended with in part 4 and that we start with in this article is tagged as part-4. The code that we end this article with is tagged as part-5.

You can think of tags like an alias to a specific commit id. You can switch between them using git checkout. You can read more on that here.

So, to get up and running (with the latest version of the Angular CLI installed) we would do this:

git clone git@github.com:sitepoint-editors/angular-todo-app.git
cd angular-todo-app
git checkout part-4
npm install
ng serve

Then visit http://localhost:4200/. If all’s well, you should see the working Todo app.

Plan of Attack

In this article, we will:

  • set up a backend to authenticate against
  • add a sign-in method to our existing ApiService
  • set up an authentication service to handle authentication logic
  • set up a session service to store session data
  • create a SignInComponent to display a sign-in form
  • set up a route guard to protect parts of our application from unauthorized access.

By the end of this article, you’ll understand:

  • the difference between cookies and tokens
  • how to create an AuthService to implement authentication logic
  • how to create a SessionService to store session data
  • how to create a sign-in form using an Angular reactive form
  • how to create a route guard to prevent unauthorized access to parts of your application
  • how to send a user’s token as an Authorization Header in an HTTP request to your API
  • why you should never send your user’s token to a third party.

Our application will look like this:

Part 5 Authentication Demo

So, let’s get started!

Authentication Strategy

Server-side web applications typically handle user sessions on the server. They store session details on the server and send the session ID to the browser via a cookie. The browser stores the cookie and automatically sends it to the server with every request. The server then grabs the session ID from the cookie and looks up the corresponding session details from its internal storage (memory, database, etc). The session details remain on the server and are not available in the client.

In contrast, client-side web applications, such as Angular applications, typically manage user sessions in the client. The session data is stored in the client and sent to server when needed. A standardized way to store sessions in the client are JSON Web Tokens, also called JWT tokens. If you’re unfamiliar with how tokens work, check out this simple metaphor to easily understand and remember how token-based authentication works and you’ll never forget again.

If you want to get a deeper understanding of cookies and tokens, make sure to check out Philippe De Ryck’s talk on Cookies versus tokens: a paradoxial choice.

Due to the popularity of JSON Web Tokens in today’s ecosystem, we’ll use a JWT-based authentication strategy.

Setting Up the Backend

Before we can add authentication to our Angular application, we need a back end to authenticate against.

In the previous parts of this series, we use json-server to serve back end data based on the db.json file in the root of our project.

Luckily, json-server can also be loaded as a node module, allowing us to add custom request handlers.

Let’s start by installing the body-parser npm module, which we’ll need to parse the JSON in our HTTP requests:

$ npm install --save body-parser

Next, we create a new file json-server.js in the root of our project:

const jsonServer = require('json-server');
const server = jsonServer.create();
const router = jsonServer.router('db.json');
const middlewares = jsonServer.defaults();
const bodyParser = require('body-parser');

// Sample JWT token for demo purposes
const jwtToken = 'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJuYW1lIjoiU2l0ZVBvaW50IFJ' +
  'lYWRlciJ9.sS4aPcmnYfm3PQlTtH14az9CGjWkjnsDyG_1ats4yYg';

// Use default middlewares (CORS, static, etc)
server.use(middlewares);

// Make sure JSON bodies are parsed correctly
server.use(bodyParser.json());

// Handle sign-in requests
server.post('/sign-in', (req, res) => {
  const username = req.body.username;
  const password = req.body.password;
  if(username === 'demo' && password === 'demo') {
    res.json({
      name: 'SitePoint Reader',
      token: jwtToken
    });
  }
  res.send(422, 'Invalid username and password');
});

// Protect other routes
server.use((req, res, next) => {
  if (isAuthorized(req)) {
    console.log('Access granted');
    next();
  } else {
    console.log('Access denied, invalid JWT');
    res.sendStatus(401);
  }
});

// API routes
server.use(router);

// Start server
server.listen(3000, () => {
  console.log('JSON Server is running');
});

// Check whether request is allowed
function isAuthorized(req) {
  let bearer = req.get('Authorization');
  if (bearer === 'Bearer ' + jwtToken) {
    return true;
  }
  return false;
}

This article is not meant to be a tutorial on json-server, but let’s quickly have a look at what’s happening.

First we import all json-server machinery:

const jsonServer = require('json-server');
const server = jsonServer.create();
const router = jsonServer.router('db.json');
const middlewares = jsonServer.defaults();
const bodyParser = require('body-parser');

In a real-world application, we would dynamically generate a JWT token when a user authenticates, but for the purpose of this demo, we define a JWT token statically:

// Sample JWT token for demo purposes
const jwtToken = 'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJuYW1lIjoiU2l0ZVBvaW50IFJ' +
  'lYWRlciJ9.sS4aPcmnYfm3PQlTtH14az9CGjWkjnsDyG_1ats4yYg';

Next, we configure json-server to run its own default middlewares:

// Use default middlewares (CORS, static, etc)
server.use(middlewares);

and to parse incoming JSON requests properly:

// Make sure JSON bodies are parsed correctly
server.use(bodyParser.json());

Json-server’s default middlewares are request handler functions that deal with static files, CORS, etc. For more detailed information, check out the documentation.

We then define a request handler for sign-in requests:

// Handle sign-in requests
server.post('/sign-in', (req, res) => {
  const username = req.body.username;
  const password = req.body.password;
  if(username === 'demo' && password === 'demo') {
    res.json({
      name: 'SitePoint Reader',
      token: jwtToken
    });
  }
  res.send(422, 'Invalid username and password');
});

We tell json-server to listen for HTTP POST requests on /sign-in. If the request contains a username field with a value of demo and password field with a value of demo, we return an object with the JWT token. If not, we send an HTTP 422 response to indicate that the username and password are invalid.

In addition, we also tell json-server to authorize all other requests:

// Protect other routes
server.use((req, res, next) => {
  if (isAuthorized(req)) {
    console.log('Access granted');
    next();
  } else {
    console.log('Access denied, invalid JWT');
    res.sendStatus(401);
  }
});

// Check whether request is allowed
function isAuthorized(req) {
  let bearer = req.get('Authorization');
  if (bearer === 'Bearer ' + jwtToken) {
    return true;
  }
  return false;
}

If the client’s HTTP request contains an Authorization header with the JWT token, we grant access. If not, we deny access and send an HTTP 401 response.

Finally, we tell json-server to load the API routes from db.json and start the server:

// API routes
server.use(router);

// Start server
server.listen(3000, () => {
  console.log('JSON Server is running');
});

To start our new back end, we run:

$ node json-server.js

For our convenience, let’s update the json-server script in package.json:

"json-server": "node json-server.js"

Now we can run:

$ npm run json-server

> todo-app@0.0.0 json-server /Users/jvandemo/Projects/sitepoint-editors/angular-todo-app
> node json-server.js

JSON Server is running

And voila, we have our own API server with authentication running.

Time to dig into the Angular side.

Adding Authentication Logic to our API Service

Now that we have an API endpoint to authenticate against, let’s add a new method to our ApiService to perform an authentication request:

@Injectable()
export class ApiService {

  constructor(
    private http: Http
  ) {
  }

  public signIn(username: string, password: string) {
    return this.http
      .post(API_URL + '/sign-in', {
        username,
        password
      })
      .map(response => response.json())
      .catch(this.handleError);
  }

  // ...

}

When called, the signIn() method performs an HTTP POST request to our new /sign-in API endpoint, including the username and password in the request body.

If you’re not familiar with Angular’s built-in HTTP service, make sure to read Part 3 — Update the Todo service to communicate with a REST API.

Continue reading %Angular 2 Authentication: Protecting Private Content%


by Jurgen Van de Moere via SitePoint

5 SEO Predictions For 2018

As we enter 2018, we see that the digital marketing landscape continues to change and evolve. Marketers need to keep their eyes open to these changes in order to stay ahead in the game. Following current trends is as important as running your business itself. Learning new tips and tricks is of...

[ This is a content summary only. Visit our website https://ift.tt/1b4YgHQ for full links, other content, and more! ]

by Web Desk via Digital Information World

Authentication with Angular and Auth0

This article was originally published on the Auth0.com blog, and is republished here with permission.

In this tutorial, we’re going to build an Angular application and add login functionality using token-based authentication with Auth0.

You can check out the completed code example from our GitHub repo.

The Angular Ecosystem

AngularJS 1.x was highly regarded as a robust framework for building single-page applications (SPAs). It did a lot of things well, fell short on some, but overall allowed developers to quickly build powerful applications.

While AngularJS (1.x) is a framework, Angular is an entire platform for building modern applications. Alongside the core Angular library, the platform ships with a powerful command line interface (CLI) called Angular CLI that allows developers to easily scaffold their applications as well as control the build system. Angular Platform Server brings server-side rendering to Angular applications. Angular Material is the official implementation of Google’s Material Design, which allows developers to build beautiful applications with ease.

Our App: Daily Deals

Daily Deals App

The app we’re building today is called Daily Deals. The Daily Deals app displays a list of deals and discounts on various products. We'll have a list of publicly available deals that anyone can see and a list of private deals available only to registered members. The private deals are exclusive to registered members, and should hopefully be better.

Serving the Daily Deals

We'll have to get our daily deals from somewhere. Let's build a very simple Node.js back end to serve the deals. We'll have a publicly accessible route serving public deals and a protected route that can only be called by authenticated users. For now, we'll make both of the routes public and worry about the authentication piece later. Take a look at our implementation below:

'use strict';
// Load dependencies
const express = require('express');
const app = express();
const cors = require('cors');
const bodyParser = require('body-parser');

app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
app.use(cors());

// Public route
app.get('/api/deals/public', (req, res)=>{
  let deals = [
    // Array of public deals here
  ];
  res.json(deals);
})

// Private route
app.get('/api/deals/private', (req,res)=>{
  let deals = [
    // Array of Private Deals here
  ];
  res.json(deals);
})

app.listen(3001);
console.log('Serving deals on localhost:3001');

Both our server and the Angular app we are building will require Node.js and NPM, so be sure to have those installed before continuing. Check out the GitHub repo to get our list of daily deals or create your own. The model for each deal will be as follows:

 {
    id: 1234,
    name: 'Name of Product',
    description: 'Description of Product',
    originalPrice: 19.99, // Original price of product
    salePrice: 9.99 // Sale price of product
}

When you’re happy with the public and private deals, launch the server by running node server and navigate to both localhost:3001/api/deals/public and localhost:3001/api/deals/private to make sure you can see the list of deals you added. Next, let's set up our Angular front end.

Angular Front End Setup

One of the best ways to start building a new Angular app is with the official Angular CLI. The CLI can take care of scaffolding the initial app, adding additional components, takes care of the build system and much more. In this tutorial, we’ll scaffold our initial app with the CLI.

If you don't already have it installed, run:

npm install @angular/cli -g

This installs the Angular CLI globally. We'll interact with the CLI using the ng command. To create a new application, choose a directory and run:

ng new ng2auth --routing --skip-tests

This will create a new Angular application with routing and no initial test files for the root component. The app will be created in its own folder in the current directory, and the CLI will download all of the required npm packages and basically set everything up for us.

Once ng new is finished, enter the new directory and run the ng serve command and the Webpack based build system will take care of compiling our app from TypeScript to JavaScript and will serve our app on localhost:4200. The ng serve command will also kick off a live sync process, so any time we make a change our app will automatically recompile.

Let's head over the localhost:4200 for now to make sure that everything is working as expected so far. If you see a message saying “app works!”, you’re golden. Next, let's examine how our Angular app is scaffolded.

The ng new command scaffolded our Angular app and added a lot of files. Many of these we can ignore for now like the e2e folder, which would contain our end-to-end tests. Open up the src directory. In the src directory, we can see some familiar files like index.html, styles.css, and so on. Open up the app directory.

The app directory contains the bulk of our application. By default, we’re presented with the following files:

  • app.component.css - Holds the CSS styles for our root component
  • app.component.html - Holds the HTML view for our root component
  • app.component.ts - Holds the TypeScript logic for our root component class
  • app.module.ts - Defines our global app dependencies
  • app-routing.module.ts - Defines our app's routes.

Each Angular component we write will have at a minimum the *.component.ts file, the others are optional. Our application is going to have three components. The main or root component, a component to display the public deals, and a component to display private deals. For our root component, we'll inline the template and styles. Let's make the following edits and run the following CLI commands:

  • Delete app.component.css and app.component.html files. We'll define all we need for our root component in the app.component.ts file.
  • Create a public-deals component by running ng g c public-deals --no-spec. This component will take care of getting and displaying the public deals data.
  • Create a private-deals component by running ng g c private-deals --no-spec. This component will take care of getting and displaying the private deals data.
  • Create a callback.component.ts file by running ng g c callback --it --is --flat --no-spec.
  • Create a deal file by running ng g class deal --no-spec. This file will hold our deal class, which will let Angular know the structure of a deal.
  • Create a deal.service.ts file by running ng g s deal --no-spec. Here we'll add the functionality to get and retrieve the deal data from our API.

Note: g is a shortcut for generate, and c and s are shortcuts for component and service, respectively. Therefore, ng g c is equivalent to ng generate component. The --no-spec flag indicates that *.spec.ts files should not be generated. The --it and --is flags stand for “inline template” and “inline styles” and --flat indicates that a containing folder should not be created.

Adding HTTP Client Module

We're going to be making HTTP requests to our API in our Angular app. To do so, we need to add the correct module to our app.module.ts file. Let's do so now by importing the HttpClientModule and adding it to our @NgModule's imports array like so:

// app.module.ts
...
import { HttpClientModule } from '@angular/common/http';

@NgModule({
  declarations: [
    ...
  ],
  imports: [
    ...,
    HttpClientModule
  ],
  providers: [],
  bootstrap: [AppComponent]
})
export class AppModule { }

Adding Bootstrap CSS

We're going to use Bootstrap to style our application, so let's include the CSS in the <head> of our index.html file like so:

<!-- src/index.html -->
...
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet">
...

Building the Root Component

Every Angular application must have a root component. We can name it whatever we want, but the important thing is that we have one. In our application, the app.component.ts file will be our root component. Let's take a look at our implementation of this component.

// app.component.ts
import { Component } from '@angular/core';

@Component({
  selector: 'app-root',
  template: `
    <div class="container">
      <nav class="navbar navbar-default">
        <div class="navbar-header">
          <a class="navbar-brand" routerLink="/dashboard"></a>
        </div>
        <ul class="nav navbar-nav">
          <li>
            <a routerLink="/deals" routerLinkActive="active">Deals</a>
          </li>
          <li>
            <a routerLink="/special" routerLinkActive="active">Private Deals</a>
          </li>
        </ul>
        <ul class="nav navbar-nav navbar-right">
          <li>
            <a>Log In</a>
          </li>
          <li>
            <a>Log Out</a>
          </li>
        </ul>
      </nav>
      <div class="col-sm-12">
        <router-outlet></router-outlet>
      </div>
    </div>
  `,
  styles: [
    `.navbar-right { margin-right: 0px !important}`
  ]
})
export class AppComponent {
  title = 'Daily Deals';

  constructor() {}
}

We've created our root component. We added an inline template and some inline styles. We haven't added all the functionality yet, so every user will be able to see all the links and the login and logout buttons. We'll wait to implement those a little bit. We're also displaying the <router-outlet> element. This is where our routed components will show.

Routing

Since we initialized our app with the --routing flag, the architecture for routing is already set up for us. Let's update it so that our Deals component shows by default. We'll also set up all the routes necessary for our app.

Open the app-routing.module.ts file and add the following:

// app-routing.module.ts
import { NgModule } from '@angular/core';
import { Routes, RouterModule } from '@angular/router';
import { CallbackComponent } from './callback.component';
import { PublicDealsComponent } from './public-deals/public-deals.component';
import { PrivateDealsComponent } from './private-deals/private-deals.component';

const routes: Routes = [
  {
    path: '',
    redirectTo: 'deals',
    pathMatch: 'full'
  },
  {
    path: 'deals',
    component: PublicDealsComponent
  },
  {
    path: 'special',
    component: PrivateDealsComponent
  },
  {
    path: 'callback',
    component: CallbackComponent
  }
];

@NgModule({
  imports: [RouterModule.forRoot(routes)],
  exports: [RouterModule]
})
export class AppRoutingModule { }

We can just navigate to localhost:4200 in the browser and see our app displayed. We won't see much yet, just the top navbar and a message saying that the deals component works.

The Deal Type

TypeScript allows us to define the structure or type of our objects. This serves a bunch of useful purposes. For one, if we define the structure of an object, we'll be able to get all of the object's data via IntelliSense. We can additionally test our components easier by knowing the data structure or type of object we are dealing with.

For our app, we'll create one such type. In the deal.ts file, we'll define a type of Deal. Let's see how we'll accomplish this.

// deal.ts
export class Deal {
  id: number;
  name: string;
  description: string;
  originalPrice: number;
  salePrice: number;
}

Now we can declare objects in our Angular application to be a type of deal. These objects will gain all of the properties and methods of the deal type. We’re only defining properties here; we won't have any methods.

Continue reading %Authentication with Angular and Auth0%


by Ado Kukic via SitePoint

9 Scientific Reasons Why It’s Sometimes Better to Give Up - #infographic

We are constantly being told how setting ourselves goals and doing everything we can to reach them is what defines successful people. Bookshelves are full of self-help books and motivational speakers make quite a living from delivering speeches to eager audiences looking for the secrets to...

[ This is a content summary only. Visit our website https://ift.tt/1b4YgHQ for full links, other content, and more! ]

by Irfan Ahmad via Digital Information World

YouTube And Pinterest Barely Disclose Their Marketing Relationships

According to a latest study conducted by Princeton University, YouTube and Pinterest do not reveal almost 90% of their marketing relationships with the users. Most of them are surrounded with affiliate posts which content creators can add in their posts. The research paper further disclosed that...

[ This is a content summary only. Visit our website https://ift.tt/1b4YgHQ for full links, other content, and more! ]

by Zubair Ahmed via Digital Information World

New Facebook Advertising Research for Marketers

Is Facebook part of your marketing plan? Wondering if Facebook ads are still worthwhile? In this article, you’ll discover stats from recent Facebook advertising research. You’ll also find insights to help you make more informed choices for your advertising campaigns. #1: Facebook Revenue & Growth Statistics No one wants to invest in a platform that’s [...]

This post New Facebook Advertising Research for Marketers first appeared on Social Media Examiner.


by Johnathan Dane via

Everyday Needs

Everyday Needs is a store for people who want to make informed decisions for their way of living.
by via Awwwards - Sites of the day
This website attempted to run a cryptominer in your browser. Click here for more information.