복붙노트

[SPRING] sec : thymeleaf 뷰에서 isAuthenticated () 및 isAnonymous ()를 true로 반환하도록 권한 부여

SPRING

sec : thymeleaf 뷰에서 isAuthenticated () 및 isAnonymous ()를 true로 반환하도록 권한 부여

현재 사용중인 스프링 부트 프로젝트에서 필자는 thymeleaf 뷰에서 다음과 같은 코드 스 니펫을 보았습니다.

<div class="account">
    <ul>
        <li id="your-account" sec:authorize="isAnonymous()">
            ... code 1 ...
        </li>
        <li id="your-account" sec:authorize="isAuthenticated()">
            ... code 2 ...
        </li>
        <li th:if="${cart}">
            ...
        </li>
    </ul>
</div>

스 니펫 1 또는 2 중 하나만 같은 시간에 표시되어야합니다. 하지만 지금 브라우저에서이보기를 열면 두 영역이 표시됩니다.

누구나 여기서 무엇이 잘못되었는지 알 수 있습니까?

ps : 내 thymeleaf 구성 클래스는 다음과 같습니다.

@Configuration
public class Thymeleaf {

  @Bean
  public SpringTemplateEngine templateEngine() {
    SpringTemplateEngine engine  =  new SpringTemplateEngine();

    final Set<IDialect> dialects = new HashSet<IDialect>();
    dialects.add( new SpringSecurityDialect() );
    engine.setDialects( dialects );

    return engine;
  }

}

ps : 내 스프링 보안 구성 클래스는 다음과 같습니다.

@Configuration
@ComponentScan(value="com.spring.loja")
@EnableGlobalMethodSecurity(prePostEnabled=true)
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
        @Autowired
        private UserDetailsService userDetailsService;

        @Autowired
        private SocialUserDetailsService socialUserDetailsService;

        @Autowired
        private PasswordEncoder passwordEncoder;

        @Autowired
      private AuthenticationManagerBuilder auth;

        @Override
    protected void configure(HttpSecurity http) throws Exception {
        http
            .csrf()
                .disable()
            .authorizeRequests()
                .antMatchers("/b3/**", "/v1.1/**", "/**", "/destaque/**", "/categoria/**").permitAll()
                .anyRequest().authenticated()
                    .and()
                .formLogin()
                    .loginPage("/signin")
                    .loginProcessingUrl("/login").permitAll()
                    .usernameParameter("login")
                    .passwordParameter("senha")
                    .and()
                .logout()
                    .logoutUrl("/logout")
                    .logoutSuccessUrl("/")
                    .and()
                .apply(new SpringSocialConfigurer());
    }

        @Override
        public void configure(WebSecurity web) throws Exception {
            DefaultWebSecurityExpressionHandler handler = new DefaultWebSecurityExpressionHandler();
        handler.setPermissionEvaluator(new CustomPermissionEvaluator());
        web.expressionHandler(handler);
    }

        @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth
            .userDetailsService(userDetailsService)
            .passwordEncoder(passwordEncoder);
    }

        @Bean
        @Override
        public AuthenticationManager authenticationManagerBean() throws Exception {
            return auth.getOrBuild();
        }
}

해결법

  1. ==============================

    1.내 수정은 내 웹 응용 프로그램 종속성에 thymeleaf-extras-springsecurity4를 추가하는 것이 었습니다.

    내 수정은 내 웹 응용 프로그램 종속성에 thymeleaf-extras-springsecurity4를 추가하는 것이 었습니다.

    나는 thymeleaf extras를 포함하는 spring boot (1.4.1.RELEASE)를 가져 오는 부모 pom을 가지고 있었지만 다음과 같이 특정 thymeleaf extras 의존성을 호출하는 데 필요한 웹 응용 프로그램 코드가있는 자식 child :

    <의존성>      org.thymeleaf.extras      thymeleaf-extras-springsecurity4

    그리고 voilà ... 이제 작동합니다.

    나는 thymeleaf 템플릿 (.html 파일)에서 사용자가 로그인했을 때 div와 그 내용 만 표시하도록

    그 div를 항상 보여주고있었습니다.

    thymeleaf extras 의존성을 포함하기 전에 봄 보안 태그를 인식 할 수 없다는 오류를 던지면 디버깅이 훨씬 쉬워졌습니다.

  2. ==============================

    2.결과적으로 클래스 패스에 thymeleaf-extras-springsecurity4 아티팩트가 누락 될 수 있습니다. 나는이 문제를 안고 있었고 (대부분의 머리카락을 뽑은 후) 항아리가 없기 때문에 SpringSecurity 방언이 thymeleaf 용으로로드되지 않았다는 것을 발견했습니다. 이 종속성을 다음과 같이 추가했습니다.

    결과적으로 클래스 패스에 thymeleaf-extras-springsecurity4 아티팩트가 누락 될 수 있습니다. 나는이 문제를 안고 있었고 (대부분의 머리카락을 뽑은 후) 항아리가 없기 때문에 SpringSecurity 방언이 thymeleaf 용으로로드되지 않았다는 것을 발견했습니다. 이 종속성을 다음과 같이 추가했습니다.

    <dependency>
        <groupId>org.thymeleaf.extras</groupId>
        <artifactId>thymeleaf-extras-springsecurity4</artifactId>
    </dependency>
    

    희망이 도움이됩니다. https://stackoverflow.com/a/31622977/4091838 참조

  3. ==============================

    3.내 경우 엔

    내 경우 엔

    spring.jpa.hibernate.ddl-auto=auto
    

    spring.jpa.hibernate.ddl-auto=none
    

    application.properties 파일에서 해결책이되었습니다.

  4. ==============================

    4.위의 모든 방법을 시도했지만 나에게 효과가 없었지만 다른 사람들에게 효과가있을 수 있습니다. 나를 위해 일한 것은 아래와 같습니다.

    위의 모든 방법을 시도했지만 나에게 효과가 없었지만 다른 사람들에게 효과가있을 수 있습니다. 나를 위해 일한 것은 아래와 같습니다.

    <properties>
        <thymeleaf.version>3.0.9.RELEASE</thymeleaf.version>
        <thymeleaf-layout-dialect.version>2.2.2</thymeleaf-layout-dialect.version>
        <thymeleaf-extras-springsecurity4.version>3.0.2.RELEASE</thymeleaf-extras-springsecurity4.version>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
        <java.version>1.8</java.version>
    </properties>
    

    다음은 thymeleaf에 대한 구성 설정입니다.

    @Bean
    public SpringTemplateEngine templateEngine() {
        SpringTemplateEngine templateEngine = new SpringTemplateEngine();
        templateEngine.setTemplateResolver(thymeleafTemplateResolver());
        templateEngine.setEnableSpringELCompiler(true);
        templateEngine.addDialect(new SpringSecurityDialect());
        return templateEngine;
    }
    
    @Bean
    public SpringResourceTemplateResolver thymeleafTemplateResolver() {
        SpringResourceTemplateResolver templateResolver = new SpringResourceTemplateResolver();
        templateResolver.setPrefix("classpath:templates/");
        templateResolver.setSuffix(".html");
        templateResolver.setCacheable(false);
        templateResolver.setTemplateMode(TemplateMode.HTML);
        return templateResolver;
    }
    
    @Bean
    public ThymeleafViewResolver thymeleafViewResolver() {
        ThymeleafViewResolver viewResolver = new ThymeleafViewResolver();
        viewResolver.setTemplateEngine(templateEngine());
        viewResolver.setCharacterEncoding("UTF-8");
        return viewResolver;
    }
    
  5. ==============================

    5.구성에서 모든 URL을 익명 액세스로 설정했습니다.

    구성에서 모든 URL을 익명 액세스로 설정했습니다.

    .antMatchers("/b3/**", "/v1.1/**", "/**", "/destaque/**", "/categoria/**").permitAll()
    

    이 시도

    .antMatchers("/b3/**", "/v1.1/**", "/**", "/destaque/**", "/categoria/**")
        .anyRequest().authenticated()
                    .and()
    

    permitAll ()로 인해 모든 URL은 익명 사용자와 인증 된 사용자가 액세스 할 수 있으므로 두 URL 모두 표시됩니다. 이러한 함정을 피하기 위해 스위치 케이스를 사용해보십시오.

  6. from https://stackoverflow.com/questions/32904857/secauthorize-returning-true-for-both-isauthenticated-and-isanonymous-in-thy by cc-by-sa and MIT license