I'm in doubt as to how to get the user's name in the session. I'm using Spring Security 4.2
I have my User Class
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import lombok.Data;
@Entity
@Data
public class Usuario {
@Id @GeneratedValue
private Integer id;
private String login;
private String senha;
private String papel;
}
My UserController class
import java.util.List;
import javax.faces.bean.ViewScoped;
import javax.inject.Named;
import lombok.Getter;
import lombok.Setter;
import org.springframework.beans.factory.annotation.Autowired;
@Named
@ViewScoped
public class UsuarioController {
@Autowired
private UsuarioRepository usuarioRepository;
@Getter @Setter
private List<Usuario> usuarios;
@Getter @Setter
private Usuario usuario = new Usuario();
}
And my SecurityConfig class, which plays the role of the filter, already built into Spring Security.
@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
@Autowired
private UsuarioRepository usuarioRepository;
@Override
protected void configure(HttpSecurity http) {
try {
http.csrf().disable();
http
.userDetailsService(userDetailsService())
.authorizeRequests()
.antMatchers("/").permitAll()
.antMatchers("/cliente.jsf").permitAll()
.anyRequest().authenticated()
.and()
.formLogin()
.loginPage("/login.jsf")
.permitAll()
.failureUrl("/login.jsf?error=true")
.defaultSuccessUrl("/cliente.jsf")
.and()
.logout()
.logoutSuccessUrl("/login.jsf");
}
catch (Exception ex) {
throw new RuntimeException(ex);
}
}
@Override
protected UserDetailsService userDetailsService() {
List<Usuario> usuarios = usuarioRepository.findAll();
List<UserDetails> users = new ArrayList<>();
for(Usuario u: usuarios){
UserDetails user = new User(u.getLogin(), u.getSenha(), AuthorityUtils.commaSeparatedStringToAuthorityList("ROLE_"+u.getPapel()));
users.add(user);
} return new InMemoryUserDetailsManager(users);
}
}
Should I create another class to retrieve the name, id of the user?