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

  • Thread starter Thread starter Harish Waghmare
  • Start date Start date
H

Harish Waghmare

Guest
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;
}

Continue reading...
 
Back
Top