1

I have an e-commerce site that I developed the backend part with asp.net core web api and the frontend with reactjs. I have generated jwt token in asp.net core web api and also I keep roles in user table in sql database There are two separate users as admin and user.And for example, I want to have areas that only the admin can access, such as adding colors and adding a brand on the react side, but even though I do authorize on the asp.net side, a person whose role is not an admin can add colors in react when they log in to the site. Do I need to do something extra in React for this? I don't know much about it, I just did things on the asp.net core web api side. Maybe they have a mistake. But it successfully generates the token and I can see the data in the token. what should i do about it?

ColorController

using BusinessLayer.Abstract;
using DataAccessLayer;
using EntityLayer.Concrete;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace API.Controllers
{
    [Route("api/[controller]")]
    [ApiController]
    [Authorize(Roles = "admin")]
    public class ColorController : Controller
    {

        IColorService _colorservice;
        DatabaseContext db = new DatabaseContext();


        public ColorController(IColorService _colorservice)
        {
            this._colorservice = _colorservice;
        }

       
        [HttpGet("getall")]
        public async Task<IActionResult> GetAll()
        {
            var colors = await _colorservice.TGetAll();

            if(colors != null)
            {
                return Ok(colors);
            }
            else
            {
                return BadRequest();
            }

        }


        [HttpPost("add")]
       
        public async Task<IActionResult> Add(Color color)
        {
            var result =_colorservice.TAdd(color);

            if (result != null)
            {
                return Ok(result);
            }
            return BadRequest(result);
        }

     

    }
}

I said that only the admin can access the ColorController for testing purposes, but I did not do anything about it in the react part. When a non-admin person enters the react part, he can add color. How can I prevent this from happening. Do I need to open the token in react and check it according to the role data in it, if so, how can I do this? Or are there any other methods?

By the way, when the user logs in correctly, I send the token as a response in react.

UserRepository

 public async Task<string> Login(UserLoginDto logindto)
        {




            var crypto = new SimpleCrypto.PBKDF2();
            var _user = await dbContext.Users.Where(x => x.Mail == logindto.Mail).FirstOrDefaultAsync();

            if (_user != null)
            {

                if ( (!_user.isLock) && ( _user.Password == crypto.Compute(logindto.Password, _user.salt) ))
                {


                    var authClaims = new List<Claim>
                    {
                           new Claim(ClaimTypes.Email,_user.Mail),
                           new Claim(ClaimTypes.Name,_user.Name),
                           new Claim(ClaimTypes.Surname,_user.LastName),
                           new Claim(ClaimTypes.Role,_user.role),
                           

                           new Claim(JwtRegisteredClaimNames.Jti,Guid.NewGuid().ToString())
                    };
                    var authSigninKey = new SymmetricSecurityKey(Encoding.ASCII.GetBytes(configuration["JWT:Secret"]));

                    var token = new JwtSecurityToken(
                        issuer: configuration["JWT:ValidIssuer"],
                        audience: configuration["JWT:ValidAudience"],
                        expires: DateTime.Now.AddDays(1),
                        claims: authClaims,
                        signingCredentials: new SigningCredentials(authSigninKey, SecurityAlgorithms.HmacSha256Signature));
                    return new JwtSecurityTokenHandler().WriteToken(token);
                }
                else
                {
                    _user.LockCount +=1;
                    dbContext.SaveChanges();
                    if(_user.LockCount >= 3)
                    {
                        _user.isLock = true;
                        dbContext.SaveChanges();
                        return "blockuser";
                    }
                    return "invalid";
                }
            }



            return "invalid";


        }

EDIT

I found something called jwt token decode for this, but I couldn't find how to access the role data here either.

role data where I want to reach

enter image description here

NewPartizal
  • 604
  • 4
  • 18
  • I think this might help you https://stackoverflow.com/questions/70743498/role-based-react-router#:~:text=Define%20Roles%20and%20Permissions%20at,general%20and%20in%20react%20app. – mc-user Aug 26 '22 at 12:30
  • i am getting it with jwt token so i need to check role data in jwt token. The answer you lead creates the roles in React. When the user logs in, I send that person's token to React and that token has the role of the logged in user, so I need to make a check based on that token. – NewPartizal Aug 26 '22 at 12:37
  • I found something called jwt token decode for this, but I couldn't find how to access the role data here either. – NewPartizal Aug 26 '22 at 12:38
  • Just an observation, make sure you don't make any authorization decision in the frontend (ie, use auth info only for UX enhancements) and leave all authorization logic to the backend. – Leonardo Herrera Aug 26 '22 at 12:43
  • Yes I understand you but as you can see in the colorcontroller above, I just added [Authorize(Roles = "admin")] and it didn't work. Am I doing something wrong or do I have something to add? I agree with you that it is better to do it in the backend. But here I am trying this method because I can't do it in the backend. But as I said backend, I did it this way, do you have any suggestions for me? where am i doing wrong? – NewPartizal Aug 26 '22 at 13:05
  • I log in with the person whose postmande role is admin and after that I run the color add api, but even though the role is admin, 401Unauthorized the same goes for the person whose role is not admin. – NewPartizal Aug 26 '22 at 13:08

0 Answers0