You've created a web API, but now you want to control access to it. In this series of articles, we'll look at some options for securing a web API from unauthorized users. This series will cover both authentication and authorization.

  • Authentication is knowing the identity of the user. For example, Alice logs in with her username and password, and the server uses the password to authenticate Alice.
  • Authorization is deciding whether a user is allowed to perform an action. For example, Alice has permission to get a resource but not create a resource.

    1

The first article in the series gives a general overview of authentication and authorization in ASP.NET Web API. Other topics describe common authentication scenarios for Web API.

Note

Thanks to the people who reviewed this series and provided valuable feedback: Rick Anderson, Levi Broderick, Barry Dorrans, Tom Dykstra, Hongmei Ge, David Matson, Daniel Roth, Tim Teebken.

Authentication

Web API assumes that authentication happens in the host. For web-hosting, the host is IIS, which uses HTTP modules for authentication. You can configure your project to use any of the authentication modules built in to IIS or ASP.NET, or write your own HTTP module to perform custom authentication.1

When the host authenticates the user, it creates a principal, which is an IPrincipal object that represents the security context under which code is running. The host attaches the principal to the current thread by setting Thread.CurrentPrincipal. The principal contains an associated Identityobject that contains information about the user. If the user is authenticated, the Identity.IsAuthenticated property returns true. For anonymous requests, IsAuthenticated returns false. For more information about principals, see Role-Based Security.

HTTP Message Handlers for Authentication

Instead of using the host for authentication, you can put authentication logic into an HTTP message handler. In that case, the message handler examines the HTTP request and sets the principal.

When should you use message handlers for authentication? Here are some tradeoffs:

  • An HTTP module sees all requests that go through the ASP.NET pipeline. A message handler only sees requests that are routed to Web API.
  • You can set per-route message handlers, which lets you apply an authentication scheme to a specific route.
  • HTTP modules are specific to IIS. Message handlers are host-agnostic, so they can be used with both web-hosting and self-hosting.
  • HTTP modules participate in IIS logging, auditing, and so on.
  • HTTP modules run earlier in the pipeline. If you handle authentication in a message handler, the principal does not get set until the handler runs. Moreover, the principal reverts back to the previous principal when the response leaves the message handler.

Generally, if you don't need to support self-hosting, an HTTP module is a better option. If you need to support self-hosting, consider a message handler.

Setting the Principal

If your application performs any custom authentication logic, you must set the principal on two places:

  • Thread.CurrentPrincipal. This property is the standard way to set the thread's principal in .NET.
  • HttpContext.Current.User. This property is specific to ASP.NET.

The following code shows how to set the principal:

C#Copy

private
void
SetPrincipal(IPrincipal principal)

{

    Thread.CurrentPrincipal = principal;


if (HttpContext.Current != null)

    {

        HttpContext.Current.User = principal;

    }

}

For web-hosting, you must set the principal in both places; otherwise the security context may become inconsistent. For self-hosting, however, HttpContext.Current is null. To ensure your code is host-agnostic, therefore, check for null before assigning to HttpContext.Current, as shown.

Authorization

Authorization happens later in the pipeline, closer to the controller. That lets you make more granular choices when you grant access to resources.

  • Authorization filters run before the controller action. If the request is not authorized, the filter returns an error response, and the action is not invoked.
  • Within a controller action, you can get the current principal from the ApiController.User property. For example, you might filter a list of resources based on the user name, returning only those resources that belong to that user.

Using the [Authorize] Attribute

Web API provides a built-in authorization filter, AuthorizeAttribute. This filter checks whether the user is authenticated. If not, it returns HTTP status code 401 (Unauthorized), without invoking the action.

You can apply the filter globally, at the controller level, or at the level of inidivual actions.1

Globally: To restrict access for every Web API controller, add the AuthorizeAttribute filter to the global filter list:

C#Copy

public
static
void
Register(HttpConfiguration config)

{

    config.Filters.Add(new AuthorizeAttribute());

}

Controller: To restrict access for a specific controller, add the filter as an attribute to the controller:

C#Copy

// Require authorization for all actions on the controller.

[Authorize]

public
class
ValuesController : ApiController

{


public HttpResponseMessage Get(int id) { ... }


public HttpResponseMessage Post() { ... }

}

Action: To restrict access for specific actions, add the attribute to the action method:

C#Copy

public
class
ValuesController : ApiController

{


public HttpResponseMessage Get() { ... }

 


// Require authorization for a specific action.

    [Authorize]


public HttpResponseMessage Post() { ... }

}

Alternatively, you can restrict the controller and then allow anonymous access to specific actions, by using the [AllowAnonymous] attribute. In the following example, the Post method is restricted, but the Get method allows anonymous access.

C#Copy

[Authorize]

public
class
ValuesController : ApiController

{

    [AllowAnonymous]


public HttpResponseMessage Get() { ... }

 


public HttpResponseMessage Post() { ... }

}

In the previous examples, the filter allows any authenticated user to access the restricted methods; only anonymous users are kept out. You can also limit access to specific users or to users in specific roles:

C#Copy

// Restrict by user:

[Authorize(Users="Alice,Bob")]

public
class
ValuesController : ApiController

{

}

 

// Restrict by role:

[Authorize(Roles="Administrators")]

public
class
ValuesController : ApiController

{

}

Note

The AuthorizeAttribute filter for Web API controllers is located in the System.Web.Http namespace. There is a similar filter for MVC controllers in the System.Web.Mvc namespace, which is not compatible with Web API controllers.

Custom Authorization Filters

To write a custom authorization filter, derive from one of these types:

  • AuthorizeAttribute. Extend this class to perform authorization logic based on the current user and the user's roles.
  • AuthorizationFilterAttribute. Extend this class to perform synchronous authorization logic that is not necessarily based on the current user or role.
  • IAuthorizationFilter. Implement this interface to perform asynchronous authorization logic; for example, if your authorization logic makes asynchronous I/O or network calls. (If your authorization logic is CPU-bound, it is simpler to derive from AuthorizationFilterAttribute, because then you don't need to write an asynchronous method.)

The following diagram shows the class hierarchy for the AuthorizeAttribute class.

Authorization Inside a Controller Action

In some cases, you might allow a request to proceed, but change the behavior based on the principal. For example, the information that you return might change depending on the user's role. Within a controller method, you can get the current principle from the ApiController.User property.2

C#Copy

public HttpResponseMessage Get()

{


if (User.IsInRole("Administrators"))

    {


// ...

    }

}

 

From: https://docs.microsoft.com/en-us/aspnet/web-api/overview/security/authentication-and-authorization-in-aspnet-web-api

Note: about sessionStorage, can refer here: http://www.cnblogs.com/time-is-life/p/7693568.html

Authentication and Authorization in ASP.NET Web API的更多相关文章

  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. 杂项:ASP.NET Web API

    ylbtech-杂项:ASP.NET Web API ASP.NET Web API 是一种框架,用于轻松构建可以访问多种客户端(包括浏览器和移动设备)的 HTTP 服务. ASP.NET Web A ...

  3. [转]ASP.NET Web API(三):安全验证之使用摘要认证(digest authentication)

    本文转自:http://www.cnblogs.com/parry/p/ASPNET_MVC_Web_API_digest_authentication.html 在前一篇文章中,主要讨论了使用HTT ...

  4. ASP.NET Web API(三):安全验证之使用摘要认证(digest authentication)

    在前一篇文章中,主要讨论了使用HTTP基本认证的方法,因为HTTP基本认证的方式决定了它在安全性方面存在很大的问题,所以接下来看看另一种验证的方式:digest authentication,即摘要认 ...

  5. ASP.NET Web API Authorization using Tokens

    Planning real world REST API http://blog.developers.ba/post/2012/03/03/ASPNET-Web-API-Authorization- ...

  6. 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 ...

  7. Asp.net Web Api 2 FORM Authentication Demo

    最近看了一点 web api 2方面的书,对认证都是简单介绍了下,所以我在这里做个简单Demo,本文主要是FORM Authentication,顺带把基本认证也讲了. Demo 一.FORM Aut ...

  8. (转)【ASP.NET Web API】Authentication with OWIN

    概述 本文说明了如何使用 OWIN 来实现 ASP.NET Web API 的验证功能,以及在客户端与服务器的交互过程中,避免重复提交用户名和密码的机制. 客户端可以分为两类: JavaScript: ...

  9. asp.net Web API 身份验证 不记名令牌验证 Bearer Token Authentication 简单实现

    1. Startup.Auth.cs文件 添加属性 1 public static OAuthBearerAuthenticationOptions OAuthBearerOptions { get; ...

随机推荐

  1. MHDD硬盘坏道检测修复教程(转)

    MHDD算是在DOS下比较专业的检测工具,比一些GUI的好用很多,并且现在有人专门做成硬件机器卖到了电脑城,电脑城一般倒卖硬盘的都使用这种机器. 进入MHDD 上面图片中就可以看到硬盘是ST34081 ...

  2. InnoDB 与 MYISAM

    http://www.cnblogs.com/sopc-mc/archive/2011/11/01/2232212.html

  3. C++ 实践总结

     对于一个应用程序而言,静态链接库可能被载入多次,而动态链接库仅仅会被载入一次. Gameloft面试之错误一 Event: 面试官说例如以下程序是能够链接通过的. class Base { Pu ...

  4. js中 object.constructor

  5. java用正则方法验证文件名是否合法

    Java中用到文件操作时,经常要验证文件名是否合法. 用File类的createNewFile()方法的确很管用.但当要批量验证时,效率上就会有问题.正则匹配的开销比创建文件少了很多. 那么一个合法的 ...

  6. Git每次进入都需要输入用户名和密码的问题解决

    解决方法: 在项目目录下输入以下命令: git config --global credential.helper store 使用git pull 的时候回提示再输下用户名和密码就行了.

  7. SqlServer 查看备份文件中逻辑文件信息的Sql语句

    RESTORE FILELISTONLY FROM DISK = 'D:\All\DataBase\(2013-12-18)-1.bak' 用来查看备份文件中的逻辑文件信息. 相关信息:SqlServ ...

  8. 自己写的SeekBarPreference,可以实现seekbar滑动监听和设置默认进度和最大进度

    我通过参考android源码,把这个烂尾的类写完了.具体实现了seekbar的数据自动存储,seekbar拖动时触发监听器,可以设置默认的进度和最大进度.先说使用的方式: 1.在xml文件中使用pre ...

  9. DICOM医学图像处理:WEB PACS初谈

    背景: 周末看到了一篇原公司同事的文章,讲的是关于新的互联网形势下的PACS系统.正好上一篇专栏文章也提到了有想搭建一个worklist服务器的冲动,所以就翻箱倒柜将原本学生时代做课题时搭建的简易We ...

  10. ProDinner

    ylbtech-dbs:ProDinner A, 数据库关系图 返回顶部 4, 点餐关系图 3, 留言图 1, 用户角色关系图 0, B,SQL脚本返回顶部 2, use master go --ki ...