Reputation:
I have an application that is authorizing an OAuth2 token with Spring Security. Using the @PreAuthorize tag, I can easily make sure that a user has a permission before allowing them to access a method:
@PreAuthorize("#oauth2.hasScope('account.read')")
public void getAccount(int accountId);
{
//return account
}
This works great at restricting users without the account.read permission from accessing this method.
The only problem is now any user with this permission can access any account. I want to restrict the users to only access their own account. I'm sure this is a common scenario. How do other applications deal with this?
Upvotes: 0
Views: 49
Reputation: 3542
So, the question here - how would system know if account belongs to user? The answer would be that you are probably storing User<->Account relationship in the database. The most simple solution would be to do the check right in your method:
@PreAuthorize("#oauth2.hasScope('account.read')")
public Account getAccount(int accountId) {
// get account from db
Account account = repository.findById(accountId);
// you will need a little helper to get your User from
//Spring SecurityContextHolder or whatever there for oauth2
User user = securityManager.getCurrentUser();
if (account.belongs(user)) {
return account;
} else {
throw new UnathorizedException("User is not authorized to view account");
}
}
Upd. one of possible improvements may be to first get the user, get id from it and do a repository.findByIdAndUserId(accountId, userId) or somthing like that. (or even repositoryFindByIdAndUser(accountId, user))
Upvotes: 2