2
\$\begingroup\$

Im at the point where I am designing my api security and I was going with a custom attribute I don't want to use third party systems as they cost money.

I was going to use the client id and the secret id approach and I am asking is this a safe enough way to accomplish it I am interacting to my api through a database layer.

So the first thing that will be called is this bit of code which goes out to find a match against the db and then called by the controller

How should I encrypt the client id though in the database so that it cant be easy guessed.

public bool FindKeysByClientIdByApiKey(Guid apiKey, Guid clientId)

  {

       ApiKeys results = new ApiKeys();

        using (var connection = new SqlConnection(constr))

        {

            return connection.Query<ApiKeys>($"SELECT * FROM {schemaDefination}.[ApiKeys] where ClientId= @ClientId and ApiKey=@ApiKey and isActive=1 and isDeleted!=1",

              new { ApiKey = apiKey, ClientId = clientId }).Any();

        }

  }

Controller Code

public class ApiKeysController : ControllerBase

{

    DBContext db = new DBContext();

    [HttpGet]

    public int Get(Guid ApiKey, Guid ClientdId)

    {            

        if (!db.FindKeysByClientIdByApiKey(ApiKey, ClientdId))  {

            return StatusCodes.Status401Unauthorized;

        }else

            return StatusCodes.Status200OK;

    }

}

To Enable or disable this at will I am creating a custom Attribute which will have the following.

public async  Task OnActionExecutionAsync(ActionExecutingContext context, ActionExecutionDelegate next)

{

        //before

        if(!context.HttpContext.Request.Headers.TryGetValue(ApiKeyHeaderName, out var potentialApiKey))

        {

            context.Result = new UnauthorizedResult();

            return;



        }



        // before

        if (!context.HttpContext.Request.Headers.TryGetValue(ClientId, out var potentialClientId))

        {

            context.Result = new UnauthorizedResult();

            return;





        }

            var getConfigurationResult = Do Stuff here



        await next();

        //after



}

This should mean that I can simply call attribute on my controller would this method work ok. I presume this method will also allow me to decorate my Gets and Puts to ensure that they are also authorize what should I be returning in ApiControllers get so I can make it more generic

[Apikey]

\$\endgroup\$
1
  • \$\begingroup\$ I see a view upvotes but no suggestions on how to best encrypt the client id \$\endgroup\$ Apr 5 '20 at 21:22

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.