Ask Your Question
4

In a Spring Security application, how can the information of the currently logged-in user be shown in all templates, including the ones managed by WebMvcConfigurerAdapter?

asked 2023-01-26 11:00:00 +0000

lalupa gravatar image

edit retag flag offensive close merge delete

1 Answer

Sort by ยป oldest newest most voted
3

answered 2023-03-07 20:00:00 +0000

djk gravatar image

One way to achieve this is by using the Thymeleaf template engine and adding the following code to the header of each template:

<html xmlns:th="http://www.thymeleaf.org">
    <head>
        ...
        <meta th:if="${#authentication.getPrincipal() != null}" 
              th:content="${#authentication.getPrincipal().getUsername()}"
              name="username"/>
        ...
    </head>
    ...
</html>

This code checks if the user is logged in and if so, displays their username in the meta tag with the name "username".

To allow WebMvcConfigurerAdapter to use Thymeleaf templates, add the following configuration code to your WebMvcConfigurerAdapter:

@Configuration
@EnableWebMvc
public class WebConfig implements WebMvcConfigurer {

    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        registry.addResourceHandler("/resources/**")
            .addResourceLocations("/static/");
    }

    @Override
    public void configureViewResolvers(ViewResolverRegistry registry) {
        ThymeleafViewResolver resolver = new ThymeleafViewResolver();
        resolver.setTemplateEngine(templateEngine());
        registry.viewResolver(resolver);
    }

    ...

    @Bean
    public SpringTemplateEngine templateEngine() {
        SpringTemplateEngine engine = new SpringTemplateEngine();
        engine.setTemplateResolver(templateResolver());
        return engine;
    }

    private ITemplateResolver templateResolver() {
        SpringResourceTemplateResolver resolver = new SpringResourceTemplateResolver();
        resolver.setPrefix("/WEB-INF/views/");
        resolver.setSuffix(".html");
        resolver.setTemplateMode(TemplateMode.HTML);
        return resolver;
    }
}

This code configures a Thymeleaf view resolver and sets up a resource handler to serve static resources from a specific directory.

edit flag offensive delete link more

Your Answer

Please start posting anonymously - your entry will be published after you log in or create a new account. This space is reserved only for answers. If you would like to engage in a discussion, please instead post a comment under the question or an answer that you would like to discuss

Add Answer


Question Tools

Stats

Asked: 2023-01-26 11:00:00 +0000

Seen: 8 times

Last updated: Mar 07 '23