0

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!

1 Answers1

1

I think this should be the expected behavior because APIs are stateless.

I reproduced your issue in my side. In my controller, I will set session, so the first time I send the request, I don't have the session value should be expected, but the second time the session should be set. But in fact, when I test the API in swagger UI, it can obtain the session value in the second record, but when I send a request in a client APP, it can't.

enter image description here

In my opinion, the token shouldn't be used as sessionToken != req, token should contain some basic user information/expire time/allowed scopes and so on, and we can decode the token to get and validate the information inside it.

Tiny Wang
  • 10,423
  • 1
  • 11
  • 29