Spring Security: How to retrieve user's information in sign in?

Viewed 780

I have implemented Spring boot, with Spring security. And here is how I configure the http requests:

@Override
protected void configure(HttpSecurity http) throws Exception {
  http.authorizeRequests()
    .antMatchers( "/registeration").permitAll()
    .antMatchers("/home").hasRole("USER")
    .anyRequest().authenticated().and()
    .formLogin().loginPage("/login").permitAll();
  http.formLogin().defaultSuccessUrl("/home", true);
}

So, I am trying to redirect my logged in users to the /home url, and here is the controller:

@GetMapping("/home")
public String home(Model model,@RequestParam Long userId) {
    model.addAttribute("user", userService.getUserById(userId));
    return "home";
}

But, as you see, I need to pass the userId, to add it as a model into my view. The problem is, I don't know how to retrieve the information of yje user before redirect, and after log in.

3 Answers

Something like this should work

    @GetMapping("/home")
    public String home(Model model) {
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication()
        model.addAttribute("user", authentication.getPrincipal());
        return "home";
    }

Some good examples here

Thanks to @dur.

When the user logs in, then all of his information is in to the SecurityContextHolder, and the targeted uri can receive the principal, which contains the identity of the principal being authenticated. which contains the username of the logged in user. So, here is the solution:

@GetMapping("/home")
public String home(Model model,Principal principal) {
    final String currentUser = principal.getName();
    log.info("Logged User is:    "+ currentUser);

    model.addAttribute("user", userService.getUserByUsername(currentUser));
    return "home";
}

I wanted to add a comment to @Salman's answer, but I don't have the reputation to do that. what I wanted to say is that I think:

in model.addAttribute("user", userService.getUserByUsername(currentUser));, userService.getUserByUsername(currentUser) would return the same result as the injected principal. Therefore, model.addAttribute("user", principal); can work a little better.

Related