RSS

Tag Archives: authentication

Web API .Net with Basic Authentication

Github project.

Notes:
1. This work on .Net framework 4.6.1.
2. Authorization part is not covered.

The core authentication code is in `Security/BasicAuthAttribute.cs`. This class inherit from following:

ActionFilterAttribute
So we can use it as attribute to decorate controllers or actions.

IAuthenticationFilter
To invoke WebApi’s authentication pipeline. Some developer like to use `IActionFilter` for authentication, while it may work, it is not a best practice as `IActionFilter` execute later in the WebApi stack.

IAuthenticationFilter implement 2 methods:
1. `AuthenticateAsync`. Run first. This is code to authentication user. Caller pass in credential in request header. First we begin by parsing the header and user name/password credential caller passed in. Then authenticate user, in Github project, I add user to generic principal but in production app, you should validate credential against security provider (ie: ADFS, Auth0), etc.
2. `ChallengeAsync`. Run after `AuthenticateAsync`. This is where authentication failed and we can challenge caller to prove them selves, which is done by passing `Authorization Basic` in response header.

Usage
There are 3 ways to use this attribute in WebApi.
1. Globally. Every actions will require authentication.

WebApiConfig.cs

public static void Register(HttpConfiguration config)
{
    // Add global authentication
    config.Filters.Add(new BasicAuthAttribute());

    // Web API routes
    config.MapHttpAttributeRoutes();

    config.Routes.MapHttpRoute(
        name: "DefaultApi",
        routeTemplate: "api/{controller}/{id}",
        defaults: new { id = RouteParameter.Optional }
    );
}

2. In entire controller. Every actions under that controller will require authentication. Notice the `[BasicAuth]` decoration.

ValuesController.cs

[BasicAuth]
public class ValuesController : ApiController
{
    public IEnumerable Get()
    {
        return new string[] { "value1", "value2" };
    }
            
    public string Get(int id)
    {
        return "value";
    }
}

3. In specific action. Notice the `[BasicAuth]` decoration.

ValuesController.cs

public class ValuesController : ApiController
{
    public IEnumerable Get()
    {
        return new string[] { "value1", "value2" };
    }

    [BasicAuth]
    public string Get(int id)
    {
        return "value";
    }
}
Advertisements
 
Leave a comment

Posted by on January 11, 2019 in General

 

Tags: , , , ,

Barebone Angular Project with Auth0

Simple project to demonstrate how to use Auth0 in Angular project, download code on Github.

To get started, you must have Auth0 account.
To setup the project, update following value in `environment.ts`:
1. Client ID. This is the id of your app you created in Auth0 dashboard. See here.
2. Client Domain. Your Auth0 domain to authenticate user. See here.
3. Callback Url. This is url Auth0 will redirect to after user is authenticated. This url must be white-listed in Auth0 dashboard. See here.
4. Logout Url. This is url Auth0 will redirect to after user logout. This url must be white-listed in Auth0 dashboard. See here.

The juice is on `service/auth.service.ts`, following are explanations of each methods:
1. Login
Call Auth0 authorize method to authenticate users. The method will redirect user to Auth0, if user is not authenticated, a login screen will displated, if user is authenticated Auth0 will redirect to callback endpoint and pass id token.

2. HandleAuthentication
Parse response object from Auth0 which contain id token, access token, expiration time and other information. Redirect user to appropriate url depend on the authorization results.

3. SetSession
Set authentication tokens and expiration in browser’s storage. User is authenticated.

4. Logout
Remove authentication tokens and expiration from browser’s storage. User is not authenticated anymore.

5. IsAuthenticated
Check browser’s storage to see if user is authenticated.

 
Leave a comment

Posted by on November 27, 2018 in General

 

Tags: , , , , , ,

Adding ASP.Net Identity (with OWIN) to Existing MVC 5 Project

The simple way is start empty MVC project with authentication and pick and choose ASP.Net Identity part you want to implement.

Here is the summary:

  • Install dependencies. See https://www.asp.net/identity/overview/getting-started/introduction-to-aspnet-identity, scroll down to “Components of ASP.Net Identity”
    • Entity Framework
    • OWIN
    • Microsoft.AspNet.Identity.Core
    • Microsoft.AspNet.Identity.EntityFramework
    • Microsoft.AspNet.Identity.Owin
    • Microsoft.Owin
    • Microsoft.Owin.Host.SystemWeb
    • Microsoft.Owin.Security
    • Microsoft.Owin.Security.Cookies
    • Microsoft.Owin.Security.OAuth
    • Microsoft.Owin.Security.Google (if you want allow external login with Google)
    • Microsoft.Owin.Security.Facebook (if you want allow external login with Facebook)
    • Microsoft.Owin.Security.Twitter (if you want allow external login with Twitter)
    • Netwonsoft.Json
  • In Web.config
    • Under
      <system.web>

      Add

      <authentication mode="None" />

      This is to remove IIS authentication, because we are going to use OWIN

    • Add all OWIN dependencies
  • Add Startup.cs. This is a startup class run by OWIN
    • Don’t forget its dependency, Startup.Auth.cs in App_Start folder
  • Add all classes in IdentityConfig.cs
    • There are 4 classes, EmailService, SmsService, ApplicationUserManager, ApplicationSignInManager. I’d like to separate them into different files
  • Add all classes in IdentityModels.cs
    • There are 2 classes, ApplicationUser, ApplicationDbContext. I’d like to separate them into different files

Those are the basic setup needed for ASP.Net Identity. The rest of the setup is front-end side, AccountController and ManageController, which has its own view models and CSHTML.

 
Leave a comment

Posted by on December 27, 2016 in General

 

Tags: , , ,

OAuth2 Flows

Cliff notes from Dominick Baier’s OAuth2 Flows.

Authorization Code Flow

oauth2-flows-1

Characters: web application (server-based) clients, confidential and secured client where nobody can see user credential, human involves, consent screen, authorization happens in authorization server.

Apply to: web applications

Steps:

  1. Request authorization.
  2. Request token.
  3. Access resource.

Implicit Flow

oauth2-flows-2

Characters: native / local clients, user-agent based clients, human involves, consent screen, authorization happens in authorization servers.

Apply to: third party native applications (JavaScript application is included).

Steps:

  1. Request authorization & token.
  2. Access resource.

Resource Owner Credential Flow

oauth2-flows-3

Characters: trusted clients, no human involvement, no consent screen, authorization happens in client.

Apply to: official native applications (JavaScript application included).

Steps:

  1. Request token with resource owner credentials.
  2. Access resource.

Client Credential Flow

oauth2-flows-4

Characters: client to Service communication, no human involvement, no consent screen, authorization happens in client.

Apply to: machine to machine communication, service communication to authorization server without act as.

Steps:

  1. Request token with client credentials.
  2. Access resource.

Assertion Flow

oauth2-flows-5

Characters: use one of the ‘core’ flows, access another trusted system (partner).

Apply to: translate between identity management system (ADFS’s saml to ThinkTecture’s jwt), communication with partner’s resources using client’s credential.

Steps:

  1. Request token using ‘core’ flow (Authorization Code, Implicit, Resource Owner Credential, Client Credential).
  2. Request token using ‘assertion’ flow.
  3. Use token.
 
Leave a comment

Posted by on September 24, 2014 in General

 

Tags: , , , , , ,

 
%d bloggers like this: