Benedict Chan

software journey

ASP.NET MVC how to handle unauthorized response in JSON for your API

Assuming you want to prepare some JSON API in your ASP.NET MVC with authorization.

To share the same authorization logics for our Controller Action, what we should probably do is to implement our own FilterAttributes.

It can be as simple as:

ApiAuthorizeAttribute.cs
public class ApiAuthorizeAttribute : ActionFilterAttribute, IAuthorizationFilter
{
//Property Inject here!
public IAuthTokenService AuthTokenService { get; set; }
public ApiAuthorizeAttribute()
{
}
#region IAuthorizationFilter member
public void OnActionExecuting(ActionExecutingContext filterContext)
{
bool authTokenValid = IsRequestTokenValid(filterContext);
if (!authTokenValid)
{
filterContext.Result = new JsonResult
{
Data = new { Success = false, Data = "Unauthorized" },
ContentEncoding = System.Text.Encoding.UTF8,
ContentType = "application/json",
JsonRequestBehavior = JsonRequestBehavior.AllowGet
};
}
}
}

Note we are using property injection here for the IAuthTokenService here, check out Inject Properties Into FilterAttributes for more information.

HTTP status codes

In order to add our HTTP status codes, we can simple add the following line:

Read on →

Simple Authentication API for mobile application using ASP.NET MVC

This is actually part of server-side implementaion for the previous post: How to authenticate from a mobile application to an existing web pplication We are going to create an ASP.NET MVC action as a JSON API to authenticate a mobile client.

The Token Interface

First, let’s create a token service interface for our API Controller. We will be using dependency injection pattern.

IAuthTokenService.cs
public interface IAuthTokenService
{
/// <summary>
/// Issue a token for a user
/// </summary>
/// <param name="username"></param>
/// <returns>tokenId</returns>
string IssuseToken(string username);
/// <summary>
/// Check if a token is valid
/// </summary>
/// <param name="username"></param>
/// <param name="tokenId"></param>
/// <returns></returns>
bool IsTokenValid(string username, string tokenId);
/// <summary>
/// Expire users' tokens (designed to be called when user changed their password)
/// </summary>
/// <param name="username"></param>
/// <param name="tokensCreatedBefore">expire all tokens created before this time</param>
void ExpireUserTokens(string username, DateTime? tokensCreatedBefore);
}
Read on →

How to authenticate from a mobile application to an existing web application

The problem

The experience for a user authenticating to a web site vs a mobile application is totally different.

The web experience

  1. User comes to a web site
  2. User got redirected to the Login Page if needed
  3. User login by using their UserId,Password (cookie is created)
  4. User logout or leave the browser (cookie may expire)
  5. User come to the web applicaton next time, may need to login again (if cookie expired)

The mobile app experience

  1. User open the app for the first time, asked login with their UserId,Password
  2. After that, in most cases, user access to the app assuming they are always logged in and never need to logout or login again.

The solution

Read on →

Adding simple SEO for octopress

Adding Meta Tag, Keywords and Descriptions for your Octopress Blog

I just started using Octopress, seems it is quite simple to setup. However, the default template doesn’t provide the fields for your site, your post, or your pages. After a google search, seems it is quite easy to setup.

The main Octopress Site

Description

Meta tag Description is aleady in config file _config.yml. However, to show it in the main site. You have to modify the file source/_includes/head.html.

source/_includes/head.html
-{% capture description %}{% if page.description %}{{ page.description }}{% else %}{{ content | raw_content }}{% endif %}{% endcapture %}
+{% capture description %}{% if page.description %}{{ page.description }}{% elsif site.description %}{{ site.description }}{% else %}{{ content | raw_content }}{% endif %}{% endcapture %}
<meta name="description" content="{{ description | strip_html | condense_spaces | truncate:150 }}">
Read on →