ASP.NET Core 1 – Authorization using Policies

The goal of this post is to show how can we protect controller actions in ASP.NET Core 1 using Policies.

The whole code is available on GitHub: ASP.NET Core 1, Security using Policies.

With policies we don’t need to hard code anymore Roles or Names in our Authorize attribute. A policy is an authorization logic that contains one of more requirements.

How to use a policy?

The concept is very simple, once we have a defined policy we can add it to our Authorize attributes…

How to create a policy?

We have to define our policies in our Startup class, in ConfigureServices. We need a policy name, a list of valid authentication schemes and a list of requirements.

We can add more than one requirement to our policy, there are some pre-build requirements:

  • policy.RequireAuthenticatedUser()
  • policy.RequireClaim(…)
  • policy.RequireRole(…)

But the more flexible way is to add a custom requirement, doing this we can write our own logic:

  • policy.AddRequirements(new IsGoodMonsterRequirement());

To write our requirement we use the base class AuthorizationHandler and implement the interface IAuthorizationRequirement.

This requirement checks that the user is authenticated and has the claim “MonsterTypeClaim” = “Good”

Getting Started with ASP NET Core 1 and Angular 2 in Visual Studio 2015

The goal of this post is to set up a Visual Studio 2015 project with ASP NET Core 1 and Angular 2 Typescript that can be used as a template for all my projects.

ASP NET Core1 Logo         angular2Logo

The whole code is available on GitHub: https://github.com/softwarejc/angular2-aspmvc-core1-getting-started

We will use npm (Node Package Manager) to add our dependencies and we will configure the typescript transpiler integrated in Visual Studio. We will also configure a gulp task to bundle our javascript an css dependencies.

Content

  • Introduction
  • Install Pre-requisites
  • Create an empty ASP Core 1 project
  • Auto transpile Typescript after save
  • Add Angular 2 with npm
  • Set up gulp task to bundle dependencies

Introduction

The former ASP.NET 5 was renamed to .NET Core 1. It is a modular Microsoft runtime library implementation that includes a subset of the .NET Framework.

.NET Core 1 was written from scratch. It has a lot of advantages, for example it is lighter, open-source and multi-platform: Mac, Linux and Windows.

Although the version 1 is in Release Candidate there are some ASP.NET 4.6 features missing, like SignalR.

It is up to you to choose a mature Framework like ASP.NET 4.6 or a modern one like ASP.NET Core 1… you can read more about it in this post by Scott Hanselman. I copied the following diagram from that post🙂.

ASPNET Core 1

Install Pre-requisites

There are some problems in Windows using npm version 2. It nest dependencies and ends up having too long paths for Windows. Let’s start updating npm to version 3 and configuring Visual Studio to use it.

The first thing that we should do is to install Python version 2.7.X and NodeJS version 4.2.X. Remember the path where you install NodeJS, we will need it later.

Now open a command line and update npm:

npm install npm -g

Check your npm version:

npm -v

The version should be higher than 3.X.X.

Open visual studio and add the path where NodeJS is installed as the first path to look for external tools (at the top). The next time that Visual Studio has to restore a node package it will start looking for nodejs.exe in that path. The version we just installed will be found and used.

Configure VS to use npm 3

Create an empty ASP NET Core 1 project

Let’s create our project and configure a very simple server-side code.

In Visual Studio 2015 Update 1 ASP NET Core 1 is still called ASP NET 5. Create a new project and select the WebAPI template. Our project will have a SPA that will call a WebAPI controller to get a message.

Create ASPNET 5 Project

 

Delete the Project_Readme.html and update the values controller with this simple WebAPI controller that returns a hello message and the server UTC Time:

We will call this method later from angular to check that the communication between our SPA and the server works. For now we can call it from the browser to check it. Run the application and write something like this in your browser using your configured port:

http://localhost:10137/api/hello

You should see something like:

apiTest

You can also pass your name to check that the server receive your parameters:

http://localhost:10137/api/hello?name=JuanCarlos

The file Startup.cs contains the configuration of the middleware. We will see in a future post how it works and how to configure it to use features like authentication. The default configuration when you select a WebAPI project template is ok for us.

Auto transpile Typescript after save

We can tell Visual Studio to auto transpile always that we edit and save a typescript file enabling:

“Automatically compile TypeScript files which are not part of a project”
ts Compile on Save

Our files will be part of the project… but this is an easy way to make Visual Studio auto transpile. Running typescript compiler in watch mode is an alternative… but I like this solution because I have everything integrated in Visual Studio.

If you know a better way please leave me a comment.🙂

We will have a tsconfig.json file on the project root of our project to configure typescript, Visual Studio will use that file and not the settings that we configure in Options:

Add Angular 2 with npm

The application that we will use as an example will be a simple application that call the server to get a message and will display using Angular 2.

Let’s add Angular 2 and other dependencies to npm, we need a file called “package.json” on the root of our project:

Save the file and Visual Studio will create node_modules folder and download all dependencies for you.

It is out of the scope of this post to explain how Angular 2 works you can read more about it here. But basically we define a component that we can use in our index.

<hello></hello>

This component is a html view that has bindings to its code behind or “view-model”.

hello.view.html

hello.component.ts

The hello.component uses the service hello.service that makes REST calls to the server and returns Observable<T>.

hello.service.ts

We need to “start” / “bootstrap” our application. We will use System.JS to do that. This is this index.html where we “start” our Angular 2 app:

index.html

This is the piece of code of index.html that bootstrap our application:

System.import(‘./app/bootstrap’).then(null, console.error.bind(console));

And this is our bootstrap.ts:

Set up gulp task to bundle dependencies

Our index.html only references a style.css and a deps.js file. Those files are a bundle with all our dependencies. To create that bundle we will use gulp. We need this gulpfile.js on the root of our project:

We want to create our bundles automatically when we rebuild or clean the project (not in every build).

Open Task Runner Explorer and bind the clean and bundle tasks to the “Clean” Visual Studio event:

GulpBinding

This will trigger our tasks always that we clean or rebuild our solution. You can also add the bundle task to the “Before Build” event… but it can takes 8-10 seconds and normally the dependencies are not changing in every build.

We have a pre-configured project that hopefully will save us some time in the future!

If you know how to make it better please leave me a comment!

Have fun with ASP.NET Core and Angular 2!

Swift 2 examples – #12 Extensions. Show Loading Indicators and Alerts

This post is part of my collection: Swift 2 – For Beginners.

Swift extensions add new functionality to an existing class, structure, enumeration, or protocol type.

In this example we will see how to write a UIViewController extension to show loading indicators and alerts.

To add a class extensions we have to write something like:

extension UIViewController {
// write your extensions here
}

Show a loading indicator

Our first extension method will be a method that should show a loading indicator and disable the application so that the user cannot interact with it. To help the user understand that the application is disabled it should be grayed out.

To use this method we don’t need any parameter but we need a reference to the created indicator to hide it later:

var spinner = self.showModalSpinner()

To do this we can use the class UIActivityIndicatorView.

/**
Shows a loading indicator and disables user interaction with the app until it is hidden
*/
func showModalSpinner() ->UIActivityIndicatorView{

// user cannot interact with the app while the spinner is visible
UIApplication.sharedApplication().beginIgnoringInteractionEvents()

var indicator = UIActivityIndicatorView()

indicator = UIActivityIndicatorView(frame: self.view.frame)
indicator.center = self.view.center
indicator.backgroundColor = UIColor(white: 0.0, alpha: 0.5)
indicator.activityIndicatorViewStyle = UIActivityIndicatorViewStyle.Gray
indicator.hidesWhenStopped = true
indicator.startAnimating()

self.view.addSubview(indicator)

return indicator
}

Now we need a method to hide the spinner when our task was completed:

self.hideModalSpinner(self.spinnerView)
/**
Hides the loading indicator and enables user interaction with the app
*/
func hideModalSpinner(indicator: UIActivityIndicatorView){

indicator.stopAnimating()
indicator.hidden = true

// user can interact again with the app
UIApplication.sharedApplication().endIgnoringInteractionEvents()
}

If we put these two methods within a UIViewController extension we can use them like a normal method of the class.

Show an alert

Let’s add now a method to our extension to show an alert to the user, it should have an ‘ok’ button that will close the alert when the user taps it.

alert ios

I would like to have a very simple method that has only two parameters to indicate the title and message:

self.showAlert("Error", message: "Invalid user name / password.")

We can use the class UIAlertController to do that:

/**
Shows an alert with a title and a message
*/
func showAlert(title: String, message:String) {

let alertController = UIAlertController(title: title, message: message, preferredStyle: UIAlertControllerStyle.Alert)

// show the alert with a "ok" button that will close the alert
let okAction = UIAlertAction(title: "ok", style: UIAlertActionStyle.Default) { (action) -> Void in
self.dismissViewControllerAnimated(true, completion: nil)
}
alertController.addAction(okAction)

// show alert controller
self.presentViewController(alertController, animated: true, completion: nil)
}

Complete example:

import UIKit
extension UIViewController{

/**
Shows an alert with a title and a message
*/
func showAlert(title: String, message:String) {

let alertController = UIAlertController(title: title, message: message, preferredStyle: UIAlertControllerStyle.Alert)

// show the alert with a "ok" button that will close the alert
let okAction = UIAlertAction(title: "ok", style: UIAlertActionStyle.Default) { (action)-> Void in
self.dismissViewControllerAnimated(true, completion: nil)
}
alertController.addAction(okAction)

// show alert controller
self.presentViewController(alertController, animated: true, completion: nil)
}

/**
Shows a loading indicator and disables user interaction with the app until it is hidden
*/
func showModalSpinner()->UIActivityIndicatorView{

// user cannot interact with the app while the spinner is visible
UIApplication.sharedApplication().beginIgnoringInteractionEvents()

var indicator = UIActivityIndicatorView()

indicator = UIActivityIndicatorView(frame: self.view.frame)
indicator.center = self.view.center
indicator.backgroundColor = UIColor(white: 0.0, alpha: 0.5)
indicator.activityIndicatorViewStyle = UIActivityIndicatorViewStyle.Gray
indicator.hidesWhenStopped = true
indicator.startAnimating()

self.view.addSubview(indicator)

return indicator
}

/**
Hides the loading indicator and enables user interaction with the app
*/
func hideModalSpinner(indicator: UIActivityIndicatorView){

indicator.stopAnimating()
indicator.hidden = true

// user can interact again with the app
UIApplication.sharedApplication().endIgnoringInteractionEvents()
}
}

Swift 2 examples – #11 Loading images from the Photo Library and the Camera

This post is part of my collection: Swift 2 – For Beginners.

In this example we will see how to load photos in our application from the Photo Library and from the camera.

To open the photo library to pickup a photo we need a UIImagePickerController. Our controller can be the delegate. To do that we have to implement the protocols: UINavigationControllerDelegate and UIImagePickerControllerDelegate.

This code creates UIImagePickerController and use the method presentViewController to open the Photo Library:

  func selectImage(){
        let imagePickerController = UIImagePickerController()
        imagePickerController.delegate = self

        imagePickerController.sourceType = UIImagePickerControllerSourceType.PhotoLibrary
        imagePickerController.allowsEditing = true

        self.presentViewController(imagePickerController, animated: true, completion: nil)
    }

Once the user selects a photo our controller will be called back. Let’s implement a function that will load the selected image into a imageView:

   // Pick image finished, show selected image in a imageView
    func imagePickerController(picker: UIImagePickerController, didFinishPickingImage image: UIImage, editingInfo: [String : AnyObject]?) {
        // Show image
        imageView.image = image
        self.dismissViewControllerAnimated(true, completion: nil)
    }

To take a new photo using the camera we just change the value of imagePickerController.sourceType. Instead of PhotoLibrary we use Camera.

We can add a parameter to the previous function to specify the source of our image:

    func selectImage(from source: UIImagePickerControllerSourceType){
        let imagePickerController = UIImagePickerController()
        imagePickerController.delegate = self

        imagePickerController.sourceType = source
        imagePickerController.allowsEditing = true

        self.presentViewController(imagePickerController, animated: true, completion: nil)
    }

Complete example:

import UIKit

class ViewController: UIViewController,

    // 1 Allows navigation to camera or photo library to pick up a photo
    // used to set this controller as delegate of UIImagePickerController
    UINavigationControllerDelegate, UIImagePickerControllerDelegate
{

    override func viewDidLoad() {
        super.viewDidLoad()
    }

    @IBOutlet weak var imageView: UIImageView!

    @IBAction func addFromCamera(sender: AnyObject) {
        selectImage(from: UIImagePickerControllerSourceType.Camera)
    }

    @IBAction func addFromLibrary(sender: AnyObject) {
        selectImage(from: UIImagePickerControllerSourceType.PhotoLibrary)
    }

    // 2 Show image picker or camera app
    func selectImage(from source: UIImagePickerControllerSourceType){
        let imagePickerController = UIImagePickerController()
        imagePickerController.delegate = self

        imagePickerController.sourceType = source
        imagePickerController.allowsEditing = true

        self.presentViewController(imagePickerController, animated: true, completion: nil)
    }

    // 3 Pick image finished, show selected image
    func imagePickerController(picker: UIImagePickerController, didFinishPickingImage image: UIImage, editingInfo: [String : AnyObject]?) {
        // Show image
        imageView.image = image
        self.dismissViewControllerAnimated(true, completion: nil)
    }
}

Swift 2 examples – #10 Serialization to/from JSON using ObjectMapper

This post is part of my collection: Swift 2 – For Beginners.

JSON (JavaScript Object Notation) is a lightweight, human readable, open source, data-interchange format. In this example we will see how to serialize and deserialize objects to/from JSON using ObjectMapper in our iOS application.

For example, this would be the JSON representation of an object with two properties
name: string = “Juan Carlos”
age: Int = 29
JuanCarlosJSON

ObjectMapper is an open source project to make JSON Object mapping written in Swift. It is available in github: ObjectMapper.

Reference ObjectMapper using CocoaPods

CocoaPods is a dependency manager for Swift and Objective-C Cocoa projects. We will use it to reference ObjectMapper in our project. (If would also be possible to add it as a submodule. Check the project in GitHub for more information)

To add ObjectMapper to our project we need to execute the following commands:
Install cocoapods

sudo gem install cocoapods

Create Podfile in our project root

touch Podfile

To reference ObjectMapper add this content to the PodFile

use_frameworks!
pod 'ObjectMapper', '~> 1.0'

Select XCode path

sudo xcode-select --switch /Applications/Xcode.app

Add ObjectMapper repository

pod repo add ObjectMapper https://github.com/Hearst-DD/ObjectMapper.git

Install the project locally

pod install

Close XCode and open the created file *.xcworkspace. It contains our project and a reference to a new project called Pods. All our referenced projects will be contained in this new project.

Now we are ready to import and use ObjectMapper:

import ObjectMapper

Define our objects and implement the protocol “Mappeable”

To serialize and deserialize objects we must implement the protocol Mappeable.

// Mappeable source code
public protocol Mappable {
	init?(_ map: Map)
	mutating func mapping(map: Map)
}

Let’s write our User class, it will have two properties, name and age. The class will also implement the protocol Mappeable.

// Define our class and implement the Mappable protocol
class User: Mappable {
    var name: String?
    var age: Int = 0
    
    init(name: String, age: Int) {
        self.name = name
        self.age = age
    }
    
    // MARK: Mappable
    required init?(_ map: Map) {
        // subClasses must call the constructor of the base class
        // super.init(map)
    }

    func mapping(map: Map) {
        name <- map["name"]
        age  <- map["age"]
    }
}

Serialize and Deserialize objects

ObjectMapper is extremely easy to use:

        // Object to be serialized to JSON
        let myUser = User(name: "Juan Carlos", age: 29)

        // Convert Object to JSON
        let serializedUser = Mapper().toJSONString(myUser)
        print(serializedUser)
        
        // Convert JSON to Object
        if let deserializedUser = Mapper<User>().map(serializedUser){
            print(deserializedUser.name)
        }
        
        // Output:
        //  Optional("{\"age\":29,\"name\":\"Juan Carlos\"}")
        //  Optional("Juan Carlos")

Swift 2 examples – #9 Core Data. Create, get, update and remove entities

This post is part of my collection: Swift 2 – For Beginners.

Core Data is a persistence framework provided by Apple. In this example we will see how to use it in our iOS application. First we will see how to create our data model and then how to perform the following basic operations:

  • Create
  • Get by Id
  • Get all and Get applying a predicate
  • Update
  • Remove

How to create our data model

A data model consist of a group of entities. The concept of entity in Core Data is similar to the concept of table in SQL. Each entity can have attributes in the same way that a table can have columns.

To create a new entity you need a project with Core Data included. Then go to your xdatamodel file and click “Add Entity”, “Add Attribute” to configure it.

To keep the example simple our data model will have one entity with two attributes. A Person with name and age:

Person
-name: string
-age: integer

createEntity

To create a class that represent our data model click on “Editor” > “Create NSManagedObject Subclass…”.
Create NSManagedObject

It should create a class and an extension representing our entity “Person”. To that class we will only add a static field with the entity name, we will use it later to avoid magic strings:

extension Person {
    @NSManaged var name: String?
    @NSManaged var age: NSNumber?
}
class Person: NSManagedObject {
    // Add this line, the string must be equal to your class name
    static let entityName = "Person"
}

managedObjectContext

Before writing code to make our basic operations it is important to know what the managedObjectContext is.

When the project has Core Data Xcode add a bunch of code to our AppDelegate.swift. A piece of that code is the managedObjectContext. This is the object that we need to access the data model. We can get it in our controller with this line of code:

let context = (UIApplication.sharedApplication().delegate as! AppDelegate).managedObjectContext

To save our changes we always have to call context.save(). It can throw an exception so we have to make the call in a do.. catch.. block:

    // Saves all changes
    func saveChanges(){
        do{
            try context.save()
        } catch let error as NSError {
            // failure
            print(error)
        }
    }

Now we are ready to write our basic functions to access the data model:

Create

    // Creates a new Person
    func create(name: String, age: NSNumber) -> Person {
        
        let newItem = NSEntityDescription.insertNewObjectForEntityForName(Person.entityName, inManagedObjectContext: context) as! Person
        
        newItem.name = name
        newItem.age = age
        
        return newItem
    }

GetById

    // Gets a person by id
    func getById(id: NSManagedObjectID) -> Person? {
        return context.objectWithID(id) as? Person
    }

Get

Now we will see how to get all entities and how to get all entities applying a NSPredicate to our query.

    // Gets all with an specified predicate.
    // Predicates examples:
    // - NSPredicate(format: "name == %@", "Juan Carlos")
    // - NSPredicate(format: "name contains %@", "Juan")
    func get(withPredicate queryPredicate: NSPredicate) -> [Person]{
        let fetchRequest = NSFetchRequest(entityName: Person.entityName)
        
        fetchRequest.predicate = queryPredicate
        
        do {
            let response = try context.executeFetchRequest(fetchRequest)
            return response as! [Person]
            
        } catch let error as NSError {
            // failure
            print(error)
            return [Person]()
        }
    }

Our get all function will be a call to the previous function. The predicate will be a true predicate, to return all objects in our data model.

    // Gets all.
    func getAll() -> [Person]{
        return get(withPredicate: NSPredicate(value:true))
    }

Update

    // Updates a person
    func update(updatedPerson: Person){
        if let person = getById(updatedPerson.objectID){
            person.name = updatedPerson.name
            person.age = updatedPerson.age
        }
    }

Remove

    // Deletes a person
    func delete(id: NSManagedObjectID){
        if let personToDelete = getById(id){
            context.deleteObject(personToDelete)
        }
    }

Complete example:

This class puts all the functions that we have seen before together, we can call it PersonService.

import CoreData

class PersonService{
    
    var context: NSManagedObjectContext
    
    init(context: NSManagedObjectContext){
        self.context = context
    }
    
    // Creates a new Person
    func create(name: String, age: NSNumber) -> Person {
        
        let newItem = NSEntityDescription.insertNewObjectForEntityForName(Person.entityName, inManagedObjectContext: context) as! Person
        
        newItem.name = name
        newItem.age = age
        
        return newItem
    }
    
    // Gets a person by id
    func getById(id: NSManagedObjectID) -> Person? {
        return context.objectWithID(id) as? Person
    }
    
    // Gets all.
    func getAll() -> [Person]{
        return get(withPredicate: NSPredicate(value:true))
    }
    
    // Gets all that fulfill the specified predicate.
    // Predicates examples:
    // - NSPredicate(format: "name == %@", "Juan Carlos")
    // - NSPredicate(format: "name contains %@", "Juan")
    func get(withPredicate queryPredicate: NSPredicate) -> [Person]{
        let fetchRequest = NSFetchRequest(entityName: Person.entityName)
        
        fetchRequest.predicate = queryPredicate
        
        do {
            let response = try context.executeFetchRequest(fetchRequest)
            return response as! [Person]
            
        } catch let error as NSError {
            // failure
            print(error)
            return [Person]()
        }
    }
    
    // Updates a person
    func update(updatedPerson: Person){
        if let person = getById(updatedPerson.objectID){
            person.name = updatedPerson.name
            person.age = updatedPerson.age
        }
    }
    
    // Deletes a person
    func delete(id: NSManagedObjectID){
        if let personToDelete = getById(id){
            context.deleteObject(personToDelete)
        }
    }
    
    // Saves all changes
    func saveChanges(){
        do{
            try context.save()
        } catch let error as NSError {
            // failure
            print(error)
        }
    }
}

How to use the service:

        // Create an instance of the service.
        let context = (UIApplication.sharedApplication().delegate as! AppDelegate).managedObjectContext
        let personService = PersonService(context: context)
        
        // Create
        let juanCarlos = personService.create("Juan Carlos", age: 52)

        // Read all
        var people : [Person] = personService.getAll()

        // Read by id
        let firstPerson = personService.getById(people[0].objectID)!

        // Update
        firstPerson.name = "Juan Carlos Sanchez"
        personService.update(firstPerson)

        // Delete
        personService.delete(firstPerson.objectID)