web api 认证和授权

asp.net 生命周期事件和 http module和http handler

在IIS中,每个请求会经历ASP.net 的生命周期事件,每个http module可以注册关心的生命周期事件,框架会在对应事件的时候调用module的注册事件处理程序。比如router module会注册before handler事件,用来查找request对应的request handler,formauthencication module会注册authentication事件来进行认证。

Http handler负责输出request对应的response,如controller的action会转成http handler,如果要返回rss等需要自己写对应的httphandler

详情见 https://msdn.microsoft.com/en-us/library/bb398986.aspx  https://msdn.microsoft.com/en-us/library/ms178473.aspx   https://msdn.microsoft.com/en-us/library/bb470252.aspx

web api message handler

message handler是仅针对web api的在controller之前的一系列操作,每个messsage handler处理双向的管道过程(request到controller和controller到response)可以注册message handler来处理认证和权限的事情

message hadler的结构如图

典型的custom message handler的代码如下:

public class MessageHandler1 : DelegatingHandler
{
    protected async override Task<HttpResponseMessage> SendAsync(
        HttpRequestMessage request, CancellationToken cancellationToken)
    {
        Debug.WriteLine("Process request");
        // Call the inner handler.
        var response = await base.SendAsync(request, cancellationToken);
        Debug.WriteLine("Process response");
        return response;
    }
}

详情见:https://docs.microsoft.com/en-us/aspnet/web-api/overview/advanced/http-message-handlers

Http Module和Message handler关系

如果是不用支持self host 建议使用module来做authentication,因为其支持所有request,且hook时刻较早

authorize filter 

对于授权,一般用authorize filter,filter是执行在action之前的操作,可以配置全局,controller,和action层次上

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

IPrinciple和identity

用oauth进行认证

oauth基本原理图

当使用visual studio创建一个个人账户类型的web api template project时,认证过程如下

oauth2的detail被封装在OWIN 组件里

authorization server的调用OWIN 的过程如下

resource server调用OWIN过程如下

详情见 https://docs.microsoft.com/en-us/aspnet/web-api/overview/security/individual-accounts-in-web-api

参考链接

https://msdn.microsoft.com/en-us/library/ms178473.aspx

https://msdn.microsoft.com/en-us/library/bb470252.aspx

https://msdn.microsoft.com/en-us/library/ms227673.aspx

https://msdn.microsoft.com/en-us/library/bb398986.aspx

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

https://docs.microsoft.com/en-us/aspnet/web-api/overview/advanced/http-message-handlers

https://docs.microsoft.com/en-us/aspnet/web-api/overview/security/individual-accounts-in-web-api

猜你喜欢

转载自blog.csdn.net/xuefeiliuyuxiu/article/details/81431539
今日推荐