0

I had implemented a JWT token in my web API project with roles management.its working fine. Authorization attributes also working well. Role Management also implemented with the JWT. Here is the Controller side Code.

public Object Authentication(string objuser, string password)
    {
        var Login = UserLogin.DoLogin(objuser, password);
        if (Login!=null)
        {
            if (Login.Email== "Sucess")
            {
                string UserRole = GetUserRole(Login.UserType);**//Admin,Buyer,Seller**
                string issuer = ConfigurationManager.AppSettings["Url"].ToString();
                var key = ConfigurationManager.AppSettings["AuthTokenKey"].ToString();
                var securityKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(key));
                var credentials = new SigningCredentials(securityKey, SecurityAlgorithms.HmacSha256);
                var permClaims = new List<Claim>();
                permClaims.Add(new Claim(JwtRegisteredClaimNames.Jti, Guid.NewGuid().ToString()));
                permClaims.Add(new Claim("valid", "1"));
               
                permClaims.Add(new Claim("userid", Login.User_ID.ToString()));
                permClaims.Add(new Claim("Email", Login.Email));
                permClaims.Add(new Claim(ClaimTypes.Role, UserRole));
                

                var token = new JwtSecurityToken(issuer,
                                issuer,
                                permClaims,
                                expires: DateTime.Now.AddDays(1),
                                signingCredentials: credentials);
                var jwt_token = new JwtSecurityTokenHandler().WriteToken(token);
                Login.Token = jwt_token;
                return Login;
              
            }
        }
        return Login;
    }

The startup file code is here

public void Configuration(IAppBuilder app)
    {
        //createRolesandUsers();
        string Url=ConfigurationManager.AppSettings["Url"].ToString();
        string key = ConfigurationManager.AppSettings["AuthTokenKey"].ToString();
        app.UseJwtBearerAuthentication(
            new JwtBearerAuthenticationOptions
            {
                AuthenticationMode = AuthenticationMode.Active,
                TokenValidationParameters = new TokenValidationParameters()
                {
                    ValidateIssuer = true,
                    ValidateAudience = true,
                    ValidateIssuerSigningKey = true,
                    ValidIssuer = Url, //some string, normally web url,
                    ValidAudience = Url,
                    IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(key))
                }
            });
    }

Ajax side code I am sending this token from ajax like this way:

 $.ajax({
        url: pathtoBuyerDetails,
        type: "Get",
        **headers: { Authorization: 'Bearer ' + sessionStorage.getItem('AuthorizeToken')},**
        data: { Time: Time, UID: UID },
        success: function (values) {something}

The new requirement from my client is that the token should be validated with UserID. i.e first Buyer login and his UserID=2 and TokenID="eyJqdGkiOiJkNTEwMzEwMC1jZDI3LTQxY2QtOTFmZS1iZGFjOTY5ZTMwOTUiLCJ2YWxpZCI6IjEiLCJleHAiOjE2MDExMjI4NTksImlzcyI6Imh0dHA6Ly9sb2NhbGhvc3Q6NTUyNTMvIiwiYXVkIjoiaHR0cDovL2xvY2FsaG9zdDo1NTI1My8ifQ"

Second Buyer login and his UserID=3 and TokenID="JqdGkiOiJkNTEwMzEwMC1jZDI3LTQxY2QtOTFmZS1iZGFjOTY5ZTMwOTUiLCJ2YWxpZCI6IjEiLCJleHAiOjE2MDExMjI4NTksImlzcyI6Imh0dHA6Ly9sb2NhbGhvc3Q6NTUyNTMvIiwiYXVkIjoiaHR0cDovL2xvY2FsaG9zdDo1NTI1My8ifQ.zEazMtGdWSjMOj4EqrCM3BX"

Required Solution if 2nd Buyer changes his id from 3 to 2 in session-storage and hit the URL he should not access the data of First Buyer because its token id does not match the first buyer token id. In short, we need to ensure that a buyer cannot access another buyer’s data. This means we need to check the JWT to ensure that the user ID we passed as the parameter is the same as the owner of the JWT.

aman jutt
  • 21
  • 8
  • 1
    It's already done as you included userid into JWT. Therefore user cannot change Id from 3 to 2 which will make JWT is not validated anymore. You can see my answer: https://stackoverflow.com/questions/40281050/jwt-authentication-for-asp-net-web-api/40284152#40284152 – cuongle Sep 25 '20 at 13:23
  • @cuongle Buyer can be changed UserID from session storage.then how I can handle this. Please help me – aman jutt Sep 25 '20 at 13:50
  • as @cuongle already pointed out, your token is married to the user. If user changes the ID, that does not suddenly make the token belong to another user. if this is really happening, then, this is a security hole that has to be dealt with how you are generating tokens and validating them for users. – Jay Sep 28 '20 at 05:30

0 Answers0