How to customize the HTTP return message/code of an expired/invalid token in Web Api 2 + Owin?

Asked

Viewed 188 times

0

When my token expires and becomes invalid, I get a 404 (Not found) error return, but the truth is it should be a 401 (Unauthorized). The problem is I don’t know how to customize it. I’m using Asp.Net Web Api 2 with Owin.

public class Startup {
    public void Configuration(IAppBuilder app) {

        HttpConfiguration config = new HttpConfiguration() {

            IncludeErrorDetailPolicy = IncludeErrorDetailPolicy.Always 
        };

        // Configurando injeção de dependência
        var container = new UnityContainer();
        ResolvedorDependencias.registrar(container);
        config.DependencyResolver = new UnityResolver(container);

        // habilitando o CORS
        app.UseCors(Microsoft.Owin.Cors.CorsOptions.AllowAll);

        IUsuarioServico servico = container.Resolve<IUsuarioServico>();

        OAuthAuthorizationServerOptions OAuthServerOptions = new OAuthAuthorizationServerOptions() {
            AllowInsecureHttp = true, // TODO trocar para false quando for para produção
            TokenEndpointPath = new PathString("/api/token"),
            AccessTokenExpireTimeSpan = TimeSpan.FromDays(2),
            Provider = new ProvedorDeAutorizacao(servico),
            RefreshTokenProvider = new RefreshTokenProvider(), // provê um refresh_token para recuperar um novo token quando este expirar
        };

        // Geração do token com login local
        app.UseOAuthAuthorizationServer(OAuthServerOptions);
        app.UseOAuthBearerAuthentication(new OAuthBearerAuthenticationOptions());

        WebApiConfig.Register(config);
        app.UseWebApi(config);

        ConfigureWebApi(config);
    }

    public static void ConfigureWebApi(HttpConfiguration config) {

        var formatters = config.Formatters;

        // Remove o XML
        formatters.Remove(formatters.XmlFormatter);

        var jsonSettings = formatters.JsonFormatter.SerializerSettings;

        // Modifica a identação para fins didáticos
        // TODO remover quando for para produção
        jsonSettings.Formatting = Formatting.Indented;

        // configura as propriedades para minusculo
        jsonSettings.ContractResolver = new CamelCasePropertyNamesContractResolver();

        // tirando a referência circular
        jsonSettings.ReferenceLoopHandling = ReferenceLoopHandling.Ignore; 

        // Modifica a serialização
        formatters.JsonFormatter.SerializerSettings.PreserveReferencesHandling = PreserveReferencesHandling.None;
    }
}

public class RefreshTokenProvider : AuthenticationTokenProvider {
    public override void Create(AuthenticationTokenCreateContext context) {
        // Expira em 15 dias (tempo em segundos)
        // 15 dias * 24 horas * 60 minutos * 60 segundos
        int expire = 15 * 24 * 60 * 60;
        context.Ticket.Properties.ExpiresUtc = new DateTimeOffset(DateTime.Now.AddSeconds(expire));
        context.SetToken(context.SerializeTicket());
    }

    public override void Receive(AuthenticationTokenReceiveContext context) {
        context.DeserializeTicket(context.Token);
    }
}

(I’ve researched the stack overflow in English and found nothing, I don’t know if I’m searching wrong)

  • I believe the redirect location to Login is missing. It doesn’t cost to try.

  • You’re right. But in my case, the Web Api is to be consumed by a native Android app. So I’d like to return a 401 error. I haven’t found a solution yet. I am trying to customize an Authorizeattribute to try to launch the error there, since I am using this Dataannotation on top of Apicontroller to restrict the access by mandatory token.

No answers

Browser other questions tagged

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