Get User name in jsf session

Asked

Viewed 223 times

2

I’m having doubts about how to get the username 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 User Controller 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 makes the filter paper, already embedded in 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 must create another class to redeem the name, user id?

  • Can anyone help me? Any tips?

  • Hello, you can take a look in that material from the Baeldung site. Although it is in English, looking at the codes can already have an orientation. Another tip would be to look in the commenting who apparently seeks to know the same thing as you.

No answers

Browser other questions tagged

You are not signed in. Login or sign up in order to post.