1

I am in doubt as to how to get the user name in the session. I am using Spring Security 4.2

I have my Class Usuario

@Entity
@Data
public class Usuario {

    @Id @GeneratedValue
    private Integer id;

    private String login;
    private String senha;
    private String papel;

}

My class UsuarioController

@Named
@ViewScoped
public class UsuarioController {

    @Autowired
    private UsuarioRepository usuarioRepository;

    @Getter @Setter
    private List<Usuario> usuarios;

    @Getter @Setter
    private Usuario usuario = new Usuario();

}

And my class SecurityConfig, 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);

    }
}

I already researched other posts in the forum, did not help, any tips? Do I need to create another class?

BalusC
  • 1,082,665
  • 372
  • 3,610
  • 3,555
Genn
  • 11
  • 1
  • 3
  • 1
    For CDI/JSF you are using the wrong combination of `@Named` and `@Viewsoped`. One is 'CDI' and one is 'JSF'. If it works that way for sprimg, the question is in no way jsf related. – Kukeltje Aug 27 '17 at 18:51
  • Hi Kukeltje, and what would be the correct form? – Genn Aug 27 '17 at 19:00
  • Normally I'd say, try google, but I'm in a good mood: https://stackoverflow.com/questions/14384369/how-to-replace-managedbean-viewscope-by-cdi-in-jsf-2-0-2-1 – Kukeltje Aug 27 '17 at 19:03
  • Kukeltje, I'm using the OmniFaces native @ViewScoped, which is compatible with the CDI. – Genn Aug 27 '17 at 19:06
  • You use `javax.faces.bean.ViewScoped` that is not the omnifaces one – Kukeltje Aug 27 '17 at 19:14
  • Yes, but I use native omnifaces. – Genn Aug 27 '17 at 19:42

2 Answers2

2

If you want to get the username of the current user authenticated with Spring Security, you could use the following:

final String currentUserName = SecurityContextHolder.getContext().getAuthentication().getName();

Here, we find the current Authentication and query it for the username. For password-based authentiction, getName() returns user's login.

Roman Puchkovskiy
  • 11,415
  • 5
  • 36
  • 72
  • Hi Roman! Thank you for answer! I insert where the end String Current User Name = SecurityContextHolder.getContext (). GetAuthentication (). GetName () ;? At SecurityConfig? Or do I create another class? – Genn Aug 27 '17 at 18:53
-1

You can create your own SecurityUtility class like this:

public final class SecurityUtils {

    private SecurityUtils() {
    }


    public static String getUserName() {
        SecurityContext securityContext = SecurityContextHolder.getContext();
        Authentication authentication = securityContext.getAuthentication();
        String userName = null;
        if (authentication != null) {

                UserDetails userDetails = (UserDetails) authentication.getPrincipal();
                userName = userDetails.getUsername();

        }
        return userName;
    }

And call it from the class where you need the username, for example: SecurityUtils.getCurrentUserLogin();

Daniel C.
  • 5,418
  • 3
  • 23
  • 26