12

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

1
  • 1
    You might read about AccessDecisionVoter to make ConsensusBased decisions. Commented Jul 26, 2012 at 7:16

1 Answer 1

21

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.

Sign up to request clarification or add additional context in comments.

2 Comments

the advice on how error-prone Spring EL is and how to avoid it, is invaluable. +10 for that! thnx
I was getting an error because my method was void, one hour to see that. Thanks for "method which returns true or false depending"

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.