Adding additional logic to Bearer authorization

后端 未结 3 852
借酒劲吻你
借酒劲吻你 2021-01-30 15:11

I am attempting to implement OWIN bearer token authorization, and based on this article. However, there\'s one additional piece of information I need in bearer token that I don\

3条回答
  •  旧时难觅i
    2021-01-30 15:33

    Just to add on to LeftyX's answer, here's how you can completely control the response being sent to the client once the context is rejected. Pay attention to the code comments.

    Based on Greg P's original answer, with some modifications

    Step1: Create a class which will act as your middleware

    using AppFunc = System.Func,
    System.Threading.Tasks.Task>;
    

    namespace SignOnAPI.Middleware.ResponseMiddleware {

    public class ResponseMiddleware 
    {
        AppFunc _next;
        ResponseMiddlewareOptions _options;
    
        public ResponseMiddleware(AppFunc nex, ResponseMiddlewareOptions options)
        {
            _next = next;
        }
    
        public async Task Invoke(IDictionary environment)
        {
            var context = new OwinContext(environment);
    
            await _next(environment);
    
            if (context.Response.StatusCode == 400 && context.Response.Headers.ContainsKey("Change_Status_Code"))
            {
                //read the status code sent in the response
                var headerValues = context.Response.Headers.GetValues("Change_Status_Code");
    
                //replace the original status code with the new one
                context.Response.StatusCode = Convert.ToInt16(headerValues.FirstOrDefault());
    
                //remove the unnecessary header flag
                context.Response.Headers.Remove("Change_Status_Code");
            }
        }
    }
    

    Step2 : Create the extensions class (Can be omitted).

    This step is optional, can be modified to accept options that can be passed to the middleware.

    public static class ResponseMiddlewareExtensions
    {
        //method name that will be used in the startup class, add additional parameter to accept middleware options if necessary
        public static void UseResponseMiddleware(this IAppBuilder app)
        {
            app.Use();
        }
    }
    

    Step3: Modify GrantResourceOwnerCredentials method in your OAuthAuthorizationServerProvider implementation

    public override async Task GrantResourceOwnerCredentials(OAuthGrantResourceOwnerCredentialsContext context)
        {
    
            context.OwinContext.Response.Headers.Add("Access-Control-Allow-Origin", new[] { "*" });
    
            if ()
            {
                //first reject the context, to signify that the client is not valid
                context.Rejected();
    
                //set the error message
                context.SetError("invalid_username_or_password", "Invalid userName or password" );
    
                //add a new key in the header along with the statusCode you'd like to return
                context.Response.Headers.Add("Change_Status_Code", new[] { ((int)HttpStatusCode.Unauthorized).ToString() }); 
                return;
            }
        }
    

    Step4: Use this middleware in the startup class

    public void Configuration(IAppBuilder app)
    {
        app.UseResponseMiddleware();
    
        //configure the authentication server provider
        ConfigureOAuth(app);
    
        //rest of your code goes here....
    }
    

提交回复
热议问题