Search code examples
formsasp.net-mvc-4asp.net-identityauthorize

MVC 4 || identity || How To Disable Form Submitting For an Unauthorized User?


I have an web app' based on MVC4 and i have a form that send (via post to an action) multiply files to the server, now i enable the authorize approach to only deal with Authorize users.

My problem is that i put the [Authorize] before the Post Action in the controller so the files is upload to the server first and than the unauthorized user get the message to log in (redirect the user to the register/login page).

I want to prevent the upload of the files if the user is unauthorized, so i need to somehow check if the user is an authorize user first and then to submit the form.

Any idea how can i do it ?


Solution

  • Remember that in the MVC architecture, by default, each action can be called/replayed statelessly - that is, a request that is well-formed will hit the appropriate action so that AuthorizeAttribute and other such attributes will be evaluated only after the appropriate action is identified. Really this is not a feature of MVC so much as it is a feature of web architecture in general.

    File uploading is like any other POSTed value in that it is sent over as part of the request. Now, you may have an asynchronous (ajax) file upload control, but even in this case the file upload is still just another, plain-old request.

    MVC does not get to choose whether your client decides to send it a big request or a small request or any request at all. MVC can only respond to the request your client chooses to make.

    No doubt, you should have an [Authorize] before your POST action. But to prevent users from spending time uploading a file, only to be rejected upon the POST, you should also do something in the UI to discourage or prevent users from easily making such a request when they are not authenticated.

    In other words, you need to program the client to work in tandem with the server to determine whether or not to encourage the user to upload.

    One easy thing you could do is a check on the User.Identity.IsAuthenticated and display the form when true:

    @if (User.Identity.IsAuthenticated)
    {
        // display form razor
    }
    else
    {
        // display login razor
    }
    

    You could also intercept the submission with JavaScript, which is a deeper implementation but essentially would go something like this:

    1. On submit, check if the user is authenticated (may involve server-side call on-the-fly OR you can rely on the client to determine this if appropriate)
    2. If not authenticated, prevent submission and instead show login modal

    Hope this helps.