none
Web APi in c# : How to catch the JWT exception in custom made controller RRS feed

  • Question

  • Below is the code to validate the JWT Token... If i pass the correct token then it's working fine but when manipulate the token i am getting the error in below catch that unauthorized token but the same not getting catch in custom controller. 

    ----------------------------------------------------------

                    

    protected override Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
            {
                HttpStatusCode statusCode;
                string token;
                //determine whether a jwt exists or not
                if (!TryRetrieveToken(request, out token))
                {
                    statusCode = HttpStatusCode.Unauthorized;
                    //allow requests with no token - whether a action method needs an authentication can be set with the claimsauthorization attribute
                    return base.SendAsync(request, cancellationToken);
                }

                try
                {
                    const string sec = "401b09eab3c013d4ca54922bb802bec8fd5318192b0a75f201d8b3727429090fb337591abd3e44453b954555b7a0812e1081c39b740293f765eae731f5a65ed1";
                    var now = DateTime.UtcNow;
                    var securityKey = new Microsoft.IdentityModel.Tokens.SymmetricSecurityKey(System.Text.Encoding.Default.GetBytes(sec));


                    SecurityToken securityToken;
                    JwtSecurityTokenHandler handler = new JwtSecurityTokenHandler();
                    TokenValidationParameters validationParameters = new TokenValidationParameters()
                    {
                        ValidAudience = "http://localhost:51969",
                        ValidIssuer = "http://localhost:51969",
                        ValidateLifetime = true,
                        ValidateIssuerSigningKey = true,
                        LifetimeValidator = this.LifetimeValidator,
                        IssuerSigningKey = securityKey
                    };
                    //extract and assign the user of the jwt
                    Thread.CurrentPrincipal = handler.ValidateToken(token, validationParameters, out securityToken);
                    HttpContext.Current.User = handler.ValidateToken(token, validationParameters, out securityToken);

                    return base.SendAsync(request, cancellationToken);
                }
                catch (SecurityTokenValidationException e)
                {
                    statusCode = HttpStatusCode.Unauthorized;
                    //var msg = new HttpResponseMessage(HttpStatusCode.Unauthorized) { ReasonPhrase = "Access Token is manipulated" };
                    //throw new HttpResponseException(msg);

                }
                catch (Exception ex)
                {
                    statusCode = HttpStatusCode.InternalServerError;
                }
                return Task<HttpResponseMessage>.Factory.StartNew(() => new HttpResponseMessage(statusCode) { });
            }

    ----------------------------------------------------------Controller code ---------------------------

                                                                                                     

        #regionXYX Data
           [AcceptVerbs("POST")]
           [Authorize]
           [EnableCors("*", "*", "*")]
           [HttpHeaderAttribute("Access-Control-Allow-Origin", "Origin,Content-Type,Accept,Authorization,X-Ellucian-Media-Type")]
           [HttpPost]

            public JObject GetXYZ([FromBody] JObject data)
            {
                string MainJson = "";
                DataTable blank_dt = new DataTable();
                Boolean bFlag = true;
                string v_message = "";
                string v_data = "";


                using (DAL db = new DAL())
                {
                    try
                    {
                         DataSet ds = new DataSet();
                        SqlCommand cmd = new SqlCommand();
                        cmd.CommandType = CommandType.StoredProcedure;
                        cmd.CommandText = "XYZ";
                        string s = JsonConvert.SerializeObject(data);
                        cmd.Parameters.Add(new SqlParameter("@pJson", s));

                        ds = db.ReturnDataset(cmd);
                        if (ds != null)
                        {
                            if (ds.Tables[0].Rows.Count > 0)
                            {
                                v_data = db.ConvertTableToJson(ds.Tables[0]);
                                bFlag = true;
                            }

                        }
                    }

                        catch (HttpResponseException)
                    {
                        bFlag = false;


                    }
                        catch (HttpListenerException)
                    {
                        bFlag = false;

                    }


                    catch (Exception ex)
                    {
                        Nlogger.nLoggerMsg(ex);
                        bFlag = false;
                        v_message = ex.Message.ToString();
                    }
                }
                MainJson = "{\"data\":" + v_data + ",\"flag\":\"" + bFlag + "\",\"msg\":\"" + v_message + "\"}";

                JObject json = JObject.Parse(MainJson);
                return json;
            }

    Monday, November 25, 2019 7:04 AM

All replies

  • Maybe you could  use global exception handling in the WebAPI and eliminate the try/catch you have in the code, by using the CustomExecptionFilter attribute that I used in WebAPI 2 solution,  which I got from the link discussing WebAPI Core exception handlining.  

    It was implemented in a VB.NET WebAPI 2. You should be able to understand it and using it in C#

    https://stackify.com/csharp-catch-all-exceptions/

    There is no try/catch anywhere in the WebAPI code and in the DAL code the WebAPI is using If an exception is thrown in WebAPI or DAL, then CustomExecptionFilter will catch it.

    ASP.NET WebAPI can be discussed in the ASP.NET forums.

    http://forums.asp.net/

    Imports System.Net
    Imports System.Net.Http
    Imports System.Web.Http.Filters
    Imports log4net
    
    Public Class CustomExceptionFilter
        Inherits ExceptionFilterAttribute
    
        private ReadOnly _logger As ILog
    
        public sub New()
            _logger = LogManager.GetLogger(GetType(CustomExceptionFilter))
        End sub
    
        Public Overrides Sub OnException(actionExecutedContext As HttpActionExecutedContext)
            MyBase.OnException(actionExecutedContext)
    
            Dim exceptionMessage as String = String.Empty
    
            If IsNothing(actionExecutedContext.Exception.InnerException ) Then
                exceptionMessage = actionExecutedContext.Exception.Message _
                                   & " " & actionExecutedContext.Exception.StackTrace
            Else 
                exceptionMessage =  actionExecutedContext.Exception.Message _
                                    & " " & actionExecutedContext.Exception.InnerException.Message _
                                    & " " & actionExecutedContext.Exception.StackTrace
            End If
    
            _logger.Error(exceptionMessage)
    
            dim response =  New HttpResponseMessage(HttpStatusCode.InternalServerError)With {.Content = New StringContent(“An unhandled exception was thrown by service.”),
                    .ReasonPhrase = "Internal Server Error.Please Contact your Administrator."}
    
            actionExecutedContext.Response = response
    
        End Sub
    End Class

    Imports System.Web.Http
    Imports DAL
    Imports Entities
    
    Namespace Controllers
    
        <CustomExceptionFilter>
        Public Class ProjectController
            Inherits ApiController
    
            Private ReadOnly _daoproject As IDaoProject
    
            public sub New (daoproject As IDaoProject)
                _daoproject = daoproject
            End sub
    
            <HttpGet>
            <ActionName("GetProjectById")>
            public Function GetProjectById(ByVal id As Int32) As DtoProject
                return _daoproject.GetProjectById(id)
            End Function
    
    
            <HttpGet>
            <ActionName("GetProjectsByUserId")>
            public Function GetProjectsByUserId(ByVal userid As String) As List(Of DtoProject)
                return _daoproject.GetProjectsByUserId(userid)
            End Function
    
            <HttpPost>
            <ActionName("CreateProject")>
            public sub CreateProject(ByVal dto As DtoProject)
                Call _daoproject.CreateProject(dto)
            End sub
            
            <HttpPost>
            <ActionName("UpdateProject")>
            public sub UpdateProject(ByVal dto As DtoProject)
                Call _daoproject.UpdateProject(dto)
            End sub
    
            <HttpPost>
            <ActionName("DeleteProject")>
            public sub  DeleteProject(ByVal dto As DtoId)
                Call _daoproject.DeleteProject(dto.Id)
            End sub
            
        End Class
    End Namespace


    • Edited by DA924x Monday, November 25, 2019 8:56 AM
    Monday, November 25, 2019 8:54 AM