Загрузка Thymeleaf и Spring и Spring Spring не работают - PullRequest
0 голосов
/ 06 марта 2019

Я пытаюсь запустить тимили, весеннюю защиту и весеннюю загрузку вместе, но я не уверен, как интегрировать все это, так как у меня были некоторые проблемы с весенней безопасностью, блокирующей накопители статики и т. Д.

Проблема в том, что после отправки имени входа он не проходит через обработчик конфигурации безопасности, поэтому я думаю, что представления не отображаются правильно.

SecurityConfig выглядит так:

@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {

    private static final Logger logger = LogManager.getLogger(SecurityConfig.class);

    @Autowired
    private LoggingAccessDeniedHandler accessDeniedHandler;

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http
            .authorizeRequests()
                .antMatchers(
                        "/",
                        "/js/**",
                        "/css/**",
                        "/img/**",
                        "/webjars/**").permitAll()
                .antMatchers("/user/**").hasRole("USER")
                .anyRequest().authenticated()
            .and()
            .formLogin()
                .loginPage("/login")
                .successHandler(myAuthenticationSuccessHandler())
                .permitAll()
            .and()
            .logout()
                .invalidateHttpSession(true)
                .clearAuthentication(true)
                .logoutRequestMatcher(new AntPathRequestMatcher("/logout"))
                .logoutSuccessUrl("/login?logout")
                .permitAll()
            .and()
            .exceptionHandling()
                .accessDeniedHandler(accessDeniedHandler);
    }

    @Override
    public void configure(WebSecurity web) throws Exception {
        web
            .ignoring()
            .antMatchers("/resources/**", "/static/**", "/css/**", "/js/**", "/images/**","/vendor/**","/fonts/**");
    }

    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        logger.info("configuring");
        auth.inMemoryAuthentication()
            .withUser("user").password("password").roles("USER")
            .and()
            .withUser("manager").password("password").roles("MANAGER");
    }

    @Bean
    public AuthenticationSuccessHandler myAuthenticationSuccessHandler(){
        logger.info("GOt into the thingie");
        return new MySimpleUrlAuthenticationSuccessHandler();
    }
}

class MySimpleUrlAuthenticationSuccessHandler
    implements AuthenticationSuccessHandler {

    private static final Logger logger = LogManager.getLogger(SecurityConfig.class);

    private RedirectStrategy redirectStrategy = new DefaultRedirectStrategy();

    @Override
    public void onAuthenticationSuccess(HttpServletRequest request,
        HttpServletResponse response, 
        Authentication authentication)
        throws IOException {

        handle(request, response, authentication);
        clearAuthenticationAttributes(request);
    }

    protected void handle(HttpServletRequest request,
        HttpServletResponse response, Authentication authentication)
        throws IOException {

        logger.info("got here");
        String targetUrl = determineTargetUrl(authentication);

        if (response.isCommitted()) {
            logger.info(
                "Response has already been committed. Unable to redirect to " + targetUrl);
            return;
        }

        redirectStrategy.sendRedirect(request, response, targetUrl);
    }

    protected String determineTargetUrl(Authentication authentication) {
        logger.info("got here in target");
        boolean isUser = false;
        boolean isAdmin = false;
        Collection<? extends GrantedAuthority> authorities
            = authentication.getAuthorities();
        for (GrantedAuthority grantedAuthority : authorities) {
            if (grantedAuthority.getAuthority().equals("ROLE_USER")) {
            isUser = true;
            break;
            } else if (grantedAuthority.getAuthority().equals("ROLE_ADMIN")) {
                isAdmin = true;
                break;
            }
        }

        if (isUser) {
            return "/homepage.html";
        } else if (isAdmin) {
            return "/console.html";
        } else {
            throw new IllegalStateException();
        }
    }

    protected void clearAuthenticationAttributes(HttpServletRequest request) {
        HttpSession session = request.getSession(false);
        if (session == null) {
            return;
        }
        session.removeAttribute
            (WebAttributes.AUTHENTICATION_EXCEPTION);
    }

    public void setRedirectStrategy(RedirectStrategy redirectStrategy) {
        this.redirectStrategy = redirectStrategy;
    }
    protected RedirectStrategy getRedirectStrategy() {
        return redirectStrategy;
    }
}

Контроллер выглядит так:

@RequestMapping(value = "/", method= RequestMethod.GET)
public String login(Model model){
    return "login";
}

@RequestMapping(value = "/login", method= RequestMethod.GET)
public String loginSucc(Model model){
    return "predictions";
}

в разделе src / main / resources / templates:

шаблоны html

Как видно из рисунка выше, у меня есть все необходимые html-страницы под шаблоном. ** Predictions.html там тоже просто не включен в скриншот. Наконец, login.html выглядит так:

<!-- Login Form -->
<form th:action="@{/login}" method="post">
    <input type="text" id="login" class="fadeIn second" name="login" placeholder="login">
    <input type="text" id="password" class="fadeIn third" name="login" placeholder="password">
    <input type="submit" class="fadeIn fourth" value="Log In">
</form>

После получения страницы входа и ввода любого имени пользователя и пароля он перенаправляется на страницу прогнозов. Это явно не аутентификация, так как имя пользователя / пароль не проверяется, а также на странице прогнозов я печатаю имя пользователя, которое просто не появляется (пусто). Я добавил фрагмент в соответствии с комментарием ниже. Но это не имеет значения.

Страница прогнозов после перенаправления из «login.html»: введите описание изображения здесь

Ответы [ 2 ]

1 голос
/ 06 марта 2019

переопределите этот метод, сконфигурируйте (WebSecurity web) и измените код, как показано ниже

 @Configuration
@EnableWebSecurity
public class SpringSecurityConfig extends WebSecurityConfigurerAdapter {

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http
                .authorizeRequests()
                .antMatchers("/user/**").hasRole("USER")
                .anyRequest().authenticated()
                .and()
                .formLogin()
            .loginPage("/login")
            .defaultSuccessUrl("/module",true)
            .failureUrl("/login?error=true")
        .permitAll();// others according to your need
    }
      @Override
        public void configure(WebSecurity web) throws Exception {
            web
                    .ignoring()
                    .antMatchers("/resources/**", "/static/**", "/css/**", "/js/**", "/images/**","/vendor/**","/fonts/**");
        }
}
0 голосов
/ 20 марта 2019

Проблема была с именем типа ввода, это был логин вместо имени пользователя:

Это исправлено:

  <form th:action="@{/login}" method="post">
            <input type="text" id="username" class="fadeIn second" name="username" placeholder="login">
            <input type="text" id="password" class="fadeIn third" name="password" placeholder="password">
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...