How do I search for logged-in user information other than by the controller?

Asked

Viewed 522 times

1

I’m using spring security to log in to my site. It’s working, I can register new users, log in and drop off.

I have a navbar that, when the user is not logged in, appears the option "Log in or register", and when it is logged in appears the option "Log out".

But I would like you to display the username logged in next to the logout link, and I’m not being able to do that:

Securityconfig:

@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
    auth
        .jdbcAuthentication()
        .usersByUsernameQuery(userQuery)
        .authoritiesByUsernameQuery(roleQuery)
        .dataSource(dataSource)
        .passwordEncoder(passwordEncoder);
}

@Override
protected void configure(HttpSecurity http) throws Exception {
    http
        .authorizeRequests()
        .antMatchers("/**").permitAll()
        .anyRequest()
            .authenticated()
                .and().csrf().disable()
            .formLogin()
                .loginPage("/login").failureUrl("/login?error=true").defaultSuccessUrl("/")
                .usernameParameter("email").passwordParameter("senha")
            .and().logout()
                .logoutRequestMatcher(new AntPathRequestMatcher("/logout")).logoutSuccessUrl("/home");
}

Navbar:

<nav class="navbar navbar-expand-lg navbar-dark bg-dark custom"
    th:fragment="cabecalho">
    <a href="/home"><img src="../img/transp_IziFood6.png" class="navbar-brand logo"/></a>
    <form class="form-inline">
        <input class="form-control mr-sm-2 searchNav" type="search" placeholder="Pesquisar">
        <button class="btn btn-outline-light my-2 my-sm-0" type="submit">Pesquisar</button>
    </form>
    <div th:if="${session.isEmpty()}">
        <div class="divlogin"><a href="/login">Entre </a> | <a href="/registration"> Cadastre-se</a> </div>
    </div>
    <div th:unless="${session.isEmpty()}">
        <div class="divlogin"><a href="/logout">Sair </a></div>
    </div>
</nav>

As this navbar is a fragment, I would like to know how to search the information by Thymeleaf, so you don’t have to keep repeating code searching for user information logged in several controllers.

1 answer

1


You can recover the authentication data through the SecurityContextHolder and SecurityContext:

Authentication authentication = SecurityContextHolder.getContext().getAuthentication();

With the object Authentication, you can recover data from Principal authenticated through the getPrincipal(). There are other methods to recover Authorities, credentials, check if it is logged in...

Details can be seen here, here and here

  • This command I can run on Thymeleaf?

  • Yes, you can create a service that contains this code and refer it to your website

Browser other questions tagged

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