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.
This command I can run on Thymeleaf?
– guilhermedjc
Yes, you can create a service that contains this code and refer it to your website
– nullptr