0

Есть страницы на Freemarker, возможно ли возвращать аутентифицированного юзера постоянно, без написания в каждом методе @AuthenticationPrincipal Owner userAuth model.addAttribute("userAuth", userAuth);

@GetMapping
public String getAll(@AuthenticationPrincipal Owner userAuth, Model model) {
    model.addAttribute("userAuth", userAuth);
    return "index";
}

1 ответ 1

0

Создайте свой HandlerInterceptor приблизительно такой:

public class PrincipalToModelInterceptor extends HandlerInterceptorAdapter {
    @Override
    public void postHandle(
       HttpServletRequest request, 
       HttpServletResponse response,
       Object handler, 
       ModelAndView modelAndView) throws Exception {
       Object principal = 
         SecurityContextHolder.getContext().getAuthentication().getPrincipal();    
       // возможно захотите проверить principal на null перед добавлением 
       // это в случае, если нет аутентифицированного пользователя
       modelAndView.addObject("userAuth", principal);
    }
}

Далее нужно добавить interceptor в конфигурацию. Например, в класс конфигурации, который реализует WebMvcConfigurer :

@Override
public void addInterceptors(InterceptorRegistry registry) {
    registry.addInterceptor(new PrincipalToModelInterceptor());
}

Ваш ответ

By clicking “Отправить ответ”, you agree to our terms of service and acknowledge you have read our privacy policy.

Всё ещё ищете ответ? Посмотрите другие вопросы с метками или задайте свой вопрос.