How to disable Forms Authenitcation for the Web API?

Asked

Viewed 143 times

1

I have an Asp.Net MVC project and inside it has the Web Api, when a request sends an invalid token, Forms Authentication redirects to the login page, but I need it to only return an Http 401 error, as it is a Rest Api. I tried to use the tag in Web.config, but it didn’t work.

  <location path="api">
    <system.web>
      <authorization>
        <allow users="*" />
      </authorization>
    </system.web>
  </location>
  • already tried Unauthorized Return(); ?

  • @Fábio Lima, could add the problem resolution as an answer, so we will know better that found a solution. rsrs

2 answers

0

[RESOLUTION] To do what I was aiming for, I found an implementation where an implementation of an interface IHttpModule.

public class SuppressFormsAuthenticationRedirectModule : IHttpModule {

    public void Init(HttpApplication context) {
        context.EndRequest += OnEndRequest;
    }

    private void OnEndRequest(object source, EventArgs args) {
        var context = (HttpApplication)source;
        var response = context.Response;
        var request = context.Request;

        if (response.StatusCode == 302 && request.AppRelativeCurrentExecutionFilePath.StartsWith("~"+ConstantesApi.API_URL)) {

            response.TrySkipIisCustomErrors = true;
            response.ClearContent(); // limpra o conteúdo
            response.StatusCode = 401; // Coloca o código de erro http
            response.SuppressFormsAuthenticationRedirect = true; // pula o redirecionamento do forms authentication
            response.RedirectLocation = null; // tira o redirecionamento
            response.Output.Write("{\"message\": \"Erro ao autenticar\"}"); // escreve na saída do response
        }
    }

    public void Dispose() {
    }

}

Then I created a file to link the module to the system on execution

// Carrega o módulo no start da aplicação
[assembly: PreApplicationStartMethod(typeof(FormsAuthenticationConfig), "Register" /* Método chamado na classe*/)]
namespace Unitins.Egresso.MVC.App_Start {
    public static class FormsAuthenticationConfig {
        public static void Register() {
            DynamicModuleUtility.RegisterModule(typeof(SuppressFormsAuthenticationRedirectModule));
        }
    }
}

Source: http://haacked.com/archive/2011/10/04/prevent-forms-authentication-login-page-redirect-when-you-donrsquot-want.aspx/

0

Strange you have Formsauthentication configuration in a Web API project. Anyway, to disable Formsauthentication, use:

<configuration>
  ...
  <system.web>
    ...
    <authentication mode="None" />
    ...
  </system.web>
  ...
</configuration>

Browser other questions tagged

You are not signed in. Login or sign up in order to post.