Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Spring MVC, getting principal from security context in service layer

  1. What are the advantages to get principal as a parameter Principal principal in spring controller and then pass it to service layer over getting principal in the service layer immediately though SecurityContextHolder.getContext().getAuthentication().getPrincipal() ?
  2. What is the best approach to get principal details in service layer without checking getAuthentication() and getPrincipal() objects for null everywhere (something like a custom wrapper)?
like image 548
Alex Avatar asked Feb 12 '13 00:02

Alex


1 Answers

    • Your service API will be more easy to use. You will see dependency on principal directly, so you wan't call some service method by mistake in environment where principal does not exist.
    • In general less dependencies on SpringSecurity code means less problems in a case of migration to new Spring Security version.
    • You will be able to reuse your service layer in environment where Spring Security does not exist.
  1. Prepare some wrapper class (for example AuthenticationService). Add getPrincipal() method to it. Implement your checks. Inject AuthenticationService everywhere insted of direct calls to SecurityContextHolder.
like image 125
Maksym Demidas Avatar answered Oct 04 '22 11:10

Maksym Demidas