1

I want to get data who belong to one spesific user. If the user is not authorized i want to return Unauthorized(). How do I do this?

Here is my current code(Currently no user handling at all):

public async Task<IActionResult> GetById(int id, string token)
    {
        if (!ModelState.IsValid)
            return BadRequest();

        var entity = await Context.Set<T>().FindAsync(id).ConfigureAwait(false);

        if (entity == null)
            return NotFound();

        return Ok(entity);
    }

Entity has a relation to User in the database. And User has a property "JwtToken". So entity.User.JwtToken is possible to do.

The parameter "token" is a jwtToken passed as header from a GET Request.

1 Answer 1

1

Check the custom authorization policies. You can create a custom policy and continue with that.

On another note, you can work with the jwt token, without storing it into any database. Consider the following example: microsoft dev blogs

  1. The JWT token will be created during the authentication phase
  2. The JWT token will travel encrypted during the get/post/put/delete commands from web
  3. Your user.context can contain the JWT data and claims (like userid)

Then in your code, you can do the following:

    public async Task<IActionResult> GetById(int id, string token)
    {
        if (!ModelState.IsValid)
            return BadRequest();

        // Get your user id from your context here
        // Change the query to contain the user id
        var entity = await Context.Set<T>().FindAsync(id).ConfigureAwait(false);

        // If the user is authorized but there are no data for him
        // then a not found is the appropriate result
        if (entity == null)
            return NotFound();

        return Ok(entity);
    }

You are unauthorized to access the call not the data. The data just does not exist for you. If you return unauthorized, then you let the attacker know that the data exists, so they can enumerate data in your system.

1
  • Thank you for the answer! But I dont understand how to find the user connected to the token if its not stored in the database?
    – andersbs
    Apr 3, 2020 at 11:59

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.