I am doing a POC for JWT token in ASP.NET WEB API. First I have created a login API for student, in that I am generating the token as well as storing the session value for token. This token value needs to be provided by the student when he is once logged in and try to make another request to get his profile details. But as I can see the token value is coming out as null in the student attribute upon debugging. Why is that happening and how do i fix it?
Below is the login action method where I am generating token as well as setting it in Session string.
[HttpPost]
public JsonResult AuthenticateStudent(string emailId, string password)
{
try
{
if(studBLObj.AuthenticateStudent(emailId, password))
{
HttpContext.Session.SetString("email_ID", emailId);
HttpContext.Session.SetString("studentRole", "Student");
string token = GenerateToken();
HttpContext.Session.SetString("Token", token);
return new JsonResult(new { Success = true, message = "Login Succesful", token = token });
}
else
{
return new JsonResult(new { Success = false, message = "Error! Please contact admin" });
}
}
catch (Exception e)
{
return new JsonResult(new { Success = false, message = e.Message });
}
Once Student is logged in he should be able to access his details in below method but he has to give the token as well as be authenticated as "student" using the custom filter.
[Student]
[HttpGet]
public string GetStudentProfile(int rollNo)
{
try
{
var studentsProfile = studentBLObj.GetStudentProfile(rollNo);
JsonResult jsonResult = new JsonResult(studentsProfile);
var jsonString = Newtonsoft.Json.JsonConvert.SerializeObject(jsonResult.Value);
return jsonString;
}
catch (Exception e)
{
throw e;
}
}
Here comes the issue where upon debugging I can see that when I use get session inside the StudentAttribute filter, the value of it is null:
public class StudentAttribute : ActionFilterAttribute
{
public override void OnActionExecuting(ActionExecutingContext context)
{
base.OnActionExecuting(context);
**//THIS IS NOT GETTING THE TOKEN VALUE AND IS SHOWING NULL**
string sessionToken = context.HttpContext.Session.GetString("Token");
//THIS HERE IS WORKING PERFECT AND GETTING THE TOKEN VALUE THROUGH HTTPHEADER
var req = context.HttpContext.Request.Headers["Authorization"];
if (sessionToken==null || sessionToken != req)
{
context.Result =
new RedirectToRouteResult(new RouteValueDictionary
{
{ "action", "UnauthorizedAccess" },
{ "controller", "Student" }
});
return;
}
else
{
//whatever request is next, it will process and continue
return;
}
}
}
I have implemented this before in MVC core project and it worked perfectly fine. Help in this is much appreciated. Thanks!