How should DB entity IDs be managed to avoid security risks in a performant way?

筅森魡賤 提交于 2019-12-02 18:04:27

问题


Let's suppose I have a small website where users can public book reviews. So, in the server code we have somewhere something like this:

// Get user's read books.
public IHttpActionResult GetBooks()
{
    var user = GetLoggedUser();
    var userBooks = BooksRepository.GetByUserId(user.Id);

    return Ok({
        Name: user.Name,
        Books: userBooks.ToDtoList()
    });
}

public IHttpActionResult GetReviews(int bookId)
{
    var reviews = ReviewsRepository.GetByBookId(bookId);

    return Ok({
        Reviews: reviews.ToDtoList()
    });
}

Among other things, the review objects have an ID property (integer), that's their ID in the database. Now let's suppose I'm a malicious user, I log in and then, I start doing something like:

let limit = 100;

for (let id = someStart; id < (someStart + limit); id++) {
    fetch(URL + '/reviews?bookId=' + id)
        .then( /* getting other users' reviews... */ );
}

In order to avoid that situation, instead of using integers, I have seen people using GUIDs as the primary key of their tables. Do databases order GUIDs somehow internally so they can create an index? If not, isn't it a slow approach? Is there a better way to deal with IDs sent to the browser?


回答1:


Yes, there is a better way. Keep your integer IDs internal and never expose them to the clients.

One thing I did in the past, several times even, is to add a GUID column while keeping the original int IDs. Your back-end can still function using the int IDs, but when it comes to exposing data to the client, at that point you only send the GUIDs and never make the int IDs public. If a request is made from the browser, it will come with the GUID at which point you can obtain the int ID if you need it for something.

So, you're not changing your primary keys, all you do is add a new GUID column and then expose that to the clients.



来源:https://stackoverflow.com/questions/54824251/how-should-db-entity-ids-be-managed-to-avoid-security-risks-in-a-performant-way

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!