Planning real world REST API

http://blog.developers.ba/post/2012/03/03/ASPNET-Web-API-Authorization-using-Tokens.aspx

When you try to plan how to build real world REST API like other major players like Facebook or Foursquare have you will soon realize that all major players use OAuth 2.0 .

ASP.NET Web API comes with support for authorize attribute and that’s nice, but for real world API I want to support token based approach.

OAuth 2.0 Server

For supporting token based approach  you must have some kind of server that will issue tokens. Building token server can be complex and most major players have implemented OAuth 2.0 server based on draft 10 OAuth documentation.

We hope that Microsoft will provide us with their own OAuth 2.0 server for free in final version of ASP.NET MVC 4.

Meanwhile I will just assume that you already have your own OAuth 2.0 server.

Building ActionFilterAttribute

I have solved my problem with authorization by implementing RequireAuthorize ActionFilterAttribute. This attribute also have scope property. Scope property is used for limiting access to your REST API.

You just need to decorate controllers or actions in controllers with this attribute and optionally set required scope for accessing these actions.

Here is RequireAuthorizeAtribute:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
public class RequireAuthorization : ActionFilterAttribute
    {
        public string Scope { get; set; }
 
        public override void OnActionExecuting(System.Web.Http.Controllers.HttpActionContext actionContext)
        {
            string[] scope = null;
            if (!string.IsNullOrEmpty(Scope))
            {
                scope = Scope.Split(new[] { "," }, StringSplitOptions.RemoveEmptyEntries);
            }
 
            string query = actionContext.Request.RequestUri.Query;
            string accessToken = HttpUtility.ParseQueryString(query).Get("accessToken");
 
            // we first check for valid token
            if (accessToken != null)
            {
                IAccessTokenValidator accessTokenValidator = new AccessTokenValidator();
                bool validToken = accessTokenValidator.ValidateToken(accessToken, scope);
 
                if (!validToken)
                {
                    var response = new HttpResponseMessage
                    {
                        Content =
                            new StringContent("This token is not valid, please refresh token or obtain valid token!"),
                        StatusCode = HttpStatusCode.Unauthorized
                    };
                    throw new HttpResponseException(response);
                }
            }
            else
            {
                var response = new HttpResponseMessage
                {
                    Content =
                        new StringContent("You must supply valid token to access method!"),
                    StatusCode = HttpStatusCode.Unauthorized
                };
                throw new HttpResponseException(response);
            }
 
            base.OnActionExecuting(actionContext);
        }
    }

And here is AccessTokenValidator class:

1
2
3
4
5
6
7
8
9
10
11
12
public class AccessTokenValidator : IAccessTokenValidator
    {
        public bool ValidateToken(string token, string[] scope)
        {
            // replace this logic with dataBase access to table with tokens
            if (token != "someToken")
            {
                return false;
            }
            return true;
        }
    }

ASP.NET Web API Authorization using Tokens的更多相关文章

  1. Implement JSON Web Tokens Authentication in ASP.NET Web API and Identity 2.1 Part 3 (by TAISEER)

    http://bitoftech.net/2015/02/16/implement-oauth-json-web-tokens-authentication-in-asp-net-web-api-an ...

  2. Authentication and Authorization in ASP.NET Web API

      You've created a web API, but now you want to control access to it. In this series of articles, we ...

  3. ASP.NET Web API Claims Authorization with ASP.NET Identity 2.1 Part 5 (by TAISEER)

    https://www.cnblogs.com/KimmyLee/p/6430474.html https://www.cnblogs.com/rocketRobin/p/9077523.html h ...

  4. 购物车Demo,前端使用AngularJS,后端使用ASP.NET Web API(3)--Idetity,OWIN前后端验证

    原文:购物车Demo,前端使用AngularJS,后端使用ASP.NET Web API(3)--Idetity,OWIN前后端验证 chsakell分享了前端使用AngularJS,后端使用ASP. ...

  5. [转] JSON Web Token in ASP.NET Web API 2 using Owin

    本文转自:http://bitoftech.net/2014/10/27/json-web-token-asp-net-web-api-2-jwt-owin-authorization-server/ ...

  6. JSON Web Token in ASP.NET Web API 2 using Owin

    In the previous post Decouple OWIN Authorization Server from Resource Server we saw how we can separ ...

  7. 对一个前端使用AngularJS后端使用ASP.NET Web API项目的理解(2)

    chsakell分享了一个前端使用AngularJS,后端使用ASP.NET Web API的项目. 源码: https://github.com/chsakell/spa-webapi-angula ...

  8. ASP.NET Web API 2 external logins with Facebook and Google in AngularJS app

    转载:http://bitoftech.net/2014/08/11/asp-net-web-api-2-external-logins-social-logins-facebook-google-a ...

  9. 在ASP.NET Web API 2中使用Owin OAuth 刷新令牌(示例代码)

    在上篇文章介绍了Web Api中使用令牌进行授权的后端实现方法,基于WebApi2和OWIN OAuth实现了获取access token,使用token访问需授权的资源信息.本文将介绍在Web Ap ...

随机推荐

  1. TLV----Demo讲解

    接触过网络协议的人对TLV一定或多或少的知道.作为一种自定义应用层标准. TLV使用十分广泛.他对数据封包有着很好的定义,简单实用. TLV即Type-Length-Value.即我们每个封装成TLV ...

  2. exit()与_exit()的区别

    从图中可以看出,_exit 函数的作用是:直接使进程停止运行,清除其使用的内存空间,并清除其在内核的各种数据结构:exit 函数则在这些基础上做了一些小动作,在执行退出之前还加了若干道工序.exit( ...

  3. CSDN博文大赛火爆开启

    俗话说的好,程序猿会写博,谁也挡不住! 是不是每一个开发人员都能写出好博文,这个非常难说,但能够肯定的是,能写出好博文的,一定是优秀的程序猿! 写作即思考,养成写博文的习惯,既能帮自己整理技术思路,也 ...

  4. Hadoop基础

    Hadoop组成 包括两个核心组成:HDFS:分布式文件系统,存储海量的数据MapReduce:并行处理框架,实现任务分解和调度 搭建大型数据仓库,PB级数据的存储.处理.分析.统计等业务(搜索引擎. ...

  5. T-SQL索引

    索引 使用索引可以提高查询速度,不是越多越好,会损耗存储空间.应用于出现在where子句中的列建立索引.可以使用sql server 内置工具Profiler捕捉在SQL Server实例上执行的活动 ...

  6. JavaScript 中 关于 this 的学习笔记

    今天上午主要学习了js中的 this ,因为之前学习面向对象时,this这个东西出现的还是很频繁的,理解的很不透彻,感觉老被JAVA的思想带进坑里,所以对它特别关注. 首先贴一个大神的一篇博客,我是通 ...

  7. VS2010中查询替换使用

    MSDN:http://msdn.microsoft.com/zh-cn/library/afy96z92.aspx 例子:

  8. Node.js学习系列1

    概述 最近在刷javascript的技能,觉着nodejs是个不错的入口,作为一个.Net平台的前端工程师学习使用js开发服务端,想想都有点小激动哈哈^_^^_^. 入门 之前开发过ionic,所以对 ...

  9. mysql5.6 zip版安装

    MySQL安装文件分为两种,一种是msi格式的,一种是zip格式的.如果是msi格式的可以直接点击安装,按照它给出的安装提示进行安装(相信大家的英文可以看懂英文提示),一般MySQL将会安装在C:\P ...

  10. OSX: 10.9的SMB网络共享连接可能破坏其权限设置

    参见以前的Blog,“OSX: 10.9 Mavericks的重要更新技术细节(1)”,自从10.9之后,它的内核默认地使用全新的SMB2协议,这本来是令人期待的变化,不过根据这多年来和OS X系统的 ...