Kumar Mullur
Kumar Mullur

Reputation: 9

Spring - Including current user in every call to Service/DAO Layer

I'm performing a business validation : whether current user has permission on particular set of data in the Data Base. For this to perform, I require the user name of logged in user.

The below sample works fine, in which after successful authentication in controller/interceptor, the "userName" parameter is passed in all calls from the controller to service layer.

@Service 
public class MyServiceImpl implements MyService {

    @Autowired
    private MyDAO myDAO;

    public String getData(String userName) {
          return myDAO.getData(userName);
    }
}

From controller the User Information is being passed to the Service and then to the DAO which I want to avoid.

I have my own mechanism to handle Authentication and Authorization. I need very simple solution to include this extra parameter in some context for each call to Service/DAO layers.

Note : I need a simple solution and don't want to use frameworks like spring-security etc.

Thank you in advance

Upvotes: 0

Views: 363

Answers (2)

Aravind Sai Vellappat
Aravind Sai Vellappat

Reputation: 121

Hoping that you are using thread context, you can easily set a parameter in the context and use it anywhere inside the application. (much like session variables).

You can refer to this link for assistance.
If you are already using spring sessions, then you set variables in session and make use of it.

Upvotes: 1

Justin LI
Justin LI

Reputation: 94

Maybe you can consider using ThreadLocal. Set the username to ThreadLocal after authentication and get the value in the Service class.

Upvotes: 0

Related Questions