1

I'm creating my first WebAPI project, and have hit my first snag. It seems that because the WebAPI model is stateless, I have no Session available to me. So, my attempt to add a session variable when logging in, has failed.

public static void CreateSession(int userId, string firstName, string surname, int timezoneOffset, string timezoneName)
{
    // Create the object.
    var session = new SessionToken
    {
        FirstName = firstName,
        Surname = surname,
        TimezoneName = timezoneName,
        TimezoneOffset = timezoneOffset,
        UserID = userId
    };

    // Is there an existing session?
    var existing = HttpContext.Current.Session[SESSIONNAME];

    // If so, we need to kill it and refresh it. Not sure why we would have this case though.
    if (existing != null)
        HttpContext.Current.Session.Remove(SESSIONNAME);

    // Create the session.
    HttpContext.Current.Session.Add(SESSIONNAME, session);

}

Session is null, and this is because of the stateless model used by WebAPI.

How can I achieve this with Web API? How can I have something to check and query to see if the current user is valid? My session would normally hold some items such as the chaps name, to render on the layout screen - but it looks like that isn't possible right now.

Craig
  • 18,074
  • 38
  • 147
  • 248
  • Refer this: http://stackoverflow.com/a/13758602 – Divyang Desai Nov 19 '16 at 09:25
  • And another way, if you want to it in more secure, then use authentication token like [JWT](https://jwt.io/introduction/) or custom. – Divyang Desai Nov 19 '16 at 09:29
  • That seems to enable sessions. Is that best practise (As web api seems to specifically get rid of sessions), or is this a suitable fix? I saw this, but never created my project with "Individual user accounts" selected. http://www.dotnetcurry.com/aspnet/1223/secure-aspnet-web-api-using-tokens-owin-angularjs – Craig Nov 19 '16 at 09:29

1 Answers1

0

The recommended approach is using stateless authentication and authorization with tokens.

Since some years, it's very easy to configure your WebAPI to integrate OAuth2 workflow using an OWIN middleware.

Learn how following this tutorial.

What you call session items, in OAuth2 you talk about claims.

Matías Fidemraizer
  • 63,804
  • 18
  • 124
  • 206