How do I disable Forms Authenitcation for the Web API?

1

I have an Asp.Net MVC project and inside it has the Api web, when a request sends an invalid token, the forms authentication redirects to the login page, but I need it to only return an Http 401 error as it is an Api Rest. I already tried to use the tag in Web.config, but it did not work.

  <location path="api">
    <system.web>
      <authorization>
        <allow users="*" />
      </authorization>
    </system.web>
  </location>
    
asked by anonymous 03.02.2017 / 17:24

2 answers

0

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

<configuration>
  ...
  <system.web>
    ...
    <authentication mode="None" />
    ...
  </system.web>
  ...
</configuration>
    
03.02.2017 / 19:09
0

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

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 at runtime

// 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: link

    
07.02.2017 / 18:43