3
4 Comments

.Net Core authentication+session analysis paralysis

I'd like to build "yet another 'for sale'" site using .net core. However, as i'm in the File->New Project stage, I'm running into analysis paralysis as to how to best set up authentication, session handling, etc... Is using a jwt considered preemptive scaling? Should I just use the built in Identity that builds out the SQL tables? I'm a little stuck. Any thoughts?

on November 15, 2019
  1. 1

    If you have a SPA, then there is nothing wrong with JWT, it's pretty straightforward to implement (and plays well with Facebook or Google authentication). I built my platform Dupaws.com with built in authentication provided by dot net and JWT, never had an issue with users authentication.

    One thing to note though, you have to manually check token expiry and prompt users to login again, I set that to 60 days in my app. Also if you want to add more logic later on to your app (i.e claims and role based access), then having identity built in is helpful.

    1. 1

      Would you be able to issue refresh keys so when the jwt expires, you could generate a new one automatically for them?

      1. 1

        I actually didn't go through refresh keys as it wasn't straightforward and I was building the MVP and wanted to iterate quickly. Here is what I ended up doing:

        When users login, I create token object with user details to be saved on local storage, I send value "loggedDate"/"issued" on the C# backend and "expires" in addition to access_token, I set the expires to maximum of 60 days.

        You need to set the AccessTokenExpireTimeSpan to 60 days if you want users to be prompted to login again after 60 days.

        // Create the response building a JSON object that mimics exactly the one issued by the default /Token endpoint
                    JObject token = new JObject(
                        new JProperty("userName", user.UserName),
                        new JProperty("userId", user.Id),
                        new JProperty("firstName", user.FirstName),
                        new JProperty("lastName", user.LastName),
                        new JProperty("access_token", accessToken),
                        new JProperty("token_type", "bearer"),
                        new JProperty("profilePicUrl", user.ProfilePicUrl),
                        new JProperty("emailConfirmed", user.EmailConfirmed.ToString()),
                        new JProperty("userRole", user.UserRole),
                        new JProperty("doubleRole", user.DoubleRole.ToString()),
                        new JProperty("phoneConfirmed", user.PhoneNumberConfirmed.ToString()),
                           new JProperty("expires",
                            currentUtc.Add(Startup.OAuthOptions.AccessTokenExpireTimeSpan)
                                .ToString("ddd, dd MMM yyyy HH:mm:ss 'GMT'"))
                    );
        

        Note: I am using Vuejs for frontend. The line below is triggered whenever a user goes from one route to another (or enters the site).

        beforeEnter: (to, from, next) => {
        auth.checkTokenExpiry()
        }

        the checkTokenExpirty function is defined below in my auth.js file:

        checkTokenExpiry() {
        /Checking if token has expired/
        if (localStorage.getItem('access_token') != null) {
        var loggedDate = moment(JSON.parse(localStorage.getItem('loggedDate')))
        //JSON parse to get red of moment warning for ISO string datetime issues.
        var currentDate = moment()
        var difference = currentDate.diff(loggedDate, 'seconds')
        if (difference >= localStorage.getItem('expires')) {
        swal("Session Expired", "Your session expired, please login again to continue.", "info")
        this.logout() <--- all you have to do is to delete the localStorage object.

                }
            }
        },
  2. 1

    For a project I'm working on, I've decided on a hybrid auth approach: the application is a PWA with a static front-end (vue) and a Java back-end. For authentication, the API back-end returns a secure, HTTP-only cookie with a JWT as the cookie's value. subsequent API requests to the app server include this cookie automatically. The API back-end reads this cookie and analyzes the JWT for session expiry and authorization (roles and access). This approach is nice because I don't need to worry about storing the token on the front-end, nor do I need to intermingle request/session code in my business logic. When I do decide to scale-out for more processing power, additional servers won't need to worry about sharing session state with eachother :)

  3. 2

    This comment was deleted 7 years ago