Create Your First Angular Schematics

I experienced a lot of pain points when I first started using Angular; I needed to open up so many files just to create a simple Hello World app. Luckily, Angular CLI took away a lot of my initial troubles. 

Angular CLI is a command-line tool that creates a simple Angular project. Angular CLI asks you questions about your app and, based on your answers, it determines the routing and the stylesheet format. How does Angular CLI do this? It uses Schematics. 

Learn What Schematics Are and How To Use Them With Your React Apps

Developers love to create streamlined processes and programs that help us achieve efficiency. I've done a lot of live demos, and, over the years, I’ve noticed that my demos have a lot of instructions. Instead of writing everything down in scripts, I’ve started using automation tools powered by Schematics.

Schematics is a project that was released by the Angular team. In short, it provides an API that allows you to manipulate files and add new dependencies to any project that has apackage.json file. It can also work in non-Angular projects.

Protecting Vue Routes with Navigation Guards

Authentication is a necessary part of every web application. It is a handy means by which we can personalize experiences and load content specific to a user — like a logged in state. It can also be used to evaluate permissions, and prevent otherwise private information from being accessed by unauthorized users.

A common practice that applications use to protect content is to house them under specific routes and build redirect rules that navigate users toward or away from a resource depending on their permissions. To gate content reliably behind protected routes, they need to build to separate static pages. This way, redirect rules can properly handle redirects.

In the case of Single Page Applications (SPAs) built with modern front-end frameworks, like Vue, redirect rules cannot be utilized to protect routes. Because all pages are served from a single entry file, from a browser’s perspective, there is only one page: index.html. In a SPA, route logic generally stems from a routes file. This is where we will do most of our auth configuration for this post. We will specifically lean on Vue’s navigation guards to handle authentication specific routing since this helps us access selected routes before it fully resolves. Let’s dig in to see how this works.

Roots and Routes

Navigation guards are a specific feature within Vue Router that provide additional functionality pertaining to how routes get resolved. They are primarily used to handle error states and navigate a user seamlessly without abruptly interrupting their workflow.

There are three main categories of guards in Vue Router: Global Guards, Per Route Guards and In Component Guards. As the names suggest, Global Guards are called when any navigation is triggered (i.e. when URLs change), Per Route Guards are called when the associated route is called (i.e. when a URL matches a specific route), and Component Guards are called when a component in a route is created, updated or destroyed. Within each category, there are additional methods that gives you more fine grained control of application routes. Here’s a quick break down of all available methods within each type of navigation guard in Vue Router.

Global Guards

  • beforeEach: action before entering any route (no access to this scope)
  • beforeResolve: action before the navigation is confirmed, but after in-component guards (same as beforeEach with this scope access)
  • afterEach: action after the route resolves (cannot affect navigation)

Per Route Guards

  • beforeEnter: action before entering a specific route (unlike global guards, this has access to this)

Component Guards

  • beforeRouteEnter: action before navigation is confirmed, and before component creation (no access to this)
  • beforeRouteUpdate: action after a new route has been called that uses the same component
  • beforeRouteLeave: action before leaving a route

Protecting Routes

To implement them effectively, it helps to know when to use them in any given scenario. If you wanted to track page views for analytics for instance, you may want to use the global afterEach guard, since it gets fired when the route and associated components are fully resolved. And if you wanted to prefetch data to load onto a Vuex store before a route resolves, you could do so using the beforeEnter per route guard.

Since our example deals with protecting specific routes based on a user’s access permissions, we will use in component navigation guards, namely the beforeEnter hook. This navigation guard gives us access to the proper route before the resolve completes; meaning that we can fetch data or check that data has loaded before letting a user pass through. Before diving into the implementation details of how this works, let’s briefly look at how our beforeEnter hook fits into our existing routes file. Below, we have our sample routes file, which has our protected route, aptly named protected. To this, we will add our beforeEnter hook to it like so:

const router = new VueRouter({
  routes: [
    ...
    {
      path: "/protected",
      name: "protected",
      component: import(/* webpackChunkName: "protected" */ './Protected.vue'),
      beforeEnter(to, from, next) {
        // logic here
      }
  ]
})

Anatomy of a route

The anatomy of a beforeEnter is not much different from other available navigation guards in Vue Router. It accepts three parameters: to, the “future” route the app is navigating to; from, the “current/soon past” route the app is navigating away from and next, a function that must be called for the route to resolve successfully.

Generally, when using Vue Router, next is called without any arguments. However, this assumes a perpetual success state. In our case, we want to ensure that unauthorized users who fail to enter a protected resource have an alternate path to take that redirects them appropriately. To do this, we will pass in an argument to next. For this, we will use the name of the route to navigate users to if they are unauthorized like so:

next({
  name: "dashboard"
})

Let’s assume in our case, that we have a Vuex store where we store a user’s authorization token. In order to check that a user has permission, we will check this store and either fail or pass the route appropriately.

beforeEnter(to, from, next) {
  // check vuex store //
  if (store.getters["auth/hasPermission"]) {
    next()
  } else {
    next({
      name: "dashboard" // back to safety route //
    });
  }
}

In order to ensure that events happen in sync and that the route doesn’t prematurely load before the Vuex action is completed, let’s convert our navigation guards to use async/await.

async beforeEnter(to, from, next) {
  try {
    var hasPermission = await store.dispatch("auth/hasPermission");
    if (hasPermission) {
      next()
    }
  } catch (e) {
    next({
      name: "dashboard" // back to safety route //
    })
  }
} 

Never forget where you came from

So far our navigation guard fulfills its purpose of preventing unauthorized users access to protected resources by redirecting them to where they may have come from (i.e. the dashboard page). Even so, such a workflow is disruptive. Since the redirect is unexpected, a user may assume user error and attempt to access the route repeatedly with the eventual assumption that the application is broken. To account for this, let’s create a way to let users know when and why they are being redirected.

We can do this by passing in a query parameter to the next function. This allows us to append the protected resource path to the redirect URL. So, if you want to prompt a user to log into an application or obtain the proper permissions without having to remember where they left off, you can do so. We can get access to the path of the protected resource via the to route object that is passed into the beforeEnter function like so: to.fullPath.

async beforeEnter(to, from, next) {
  try {
    var hasPermission = await store.dispatch("auth/hasPermission");
    if (hasPermission) {
      next()
    }
  } catch (e) {
    next({
      name: "login", // back to safety route //
      query: { redirectFrom: to.fullPath }
    })
  }
}

Notifying

The next step in enhancing the workflow of a user failing to access a protected route is to send them a message letting them know of the error and how they can solve the issue (either by logging in or obtaining the proper permissions). For this, we can make use of in component guards, specifically, beforeRouteEnter, to check whether or not a redirect has happened. Because we passed in the redirect path as a query parameter in our routes file, we now can check the route object to see if a redirect happened.

beforeRouteEnter(to, from, next) {
  if (to.query.redirectFrom) {
    // do something //
  }
}

As I mentioned earlier, all navigation guards must call next in order for a route to resolve. The upside to the next function as we saw earlier is that we can pass an object to it. What you may not have known is that you can also access the Vue instance within the next function. Wuuuuuuut? Here’s what that looks like:

next(() => {
  console.log(this) // this is the Vue instance
})

You may have noticed that you don’t technically have access to the this scope when using beforeEnter. Though this might be the case, you can still access the Vue instance by passing in the vm to the function like so:

next(vm => {
  console.log(vm) // this is the Vue instance
})

This is especially handy because you can now create and appropriately update a data property with the relevant error message when a route redirect happens. Say you have a data property called errorMsg. You can now update this property from the next function within your navigation guards easily and without any added configuration. Using this, you would end up with a component like this:

<template>
  <div>
    <span>{{ errorMsg }}</span>
    <!-- some other fun content -->
    ...
    <!-- some other fun content -->
  </div>
</template>
<script>
export default {
  name: "Error",
  data() {
    return {
      errorMsg: null
    }
  },
  beforeRouteEnter(to, from, next) {
    if (to.query.redirectFrom) {
      next(vm => {
        vm.errorMsg =
          "Sorry, you don't have the right access to reach the route requested"
      })
    } else {
      next()
    }
  }
}
</script>

Conclusion

The process of integrating authentication into an application can be a tricky one. We covered how to gate a route from unauthorized access as well as how to put workflows in place that redirect users toward and away from a protected resource based on their permissions. The assumption thus far has been that you already have authentication configured in your application. If you don’t yet have this configured and you’d like to get up and running fast, I highly recommend working with authentication as a service. There are providers like Netlify’s Identity Widget or Auth0’s lock.

The post Protecting Vue Routes with Navigation Guards appeared first on CSS-Tricks.

Facebook Authentication and Authorization in Server-Side Blazor App

Introduction

The latest preview for .NET Core 3 (preview-6) has introduced the functionality to add authentication and authorization in a server-side Blazor application. In this article, we will learn how to implement authentication and authorization using Facebook in a server-side Blazor application. You can refer to my previous article Understanding Server-side Blazor to get in-depth knowledge on server-side Blazor.

Prerequisites

  • Install the latest .NET Core 3.0 Preview SDK from here.
  • Install the latest preview of Visual Studio 2019 from here.
  • Install ASP.NET Core Blazor Language Services extension from here.

Source Code

Get the source code from GitHub.

Add User Authentication to Your React App

Savvy frontend devs use React components to scaffold their web apps efficiently and get to market faster. The React team's component-based approach has turned frontend development into a simple exercise akin to building a tower of blocks, aka their reusable and extendable components. You can find a React component for just about any need nowadays. We've even built an Okta React component that allows you to easily add user authentication to your app.

In this tutorial, you’ll be creating a fun React app that fetches random Chuck Norris jokes. I’ll also show you how to add user authentication using Okta and customize your user experience, so the jokes replace "Chuck Norris" with your user's names.

Create Your Own Wiki With Angular and Firebase

Why is Storage as a Service (SaaS) and becoming more and more popular with businesses, and what advantages do these platforms provide? Using SaaS platforms can lead to a significant increase in productivity as well as a reduction in development and maintenance costs. It also saves tech leaders from the worries related to server security, as it is all offloaded to the storage provider. There are many different SaaS providers including Google’s Firebase service.

In this tutorial, I will show you how to build your own wiki using Firebase to store the wiki docs, and Angular for the front-end.

The Death of Passwords

The Problem With Passwords

If you’ve been paying attention to cybersecurity trends over the last few years, you’ll already know that security problems are frequently found “between chair and keyboard” (often shortened to PEBCAK in IT circles). The dangers of bad password hygiene are better known by “average” users than ever, with 81 percent of company data breaches caused by poor passwords.

At the same time, technology is reaching further into the corners of our lives, both at work and at home. Because password technology puts the onus on individuals to safely and securely manage their own access methods, users are increasingly put in positions where they’re responsible for security problems.

Node + Express for a Simple Security Model

In this article, we’re going to add a simple security model to the application, which will accept a login, validate a user, redirect to a secure page, enable a logout, and catch any errors which occur during the process. Let’s get started.

Creating a Security Model

The first thing we’re going to do is create a service for the Node server. This will perform our authentication of a user, expose our logged-in user information to the application, and handle the invalidation of the user once they log out of the system.

Build a Basic Ticket Sales App With ASP.NET Core, Angular, and Stripe

Internet shopping is about more than just Amazon. It's become a daily activity for most Americans, and e-commerce is a required feature for many projects a developer may encounter. In this tutorial, you'll learn how to build an e-commerce site to sell tickets using an Angular 6 single page app (SPA) and an ASP.NET Core 2.1 backend API. You’ll build both the Angular and ASP.NET Core applications and run them from within VS Code. Let’s get to it!

Upgrade to Angular 6

I love to use the latest and greatest when starting a new project. But when you use a project generator (like Angular-CLI, or the DotNetCLI), you may be at the mercy of the latest version the authors of those libraries have added. Right now, the DotNet CLI generates an Angular application with dotnet new angular gives you an Angular app at about version 4.5, which is about two versions behind the latest. Let me show you how to upgrade the templates and the generated application so that you’re using Angular 6, which is the latest as of the time of this article.

Build a Simple Spring Boot App With Spring Data JPA and Postgres

Just about every application needs a way to save and update data, typically a resource server that is accessible via HTTP. Generally, this data must be secured. Within the Java ecosystem, Spring makes building secure resource servers for your data simple. When coupled with Okta for secure user management, you get professionally maintained OAuth 2.0 and JWT technologies easily integrated into Spring Boot via Spring Security.

In this tutorial, you’re going to build a resource server using Spring Boot and Spring Data JPA. On top of that, you’re going to implement a group-based authentication and authorization layer using OAuth 2.0.

IoT Security Compliance: Necessary?

With so many IoT devices clouding the market, we wonder about the security of each unit. And rightly so, if you consider that cyber attacks cost U.S. enterprises $1.3 million, on average, in 2017. It is predicted that around 29 billion connected devices will be present by 2022, of which around 18 billion will be related to IoT. Given these figures, it is easy to imagine how important it is to have safe and secure IoT devices. In fact, 70 percent of IoT devices have a significant security vulnerability. When there are so many devices connected to each other over nonsecure platforms, the possibility of data security and cybersecurity being compromised are incredibly high. For instance, Chevrolet reported an increase in data usage by 200 percent for its Internet-connected vehicles. In spite of its advantages, this also exposes vehicles to possibilities of a security breach. As expected, hackers were able to remotely control the brakes and steering of one of their vehicles. The impact of such hacking into any physical product is immense. Apart from the loss of brand loyalty, payment of claims, product recall, such security compromises can also lead to loss of life and property. To cite another instance, there have been studies where doctors have been handed hacked devices which have led to the death of simulated patients. It is horrifying to consider the real-life implications.

So, here is a checklist of all important points that must be considered while creating an IoT Security Compliance checklist.

Why I Took the Time to Turn On Two-Factor Authentication

For the past few years, my dad has been encouraging me to turn on two-factor authentication (2FA) on any service that offers it. Having grown up in the social media age, I felt his requests were unwarranted.

I know social media inside and out (and I have a master’s degree to prove it). I have always taken care not to share personal information online that I wouldn’t share in person, and I regularly update my security settings across all my accounts on the internet. So, what was the big deal with turning on two-factor authentication?

How to Integrate React Application Using Firebase

The world of serverless is growing and when talking about the term serverless, Firebase is a name that comes to the mind of many developers and enterprises. But what is Firebase? We'll discuss what Firebase is, how to authenticate with it, and how to use it in your next React project. Excited? Let’s begin.

Firebase is a Google cloud service that provides backend services for mobile and web applications. It is a widely used option for developers for backend-as-a-service. It has a real-time database service so all the records are instantly updated whenever there are changes in the database.