Spring security authrorize based on input parameter criteria

10,305

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.

Share:
10,305

Related videos on Youtube

Sourabh Girdhar
Author by

Sourabh Girdhar

Updated on September 15, 2022

Comments

  • Sourabh Girdhar
    Sourabh Girdhar over 1 year

    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

  • Anand Rockzz
    Anand Rockzz almost 5 years
    the advice on how error-prone Spring EL is and how to avoid it, is invaluable. +10 for that! thnx