I have an API application that works perfectly on Visual Studio 2015 debugger; I am trying to publish my application on IIS (I have installed the server by Control panel Turn on/off Windows features).
My application has a security system to check that any request is from a user registered, any request pass first throw ApiAuthorizationFilter
, resolve the token that is composed by Base64 string, it comes in the header as Authorization and returns the specific HttpStatusCode
with JSON.
The Exception Occurs after deploy, if I run a test on the application that is at IIS throws NullReferenceException
at Filter.ApiAuthorizationFilter
, but if I run the same application on Visual Studio - it works.
This is the error message:
500: Internal Server Error "Message": "An error has occurred." "ExceptionMessage": "Object reference not set to an instance of an object." "ExceptionType": "System.NullReferenceException" "StackTrace": " at API.CARDS.Models.Filter.ApiAuthorizationFilter.OnAuthorization(HttpActionContext actionContext) at System.Web.Http.Filters.AuthorizationFilterAttribute.OnAuthorizationAsync(HttpActionContext actionContext, CancellationToken cancellationToken) --- End of stack trace from previous location where exception was thrown --- at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task) at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task) at System.Web.Http.Filters.AuthorizationFilterAttribute.d__2.MoveNext() --- End of stack trace from previous location where exception was thrown --- at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task) at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task) at System.Web.Http.Dispatcher.HttpControllerDispatcher.d__1.MoveNext()"
Here is the code:
ApiAuthorizationFilter
public class ApiAuthorizationFilter : AuthorizationFilterAttribute
{
[Inject]
public IEncryptionSystemService service { get; set; }
[Inject]
public IUserService userService { get; set; }
public override void OnAuthorization(HttpActionContext actionContext)
{
//Hace una petición (request) al actionContext
HttpRequestMessage request = actionContext.Request;
try
{
//Establece la cultura (Ejemplo: es-MX) para los mensajes i18n
string culture = actionContext.Request.Headers.AcceptLanguage.ToString();
if (culture.Length == 5)
{
Thread.CurrentThread.CurrentCulture = new CultureInfo(culture);
Thread.CurrentThread.CurrentUICulture = new CultureInfo(culture);
}
//Crea un token con los valores que se obtienen del actionContext, mismos que serán las credenciales para accesar.
string token = actionContext.Request.Headers.GetValues("Authorization").FirstOrDefault().Replace("Credentials", "").Trim();
//Desencripta las credenciales con el servicio del tipo IEncryptionService.
string[] userPass = service.DecryptText(token);
User model = new User { email = userPass[0], password = userPass[1] };
////Verifica que sean correctas las credenciales que ser obtuvieron del token.
AuthorizationResult result = userService.LoginUser(model);
switch (result)
{
case AuthorizationResult.ACCESS_GRANTED:
User user = new User { email = model.email };
ApiIdentity identity = new ApiIdentity(user);
ApiPrincipal principal = new ApiPrincipal(identity);
Thread.CurrentPrincipal = principal;
break;
case AuthorizationResult.ACCESS_DENIED:
actionContext.Response = request.CreateResponse(HttpStatusCode.NotFound, "ErrorResources.NotFound");
break;
case AuthorizationResult.PERMISSION_DENIED:
actionContext.Response = request.CreateResponse(HttpStatusCode.Unauthorized, "ErrorResources.Unauthorized");
break;
}
}
catch (Exception e)
{
throw;
//Si existe un error durante la petición, regresa un estatus de InternalServerError (Error interno del Servidor).
//actionContext.Response = request.CreateErrorResponse(HttpStatusCode.InternalServerError, string.Format("ErrorResources.AuthenticationError ---- {0}",e.Message));
}
}
}