1. Overview

In this article, we will explain about Spring security custom rolevoter example. Spring security provides role-based voting based on ULR or resources but sometimes we should require role voter more specific. We will also explain how we can implement spring security custom decision manager.

We are taking here an example to explain in more details, We have two roles in application admin and staff but staff cannot login in the application during the weekend (Sunday). If staff try to login during the weekend then an application will return 405 access denied status.

we have created accessDecisionManager which contains a list of voters.

We have created a class WeekOffVoter which implements AccessDecisionVoter interface, AccessDecisionVoter have a votemethod in which we should write our custom code to take a decision where allowed to access decision or not.

vote method may return three possible value:

ACCESS_DENIED: Deny to access resources

ACCESS_GRANTED : Grant to access resources

ACCESS_ABSTAIN : Not allowed nor Deny access resources, Decision will be take based on other voters

2. Example

spring security custom rolevoter

2.1 pom.xml

spring-boot-starter-security requires for spring security other dependency is for spring boot.

Output:

It will throw 405 - Access is denied because of custom role voter deny it.

Spring security custom rolevoter example – Access Deny

3. Conclusion

In this example, We learned about how we can implement role-based custom authorization to allowed or deny access the resources. We can write our custom code using custom voter implementation in spring security.

JavaDeveloperZone is the group of innovative software developers. We are expert in Java JEE and BigData application development. Our contributions will help Java developers and make development journey easy. Feel free to ask any question and suggestion. Always have space for improvement !
We are also providing software application development as service. Contact us