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. Mysql ORM工具--MicrobeORM.Mysql开源咯

    MicrobeORM.Mysql 补充:为啥批批量比官方的ADO.NET还快,原因是这俩货 System.EnterpriseServices.dllSystem.EnterpriseServices ...

  2. 13个JavaScript图表(JS图表)图形绘制插件

    转自:http://blog.jobbole.com/13671/ 1. Flash 过去是最佳解决方案,但很多人多在从那迁移: 2. 现代浏览器及其更强大的计算能力,使其在转化绘制实时数据方面的能力 ...

  3. .net MVC内置js验证 jquery.validate.unobtrusive.js重置验证操作(备忘,找了很多次了)

    (function ($) { $.validator.unobtrusive.parseDynamicContent = function (selector) { //use the normal ...

  4. CentoS6.x网络配置

    一.配置文件 在CentoS系统里面,跟网络有关的主要配置文件有    1./etc/host.conf # 配置域名服务客户端的控制文件 2./etc/hosts # 配置主机名映射为IP的功能 3 ...

  5. Caused by: java.lang.ClassNotFoundException: com.mchange.v2.c3p0.ComboPooledDataSource

    1.错误描写叙述 usage: java org.apache.catalina.startup.Catalina [ -config {pathname} ] [ -nonaming ] { -he ...

  6. Swift自定义Class实现Hashable

    假如有个Bit类,其中含有CGPoint类型的point属性,Class定义如下 class Bit { var point : CGPoint init(point : CGPoint) { sel ...

  7. 解决jQuery.live在mobile safari(iphone / ipad / ipod)绑定失败的问题

    解决方案: 给要使用live绑定事件的元素,添加“cursor:pointer”样式即可! 如: a,input,td{cursor:pointer;}

  8. VMware下桥接设置

    操作环境 主机:Win7 X86 SP1 虚拟机:VMware station 8 虚拟机里的系统:Fedora 15 环境上,不管什么系统,什么版本的虚拟机,使用上都是大同小异的,毕竟核心是不变的. ...

  9. erp crm oa

    erp是企业管理计划 crm是客户关系管理 oa是办公自动化erp管理的是企业的进销存.产供销.财务等crm主要是管理企业的客户,可以和erp的销售系统挂钩oa主要是管理一些内部的文档.公告,行政信息 ...

  10. [string]字符串中几个比较难的算法和容易搞混的题目

    一.两个难点算法 1.Manacher算法,线性时间求最长回文子串 2.KMP算法,字符串匹配问题,c语言中的strStr 二.几个题目 1.最长回文子串 方法:暴力,动态规划,中心扩展,manach ...