使用 MvcHandler 为每个请求添加带有访问令牌的授权标头 [英] Adding authorization header with access token for every request using MvcHandler

查看:18
本文介绍了使用 MvcHandler 为每个请求添加带有访问令牌的授权标头的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试为资源服务器实现 OAuth 2.0 资源访问.我获得了一个令牌并希望将该令牌传递给资源服务器,以便资源服务器可以为每个请求使用授权服务器进行验证,并在 http 标头中传递令牌(例如授权:Bearer mF_9.B5f-4.1JqM).

I'm trying to implement OAuth 2.0 resource access for the resource server. I have acquired a token and want to pass that token to the resource server so that resource server could validate with the authorization server for every request, passing the token in the http header (e.g. Authorization: Bearer mF_9.B5f-4.1JqM).

我正在使用 MVC 4,有人告诉我应该使用 MvcHandler 来实现这一点,但是我不确定从哪里开始.任何人都可以指出我应该做什么的一般方向吗?我已经有一堆动作和控制器,并希望将这一层放在这些之上,而不是回到每个动作并更改和/或装饰每个动作.

I'm using MVC 4, and I've been told MvcHandler should be used to achieve this However I'm not sure where to start. Can anyone point me to a general direction on what should be done? I already have bunch of actions and controllers and want to put this layer on top of those instead of going back to every action and changing and/or decorating each action.

推荐答案

使用身份验证过滤器

身份验证过滤器是 ASP.NET MVC 中的一种新型过滤器在 ASP.NET MVC 管道中的授权过滤器之前运行和允许您指定每个操作、每个控制器的身份验证逻辑,或全局适用于所有控制器.身份验证过滤器过程请求中的凭据并提供相应的主体.身份验证过滤器还可以在响应未经授权的请求.

Authentication filters are a new kind of filter in ASP.NET MVC that run prior to authorization filters in the ASP.NET MVC pipeline and allow you to specify authentication logic per-action, per-controller, or globally for all controllers. Authentication filters process credentials in the request and provide a corresponding principal. Authentication filters can also add authentication challenges in response to unauthorized requests.

您只需要根据您的需要实现 IAuthenticationFilter 注册它就可以了.

You just need to implement the IAuthenticationFilter for your needs register it and it's done.

public class YourAuthenticationAttribute : ActionFilterAttribute, IAuthenticationFilter
    {
        public void OnAuthentication(AuthenticationContext filterContext)
        {            
        }

        public void OnAuthenticationChallenge(AuthenticationChallengeContext filterContext)
        {   
            if (user.Identity.IsAuthenticated == false)
            {
                 filterContext.Result = new HttpUnauthorizedResult();
            }
        }
    }

如果您希望它是全局的,请将其添加为 FilterConfig.cs

If you want it to be global add it as a global filter in FilterConfig.cs

public static void RegisterGlobalFilters(GlobalFilterCollection filters)
{
    filters.Add(new YourAuthenticationAttribute());
}

更多信息:

ASP.NET MVC 5 身份验证过滤器

ASP.NET MVC 5 身份验证过滤器

ASP.NET MVC 5 中的身份验证过滤器

终于有了新的 ASP.NET MVC 5 身份验证过滤器!

这篇关于使用 MvcHandler 为每个请求添加带有访问令牌的授权标头的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆