Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.2k views
in Technique[技术] by (71.8m points)

asp.net mvc - Adding authorization header with access token for every request using MvcHandler

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

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Use Authentication filters

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.

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();
            }
        }
    }

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());
}

More info:

ASP.NET MVC 5 Authentication Filters

ASP.NET MVC 5 Authentication Filters

AUTHENTICATION FILTERS IN ASP.NET MVC 5

FINALLY THE NEW ASP.NET MVC 5 AUTHENTICATION FILTERS!


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...