0

I am using spring security for the authentication purposes in my project wherein after successful authentication, I get the principal object inside which the various details are stored. This principal object is passed to various methods which allow the entries to be reflected in the database against the current user. In short, principal helps me in giving principal.getName() everywhere i need it.

But now when I login through spring social then I do not have principal object of Principal in hand, instead I have implemented MyPrincipal class --->

public class MyPrincipal implements Principal {
public String name;
public boolean flag;

public boolean isflag() {
    return flag;
}

public void setFlag(boolean flag) {
    this.flag = flag;
}

public void setName(String name) {
    this.name = name;
}

@Override
public String getName() {
   return name;
}

}

Then in the social login handler, I am adding the current username and flag value to myPrincipal object, and forwarding the user to the same home page where the spring security forwards in case of normal login.

  MyPrincipal myPrincipal = new MyPrincipal();
                    myPrincipal.name = username;
                    myPrincipal.socialFlag = true;
                    modelMap.addAttribute("myPrincipal", myPrincipal);
                    return new ModelAndView("forward:/home");

Adding this object in session by annotating class with

@SessionAttributes({"myPrincipal"})

Now from here on-wards I want the flow to be handed over to the home page with all the functionality working for the user correctly. But each method is taking Principal principal as argument, just like this -->

 @RequestMapping(value = {"/home"}, method = RequestMethod.POST)
 @ResponseBody
  public ModelAndView test(ModelMap modelMap, Principal principal) {
   String name = principal.getName();
 }

There are two different things going around in both cases- Normal login is giving me principal directly but social login is giving me it in session attributes.

I do not want to pass principal as parameters even in case of normal spring security login, instead here also I want to put it in session attribute. How can I do this and where to make the changes when I have implemented my own authentication provider.

Abhinav
  • 961
  • 2
  • 11
  • 17

1 Answers1

1

I don't think I fully understand...However, in general it shouldn't be necessary to pass principal instances around. Use org.springframework.security.core.context.SecurityContextHolder.getContext() to get a hold of the context then call SecurityContext.getAuthentication().getPrincipal() or SecurityContext.getAuthentication().getDetails().

Marcel Stör
  • 22,695
  • 19
  • 92
  • 198