Category Archives: Angularjs

$exceptionHandler

  1. – service in module ng

Any uncaught exception in angular expressions is delegated to this service. The default implementation simply delegates to $log.error which logs it into the browser console.

In unit tests, if angular-mocks.js is loaded, this service is overridden by mock $exceptionHandler which aids in testing.

Example:

angular.module('exceptionOverride', []).factory('$exceptionHandler', function() {
  return function(exception, cause) {
    exception.message += ' (caused by "' + cause + '")';
    throw exception;
  };
});

This example will override the normal action of $exceptionHandler, to make angular exceptions fail hard when they happen, instead of just logging to the console.


Note, that code executed in event-listeners (even those registered using jqLite’s on/bind methods) does not delegate exceptions to the$exceptionHandler (unless executed during a digest).If you wish, you can manually delegate exceptions, e.g. try { ... } catch(e) { $exceptionHandler(e); }

Difference between ngBind, ngBindHtml & ngBindTemplate in Angular JS

ng-bind

ngBind is used to replace the text content of the specified HTML element with the value of a given expression. For example if you have an html as follows <b ng-bind="name"></b> and in your controller give a value for name as $scope.name = "John". This will result in <b>John</b>. But you can’t use multiple values to bind in a single html element. For example

$scope.first_name = "John";
$scope.second_name = "D";
<b ng-bind="first_name second_name"></b> 

This will not give the result as <b>John D</b> http://uplifterscarpet.com/category/fort-meyers/ only bind first_name. So for binding multiple values we can use ng-bind-template

ng-bind-template

 $scope.first_name = "John";
 $scope.second_name = "D";

<b ng-bind-template="first_name second_name"></b>

This results in Fincar purchase canada <b>John D</b> But you can’t render an html tag in this both. For rendering html template we can use ng-bind-html.

ng-bind-html

$scope.name = "<b>John</b>";
<div ng-bind-html="name"></div>

This will result in http://jointstat.com/patients-caregivers/ John instead of showing <b>John</b> . That means it renders the html instead of showing html tag.

Click this link to view example

Minify files with UglifyJS using GULP.

gulp-uglify

Minify files with UglifyJS.

Install package with NPM and add it to your development dependencies:

npm install --save-dev gulp-uglify

var uglify = require(gulp-uglify);
 
gulp.task(compress, function() {
  return gulp.src(lib/*.js)
    .pipe(uglify())
    .pipe(gulp.dest(dist));
});
  • mangle

    Pass false to skip mangling names.

  • output

    Pass an object if you wish to specify additional output options. The defaults are optimized for best compression.

  • compress

    Pass an object to specify custom compressor options. Pass false to skip compression completely.

  • preserveComments

    A convenience option for options.output.comments. Defaults to preserving no comments.

    • all

      Preserve all comments in code blocks

    • license

      Attempts to preserve comments that likely contain licensing information, even if the comment does not have directives such as @license or /*!.

      Implemented via the uglify-save-license module, this option preserves a comment if one of the following is true:

      1. The comment is in the first line of a file
      2. A regular expression matches the string of the comment. For example: MIT, @license, or Copyright.
      3. There is a comment at the previous line, and it matches 1, 2, or 3.
    • function

      Specify your own comment preservation function. You will be passed the current node and the current comment and are expected to return either true or false.

    • some (deprecated)

      Preserve comments that start with a bang (!) or include a Closure Compiler directive (@preserve, @license,@cc_on). Deprecated in favor of the license option, documented above.

You can also pass the uglify function any of the options listed here to modify UglifyJS’s behavior.

gulp-uglify emits an ‘error’ event if it is unable to minify a specific file. Wherever possible, the PluginError object will contain the following properties:

  • fileName
  • lineNumber
  • message

To handle errors across your entire pipeline, see the gulp documentation.

ui-router ui-sref

ui-sref

directive in module ui.router.state

Description

A directive that binds a link (<a> tag) to a state. If the state has an associated URL, the directive will automatically generate & update the hrefattribute via the $state.href() method. Clicking the link will trigger a state transition with optional parameters.

Also middle-clicking, right-clicking, and ctrl-clicking on the link will be handled natively by the browser.

You can also use relative state paths within ui-sref, just like the relative paths passed to $state.go(). You just need to be aware that the path is relative to the state that the link lives in, in other words the state that loaded the template containing the link.

You can specify options to pass to $state.go() using the ui-sref-opts attribute. Options are restricted to location, inherit, and reload.

Dependencies

Usage

as attribute

  1. <ANY ui-sref=“{string}”
  2. ui-sref-opts=“{Object}”>
  3. </ANY>

Parameters

Param Type Details
ui-sref string

‘stateName’ can be any valid absolute or relative state

ui-sref-opts Object

options to pass to $state.go()

Example

Here’s an example of how you’d use ui-sref and how it would compile. If you have the following template:

  1. <a ui-sref=“home”>Home</a> | <a ui-sref=“about”>About</a> | <a ui-sref=“{page: 2}”>Next page</a>
  2.  
  3. <ul>
  4. <li ng-repeat=“contact in contacts”>
  5. <a ui-sref=“contacts.detail({ id: contact.id })”>{{ contact.name }}</a>
  6. </li>
  7. </ul>

Then the compiled html would be (assuming Html5Mode is off and current state is contacts):

  1. <a href=“#/home” ui-sref=“home”>Home</a> | <a href=“#/about” ui-sref=“about”>About</a> | <a href=“#/contacts?page=2” ui-sref=“{page: 2}”>Next page</a>
  2.  
  3. <ul>
  4. <li ng-repeat=“contact in contacts”>
  5. <a href=“#/contacts/1” ui-sref=“contacts.detail({ id: contact.id })”>Joe</a>
  6. </li>
  7. <li ng-repeat=“contact in contacts”>
  8. <a href=“#/contacts/2” ui-sref=“contacts.detail({ id: contact.id })”>Alice</a>
  9. </li>
  10. <li ng-repeat=“contact in contacts”>
  11. <a href=“#/contacts/3” ui-sref=“contacts.detail({ id: contact.id })”>Bob</a>
  12. </li>
  13. </ul>
  14.  
  15. <a ui-sref=“home” ui-sref-opts=“{reload: true}”>Home</a>

Custom AngularJS Directives

In the first post in this series I introduced custom directives in AngularJS and showed a few simple examples of getting started. In this post we’re going to explore the topic of Isolate Scope and see how important it is when building directives.

What is Isolate Scope?

Directives have access to the parent scope by default in AngularJS applications. For example, the following directive relies on the parent scope to write out a customer object’s name and street properties:

 

angular.module('directivesModule').directive('mySharedScope', function () {
    return {
        template: 'Name: {{customer.name}} Street: {{customer.street}}'
    };
});

Although this code gets the job done, you have to know a lot about the parent scope in order to use the directive and could just as easily use ng-include and an HTML template to accomplish the same thing (this was discussed in the first post). If the parent scope changes at all the directive is no longer useful.

If you want to make a reuseable directive you can’t rely on the parent scope and must use something calledIsolate Scope instead. Here’s a diagram that compares shared scope with isolate scope:

 

image

 

Looking at the diagram you can see that shared scope allows the parent scope to flow down into the directive. Isolate scope on the other hand doesn’t work that way. With isolate scope it’s as if you’re creating a wall around your directive that can’t be penetrated by the parent scope. Here’s a (silly) visual of that concept just in case you need further clarification:

image

Creating Isolate Scope in a Directive

Isolating the scope in a directive is a is a simple process. Start by adding a scope property into the directive as shown next. This automatically isolates the directive’s scope from any parent scope(s).

angular.module('directivesModule').directive('myIsolatedScope', function () {
    return {
        scope: {},
        template: 'Name: {{customer.name}} Street: {{customer.street}}'
    };
});

Now that the scope is isolated, the customer object from the parent scope will no longer be accessible. When the directive is used in a view it’ll result in the following output (notice that the customer name and street values aren’t rendered):

Name: Street:
Since the directive is now completely cut-off from the parent scope how do we pass data into the directive for data binding purposes? You use @, =, and & characters which seems a bit strange at first glance but isn’t too bad once you understand what the characters represent. Let’s take a look at how these characters can be used in directives.

 

Introducing Local Scope Properties

Directives that use isolate scope provide 3 different options to interact with the outside world (the world on the other side of the wall). The 3 options are referred to as Local Scope Properties and can be defined using the @, =, and & characters mentioned earlier. Here’s how they work.

@ Local Scope Property

The @ local scope property is used to access string values that are defined outside the directive. For example, a controller may defined a name property on the $scope object and you need to get access to that property within the directive. To do that, you can use @ within the directive’s scope property. Here’s a high level example of that concept with a step-by-step explanation:

image

  1. A controller defines $scope.name.
  2. The $scope.name property value needs to be passed into the directive.
  3. The directive creates a custom local scope property within its isolate scope named name (note that the property can be named anything and doesn’t have to match with the $scope object’s property name). This is done using scope { name: ‘@’ }.
  4. The @ character tells the directive that the value passed into the new name property will be accessed as a string. If the outside value changes the name property in the directive’s isolate scope will automatically be updated.
  5. The template within the directive can now bind to the isolate scope’s name property.

Here’s an example of putting all of the steps together. Assume that the following controller is defined within an app:

 

var app = angular.module('directivesModule', []);

app.controller('CustomersController', ['$scope', function ($scope) {
    var counter = 0;
    $scope.customer = {
        name: 'David',
        street: '1234 Anywhere St.'
    };
            
    $scope.customers = [
        {
            name: 'David',
            street: '1234 Anywhere St.'
        },
        {
            name: 'Tina',
            street: '1800 Crest St.'
        },
        {
            name: 'Michelle',
            street: '890 Main St.'
        }
    ];

    $scope.addCustomer = function () {
        counter++;
        $scope.customers.push({
            name: 'New Customer' + counter,
            street: counter + ' Cedar Point St.'
        });
    };

    $scope.changeData = function () {
        counter++;
        $scope.customer = {
            name: 'James',
            street: counter + ' Cedar Point St.'
        };
    };
}]);

The directive code creates an isolate scope that allows a name property to be bound to a value that is passed in from the “outside world”:

angular.module('directivesModule').directive('myIsolatedScopeWithName', function () {
    return {
        scope: {
            name: '@'
        },
        template: 'Name: {{ name }}'
    };
});

The directive can be used in the following way:

<div my-isolated-scope-with-name name="{{ customer.name }}"></div>

Notice how the $scope.customer.name value from the controller is bound to the name property of the directive’s isolate scope. The content rendered by the directive is shown next:

Name: David

As mentioned earlier, if the $scope.customer.name value changes, the directive will automatically pick up the change. However, if the directive changes its name property, the outside value in $scope.customer.name will not change in this case. If you need to keep properties in-sync check out the = local scope property that’s covered next.

It’s important to note that if you want the local scope property name to be different from the property name used when the directive is defined in a view that you can use the following alternate syntax:

angular.module('directivesModule').directive('myIsolatedScopeWithName', function () {
    return {
        scope: {
            name: '@someOtherName'
        },
        template: 'Name: {{ name }}'
    };
});

In this case the name property will be used internally within the directive while someOtherName will be used by the consumer of the directive to pass data into it:

<div my-isolated-scope-with-name someOtherName="{{ customer.name }}"></div>

I prefer to keep local scope property names the same as the attributes defined on the directive in a view so I don’t typically use this approach. However, there may be situations where you need this flexibility. It’s available when using @, =, and & to define local scope properties.

= Local Scope Property

The @ character works well for accessing a string value that is passed into a directive as shown in the previous example. However, it won’t keep changes made in the directive in-sync with the external/outer scope. In cases where you need to create a two-way binding between the outer scope and the directive’s isolate scope you can use the = character. Here’s a high level example of that concept with a step-by-step explanation:

 

image

 

  1. A controller defines a $scope.person object.
  2. The $scope.person object needs to be passed into the directive in a way that creates a two-way binding.
  3. The directive creates a custom local scope property within its isolate scope named customer. This is done using scope { customer: ‘=’ }.
  4. The = character tells the directive that the object passed into the customer property should be bound using a two-way binding. If the outside property value changes then the directive’s customer property should automatically be updated. If the directive’s customer property changes then the object in the external scope should automatically  be updated.
  5. The template within the directive can now bind to the isolate scope’s customer property.

Here’s an example of a directive that uses the = local scope property to define a property in the isolate scope.

angular.module('directivesModule').directive('myIsolatedScopeWithModel', function () {
    return {
        scope: {
            customer: '=' //Two-way data binding
        },
        template: '<ul><li ng-repeat="prop in customer">{{ prop }}</li></ul>'
    };
});

In this example the directive takes the object provided to the customer property and iterates through all of the properties in the object using ng-repeat. It then writes out the property values using <li> elements.

To pass data into the directive the following code can be used:

<div my-isolated-scope-with-model customer="customer"></div>

Notice that with the = local scope property you don’t pass {{ customer }} as with @. You instead pass the name of the property directly. In this example the customer object passed into the directive’s customer local scope property comes from the controller shown earlier. The directive iterates through all of the properties in the customer object using ng-repeat and writes them out. This yields the following output:

  • David
  • 1234 Anywhere St.

& Local Scope Property

At this point you’ve seen how to use local scope properties to pass values into a directive as strings (@) and how to bind to external objects using a two-way data binding technique (=). The final local scope property uses the &character and is used to bind to external functions.

The & local scope property allows the consumer of a directive to pass in a function that the directive can invoke. For example, let’s assume you’re writing a directive and as the end user clicks on a button that the directive emits you want to notify the controller. You can’t hard-code the click function to use in the directive since the controller would never know that anything happened. Raising an event could get the job done (using $emit or $broadcast) but the controller would have to know the specific event name to listen for which isn’t optimal either.

A better approach would be to let the consumer of the directive pass in a function that the directive can invoke as it needs. Whenever the directive does useful work (such as detecting when a user clicked on a button) it could then invoke the function that was passed into it. That way the consumer of the directive has 100% control over what happens and the directive simply delegates control to the function that was passed in. Here’s a high-level example of that concept with a step-by-step example:

image

  1. A controller defines a $scope.click function.
  2. The $scope.click function needs to be passed into the directive so that the directive can invoke it when a button is clicked.
  3. The directive creates a custom local scope property within its isolate scope named action. This is done using scope { action: ‘&’ }. In this example action is really just an alias for click.  When action is invoked the click function that was passed in will be called.
  4. The & character is basically saying, “Hey, pass me a function that I can invoke when something happens inside of the directive!”.
  5. The template within the directive may contain a button. When the button is clicked the action (which is really a reference to the external function that was passed in) can then be invoked.

Here’s an example of the & local scope property in action:

angular.module('directivesModule').directive('myIsolatedScopeWithModelAndFunction', function () {
    return {
        scope: {
            datasource: '=',
            action: '&'
        },
        template: '<ul><li ng-repeat="prop in datasource">{{ prop }}</li></ul> ' +
                  '<button ng-click="action()">Change Data</button>'
    };
});

Notice that the following code from the directive’s template refers to the action local scope property and invokes it (since it’s simply a reference to a function) as the button is clicked. This delegates control to whatever function was passed to action.

<button ng-click="action()">Change Data</button>

Here’s an example of using the directive. I’d of course recommend picking a shorter name for your “real life” directives.

<div my-isolated-scope-with-model-and-function 
     datasource="customer" 
     action="changeData()">
</div>

The changeData() function passed into the action property is defined in the controller shown at the beginning of this post. It changes the name and address when invoked:

$scope.changeData = function () {
      counter++;
      $scope.customer = {
          name: 'James',
          street: counter + ' Cedar Point St.'
      };
};

Conclusion

At this point in the custom AngularJS directives series you’ve seen several of the key aspects available in directives such as templates, isolate scope, and local scope properties. As a review, isolate scope is created in a directive by using the scope property and assigning it an object literal. Three types of local scope properties can be added into isolate scope including:

  • @  Used to pass a string value into the directive
  • =    Used to create a two-way binding to an object that is passed into the directive
  • &    Allows an external function to be passed into the directive and invoked

AngularJS : copy vs extend

While using AngularJS, we come across some situation in which we need to copy one object to another object. In that case, we probably have two solutions: angular.copy() or angular.extend(). Lets see how they work differently.

1. angular.copy(source, destination) : It creates a deep copy of source object or array and assign it to destination where ‘destination’ is optional. By writing deep copy, we mean that a new copy of the referred object is made. For example:

1
2
3
4
var mySource = {'name' : 'sakshi', 'age' : '24', 'obj' :{'key':'value'}}
var myDest = {}
angular.copy(mySource, myDest);
console.log(myDest);

Output: {'name' : 'sakshi', 'age' : '24', 'obj' :{'key':'value'}}

If we check mySource.obj === myDest.obj, this will give false because both point to different objects. This is called as deep copying.

2. angular.extend(destination, src1, src2 …) : It creates a shallow copy of one or more sources provided and assign them to destination. For example:

1
2
3
4
5
var mySource1 = {'name' : 'neha', 'age' : '26', obj2 : {}}
var mySource2 = {'course' : 'MCA'}
var myDest = {}
angular.extend(myDest, mySource1,mySource2)
console.log(myDest);

Output: {name: "neha", age: "26", course: "MCA", obj2: Object}

Now we check mySource1.obj2 === myDest.obj2, this will give true because both point to same reference of object. This is called as shallow copying.

NOTE: angular.copy() is slower than angular.extend()

So, by keeping these points into mind, we can make our decision of when to use copy and when to use extend.

Token Based Authentication using ASP.NET Web API 2, Owin, and Identity

The demo application can be accessed on (http://ngAuthenticationWeb.azurewebsites.net). The back-end API can be accessed on (http://ngAuthenticationAPI.azurewebsites.net/) and both are hosted on Microsoft Azure, for learning purposes feel free to integrate and play with the back-end API with your front-end application. The API supports CORS and accepts HTTP calls from any origin. You can check the source code for this tutorial on Github.

AngularJS Authentication

 

Token Based Authentication

As I stated before we’ll use token based approach to implement authentication between the front-end application and the back-end API, as we all know the common and old way to implement authentication is the cookie-based approach were the cookie is sent with each request from the client to the server, and on the server it is used to identify the authenticated user.

With the evolution of front-end frameworks and the huge change on how we build web applications nowadays the preferred approach to authenticate users is to use signed token as this token sent to the server with each request, some of the benefits for using this approach are:

  • Scalability of Servers: The token sent to the server is self contained which holds all the user information needed for authentication, so adding more servers to your web farm is an easy task, there is no dependent on shared session stores.
  • Loosely Coupling: Your front-end application is not coupled with specific authentication mechanism, the token is generated from the server and your API is built in a way to understand this token and do the authentication.
  • Mobile Friendly: Cookies and browsers like each other, but storing cookies on native platforms (Android, iOS, Windows Phone) is not a trivial task, having standard way to authenticate users will simplify our life if we decided to consume the back-end API from native applications.

What we’ll build in this tutorial?

The front-end SPA will be built using HTML5, AngularJS, and Twitter Bootstrap. The back-end server will be built using ASP.NET Web API 2 on top of Owin middleware not directly on top of ASP.NET; the reason for doing so that we’ll configure the server to issue OAuth bearer token authentication using Owin middleware too, so setting up everything on the same pipeline is better approach. In addition to this we’ll use ASP.NET Identity system which is built on top of Owin middleware and we’ll use it to register new users and validate their credentials before generating the tokens.

As I mentioned before our back-end API should accept request coming from any origin, not only our front-end, so we’ll be enabling CORS (Cross Origin Resource Sharing) in Web API as well for the OAuth bearer token provider.

Use cases which will be covered in this application:

  • Allow users to signup (register) by providing username and password then store credentials in secure medium.
  • Prevent anonymous users from viewing secured data or secured pages (views).
  • Once the user is logged in successfully, the system should not ask for credentials or re-authentication for the next 24 hours 30 minutes because we are using refresh tokens.

So in this post we’ll cover step by step how to build the back-end API, and on the next post we’ll cover how we’ll build and integrate the SPA with the API.

Enough theories let’s get our hands dirty and start implementing the API!

Building the Back-End API

Step 1: Creating the Web API Project

In this tutorial I’m using Visual Studio 2013 and .Net framework 4.5, you can follow along using Visual Studio 2012 but you need to install Web Tools 2013.1 for VS 2012 by visiting this link.

Now create an empty solution and name it “AngularJSAuthentication” then add new ASP.NET Web application named “AngularJSAuthentication.API”, the selected template for project will be as the image below. Notice that the authentication is set to “No Authentication” taking into consideration that we’ll add this manually.

Web API Project Template

Step 2: Installing the needed NuGet Packages:

Now we need to install the NuGet packages which are needed to setup our Owin server and configure ASP.NET Web API to be hosted within an Owin server, so open NuGet Package Manger Console and type the below:

The  package “Microsoft.Owin.Host.SystemWeb” is used to enable our Owin server to run our API on IIS using ASP.NET request pipeline as eventually we’ll host this API on Microsoft Azure Websites which uses IIS.

Step 3: Add Owin “Startup” Class

Right click on your project then add new class named “Startup”. We’ll visit this class many times and modify it, for now it will contain the code below:

What we’ve implemented above is simple, this class will be fired once our server starts, notice the “assembly” attribute which states which class to fire on start-up. The “Configuration” method accepts parameter of type “IAppBuilder” this parameter will be supplied by the host at run-time. This “app” parameter is an interface which will be used to compose the application for our Owin server.

The “HttpConfiguration” object is used to configure API routes, so we’ll pass this object to method “Register” in “WebApiConfig” class.

Lastly, we’ll pass the “config” object to the extension method “UseWebApi” which will be responsible to wire up ASP.NET Web API to our Owin server pipeline.

Usually the class “WebApiConfig” exists with the templates we’ve selected, if it doesn’t exist then add it under the folder “App_Start”. Below is the code inside it:

Step 4: Delete Global.asax Class

No need to use this class and fire up the Application_Start event after we’ve configured our “Startup” class so feel free to delete it.

Step 5: Add the ASP.NET Identity System

After we’ve configured the Web API, it is time to add the needed NuGet packages to add support for registering and validating user credentials, so open package manager console and add the below NuGet packages:

The first package will add support for ASP.NET Identity Owin, and the second package will add support for using ASP.NET Identity with Entity Framework so we can save users to SQL Server database.

Now we need to add Database context class which will be responsible to communicate with our database, so add new class and name it “AuthContext” then paste the code snippet below:

As you can see this class inherits from “IdentityDbContext” class, you can think about this class as special version of the traditional “DbContext” Class, it will provide all of the Entity Framework code-first mapping and DbSet properties needed to manage the identity tables in SQL Server. You can read more about this class on Scott Allen Blog.

Now we want to add “UserModel” which contains the properties needed to be sent once we register a user, this model is POCO class with some data annotations attributes used for the sake of validating the registration payload request. So under “Models” folder add new class named “UserModel” and paste the code below:

Now we need to add new connection string named “AuthContext” in our Web.Config class, so open you web.config and add the below section:

Step 6: Add Repository class to support ASP.NET Identity System

Now we want to implement two methods needed in our application which they are: “RegisterUser” and “FindUser”, so add new class named “AuthRepository” and paste the code snippet below:

What we’ve implemented above is the following: we are depending on the “UserManager” that provides the domain logic for working with user information. The “UserManager” knows when to hash a password, how and when to validate a user, and how to manage claims. You can read more about ASP.NET Identity System.

Step 7: Add our “Account” Controller

Now it is the time to add our first Web API controller which will be used to register new users, so under file “Controllers” add Empty Web API 2 Controller named “AccountController” and paste the code below:

By looking at the “Register” method you will notice that we’ve configured the endpoint for this method to be “/api/account/register” so any user wants to register into our system must issue HTTP POST request to this URI and the pay load for this request will contain the JSON object as below:

Now you can run your application and issue HTTP POST request to your local URI: “http://localhost:port/api/account/register” or you can try the published API using this end point: http://ngauthenticationapi.azurewebsites.net/api/account/register if all went fine you will receive HTTP status code 200 and the database specified in connection string will be created automatically and the user will be inserted into table “dbo.AspNetUsers”.

Note: It is very important to send this POST request over HTTPS so the sensitive information get encrypted between the client and the server.

The “GetErrorResult” method is just a helper method which is used to validate the “UserModel” and return the correct HTTP status code if the input data is invalid.

Step 8: Add Secured Orders Controller

Now we want to add another controller to serve our Orders, we’ll assume that this controller will return orders only for Authenticated users, to keep things simple we’ll return static data. So add new controller named “OrdersController” under “Controllers” folder and paste the code below:

Notice how we added the “Authorize” attribute on the method “Get” so if you tried to issue HTTP GET request to the end point “http://localhost:port/api/orders” you will receive HTTP status code 401 unauthorized because the request you send till this moment doesn’t contain valid authorization header. You can check this using this end point: http://ngauthenticationapi.azurewebsites.net/api/orders

Step 9: Add support for OAuth Bearer Tokens Generation

Till this moment we didn’t configure our API to use OAuth authentication workflow, to do so open package manager console and install the following NuGet package:

After you install this package open file “Startup” again and call the new method named “ConfigureOAuth” as the first line inside the method “Configuration”, the implemntation for this method as below:

Here we’ve created new instance from class “OAuthAuthorizationServerOptions” and set its option as the below:

  • The path for generating tokens will be as :”http://localhost:port/token”. We’ll see how we will issue HTTP POST request to generate token in the next steps.
  • We’ve specified the expiry for token to be 24 hours, so if the user tried to use the same token for authentication after 24 hours from the issue time, his request will be rejected and HTTP status code 401 is returned.
  • We’ve specified the implementation on how to validate the credentials for users asking for tokens in custom class named “SimpleAuthorizationServerProvider”.

Now we passed this options to the extension method “UseOAuthAuthorizationServer” so we’ll add the authentication middleware to the pipeline.

Step 10: Implement the “SimpleAuthorizationServerProvider” class

Add new folder named “Providers” then add new class named “SimpleAuthorizationServerProvider”, paste the code snippet below:

As you notice this class inherits from class “OAuthAuthorizationServerProvider”, we’ve overridden two methods “ValidateClientAuthentication” and “GrantResourceOwnerCredentials”. The first method is responsible for validating the “Client”, in our case we have only one client so we’ll always return that its validated successfully.

The second method “GrantResourceOwnerCredentials” is responsible to validate the username and password sent to the authorization server’s token endpoint, so we’ll use the “AuthRepository” class we created earlier and call the method “FindUser” to check if the username and password are valid.

If the credentials are valid we’ll create “ClaimsIdentity” class and pass the authentication type to it, in our case “bearer token”, then we’ll add two claims (“sub”,”role”) and those will be included in the signed token. You can add different claims here but the token size will increase for sure.

Now generating the token happens behind the scenes when we call “context.Validated(identity)”.

To allow CORS on the token middleware provider we need to add the header “Access-Control-Allow-Origin” to Owin context, if you forget this, generating the token will fail when you try to call it from your browser. Not that this allows CORS for token middleware provider not for ASP.NET Web API which we’ll add on the next step.

Step 11: Allow CORS for ASP.NET Web API

First of all we need to install the following NuGet package manger, so open package manager console and type:

Now open class “Startup” again and add the highlighted line of code (line 8) to the method “Configuration” as the below:

Step 12: Testing the Back-end API

Assuming that you registered the username “Taiseer” with password “SuperPass” in the step below, we’ll use the same username to generate token, so to test this out open your favorite REST client application in order to issue HTTP requests to generate token for user “Taiseer”. For me I’ll be using PostMan.

Now we’ll issue a POST request to the endpoint http://ngauthenticationapi.azurewebsites.net/token the request will be as the image below:

OAuth Token Request

Notice that the content-type and payload type is “x-www-form-urlencoded” so the payload body will be on form (grant_type=password&username=”Taiseer”&password=”SuperPass”). If all is correct you’ll notice that we’ve received signed token on the response.

As well the “grant_type” Indicates the type of grant being presented in exchange for an access token, in our case it is password.

Now we want to use this token to request the secure data using the end point http://ngauthenticationapi.azurewebsites.net/api/orders so we’ll issue GET request to the end point and will pass the bearer token in the Authorization header, so for any secure end point we’ve to pass this bearer token along with each request to authenticate the user.

Note: that we are not transferring the username/password as the case of Basic authentication.

The GET request will be as the image below:

Token Get Secure Resource

If all is correct we’ll receive HTTP status 200 along with the secured data in the response body, if you try to change any character with signed token you directly receive HTTP status code 401 unauthorized.

Now our back-end API is ready to be consumed from any front end application or native mobile app.

taken from:http://bitoftech.net/2014/06/01/token-based-authentication-asp-net-web-api-2-owin-asp-net-identity/

angular.copy

I wonder if there is away to avoid copying references to objects when you need to create a simple object which has an array of embedded objects.The situation is as follow: I have server which accepts a JSON and applies some logic then stores the object in DB. lets say my form is for saving teams in DB. The server accepts team as json. the team has an array of TeamMember objects, my form has a simple field to enter team member info and add it to team teamMembers array. Now here is the problem, when I add a team member to array list and want to add another team member when I type into the field the added member is changed also !. I know the reason

$scope.addTeamMember=function(teamMember){
   $scope.team.teamMembers.push(teamMember);
}

and it is because I put same reference into the teamMembers array so I have same object added several times. to avoid this I should create a new team member object, copy all teamMember properties and and add it the array.

 $scope.addTeamMember=function(teamMember){
       var newTeamMember; /*<--- copy teamMember */
       $scope.team.teamMembers.push(newTeamMember); /*and add newTeamMember*/
    }

Your question says you want to “avoid deep copy”, but I’m not sure that’s accurate. It sounds like you just want to use angular.copy, because you need to create a copy of the team member and add that to the array:

$scope.addTeamMember = function(teamMember) {
   var newTeamMember = angular.copy(teamMember);
   $scope.team.teamMembers.push(newTeamMember);
};
<!doctype html>
<html lang="en">
<head>
 <meta charset="UTF-8">
 <title>Example - example-example46-production</title>
 

 <script src="//ajax.googleapis.com/ajax/libs/angularjs/1.4.3/angular.min.js"></script>
 

 
</head>
<body ng-app="copyExample">
 <div ng-controller="ExampleController">
<form novalidate class="simple-form">
Name: <input type="text" ng-model="user.name" /><br />
E-mail: <input type="email" ng-model="user.email" /><br />
Gender: <input type="radio" ng-model="user.gender" value="male" />male
<input type="radio" ng-model="user.gender" value="female" />female<br />
<button ng-click="reset()">RESET</button>
<button ng-click="update(user)">SAVE</button>
</form>
<pre>form = {{user | json}}</pre>
<pre>master = {{master | json}}</pre>
</div>

<script>
 angular.module('copyExample', [])
 .controller('ExampleController', ['$scope', function($scope) {
 $scope.master= {};

 $scope.update = function(user) {
 // Example with 1 argument
 $scope.master= angular.copy(user);
 };

 $scope.reset = function() {
 // Example with 2 arguments
 angular.copy($scope.master, $scope.user);
 };

 $scope.reset();
 }]);
</script>
</body>
</html>

ANGULARJS AND/VS JQUERY

Basically, jQuery is a great tool for you to manipulate and control DOM elements. If you only focus on DOM elements and no Data CRUD, like building a website not web application, jQuery is the one of the top tools. (You can use AngularJS for this purpose as well.)

AngularJS is a framework. It has following features

  1. Two way data binding
  2. MVW pattern (MVC-ish)
  3. Template
  4. Custom-directive (reusable components, custom markup)
  5. REST-friendly
  6. Deep Linking (set up a link for any dynamic page)
  7. Form Validation
  8. Server Communication
  9. Localization
  10. Dependency injection
  11. Full testing environment (both unit, e2e)

    AngularJS : AngularJS is for developing heavy web applications. AngularJS can use jQuery if it’s present in the web-app when the application is being bootstrapped. If it’s not present in the script path, then AngularJS falls back to its own implementation of the subset of jQuery.

    JQuery : jQuery is a small, fast, and feature-rich JavaScript library. It makes things like HTML document traversal and manipulation, event handling, animation, and Ajax much simpler. jQuery simplifies a lot of the complicated things from JavaScript, like AJAX calls and DOM manipulation.