2

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.

dda
  • 6,030
  • 2
  • 25
  • 34
Sal-laS
  • 11,016
  • 25
  • 99
  • 169

3 Answers3

1

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

Essex Boy
  • 7,565
  • 2
  • 21
  • 24
1

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";
}
Mahozad
  • 18,032
  • 13
  • 118
  • 133
Sal-laS
  • 11,016
  • 25
  • 99
  • 169
0

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.

Ahmad Raza
  • 2,850
  • 1
  • 21
  • 37
glithedev
  • 56
  • 3
  • In general it is not the same. In this case it is not clear, because OP has not shown his user model class. – dur Nov 23 '17 at 17:06