When my token expires and becomes invalid, I get a 404 (Not found) error return, but the truth is that it should be a 401 (Unauthorized). The problem is that I do not know how to customize this. 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 already researched the stack overflow in English and found nothing, I do not know if I'm searching wrong)