Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Spring security authrorize based on input parameter criteria

I have a scenario where I need to authorize user based on combination of his permission and input parameter passed.

this is the current scenario

public void bookTicket(String bookingType)
    {
    if (bookingType == "AIR"){
         bookAirTicket();
    }else{
         bookBusTicket();
    }
    }


@PreAuthorize("hasRole('BOOK_AIR')")
private void bookAirTicket(){
}

@PreAuthorize("hasRole('BOOK_BUS')")
private void bookBusTicket(){
}

Can we have some thing like

@PreAuthorize(("hasRole('BOOK_AIR')" AND bookinType='AIR') OR ("hasRole('BOOK_BUS')"  AND bookinType='BUS'))
public void bookTicket(String bookingType)
    {
    if (bookingType == "AIR"){
         bookAirTicket();
    }else{
         bookBusTicket();
    }
    }

Basically I need authorization based in input parameters

Thanks

like image 687
Sourabh Girdhar Avatar asked Jul 26 '12 07:07

Sourabh Girdhar


1 Answers

Yes, you can. Parameters can be accessed as Spring EL variables. In fact the reference manual gives several examples which use method parameters. The class needs to be compiled with debug symbols present (which is usually the case).

Note that the annotation value is a single expressions string:

"(hasRole('BOOK_AIR') and #bookinType == 'AIR') or (hasRole('BOOK_BUS') and #bookinType='BUS')"

In practice, using complicated expressions is rather error-prone. You could also use a simpler expression, something like

"@accessChecker.check('book', #bookinType)"

Where accessChecker is a bean in your application context with a "check" method which returns true or false depending on whether the supplied operation information is allowed (you can check the current user's roles by accessing the security context yourself - you'll find that discussed elsewhere on SO).

You could also look into writing your own AccessDecisionManager or AccessDecisionVoter and plugin the functionality there, but that requires more internal knowledge.

like image 160
Shaun the Sheep Avatar answered Oct 19 '22 08:10

Shaun the Sheep