spring安全webjars在子页面上不起作用

bvjveswy  于 2021-09-30  发布在  Java
关注(0)|答案(1)|浏览(286)

很抱歉问了这么一个愚蠢的问题,但经过两个小时的努力,我终于放弃了。链接到github
bootstrap在http“/”上可以完美地工作,但在子页面“/item/show”上却不能。我有注销输出 Authorized public object filter invocation [GET /item/webjars/bootstrap/5.0.1/js/bootstrap.js] 我想应该是这样 [GET webjars/bootstrap/5.0.1/js/bootstrap.js] 但我不知道如何正确设置它。

@Slf4j
@RequiredArgsConstructor
@Component
public class defaultLoader implements CommandLineRunner {

    private final PasswordEncoder passwordEncoder;
    private final AuthorityRepository authorityRepository;
    private final RoleRepository roleRepository;
    private final UserRepository userRepository;

    @Override

    public void run(String... args) throws Exception {
        loadAccount();
    }

    private void loadAccount() {
        var storeItemCreate = authorityRepository.save(Authority.builder().permission("store.item.create").build());
        var storeItemRead = authorityRepository.save(Authority.builder().permission("store.item.read").build());
        var storeItemUpdate = authorityRepository.save(Authority.builder().permission("store.item.update").build());
        var storeItemDelete = authorityRepository.save(Authority.builder().permission("store.item.delete").build());

        var admin = roleRepository.save(Role.builder().
                authority(storeItemCreate).
                authority(storeItemRead).
                authority(storeItemUpdate).
                authority(storeItemDelete).
                name("ADMIN").build());
        var customer = roleRepository.save(Role.builder().
            authority(storeItemRead).
            name("CUSTOMER").
            build());

        userRepository.save(User.builder().
                role(admin).
                username("admin").
                password(passwordEncoder.encode("admin")).
                email("admin@admin.com").
                build()
        );

        userRepository.save(User.builder().
                role(customer).
                username("user").
                password(passwordEncoder.encode("user")).
                email("user@user.com").
                build()
        );

    }

}
@Configuration
@EnableWebSecurity
@RequiredArgsConstructor
@EnableGlobalMethodSecurity(prePostEnabled = true)
public class SecurityConfigurer extends WebSecurityConfigurerAdapter {

    private final UserRepository userRepository;
    private final UserDetailsService userDetailsService;

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

    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {

        //H2 in mem settings
        http.authorizeRequests(authorize -> {
            authorize
                    .antMatchers("/h2-console/**").permitAll() //do not use in production!
                    .antMatchers("/", "/login", "/resources/**").permitAll()
                    .antMatchers("/css/**", "/js/**", "/webjars/**","**/webjars/**").permitAll();
        }).
                httpBasic().
                and().csrf().ignoringAntMatchers("/h2-console/**")
                .and().headers().frameOptions().sameOrigin().and();

        //Loggin
        http.formLogin(configurer ->{
            configurer
                    .loginProcessingUrl("/login")
                    .loginPage("/login").permitAll()
                    .successForwardUrl("/")
                    .defaultSuccessUrl("/")
                    .failureUrl("/login/?error");
        } ).
        logout(configurer ->{
            configurer.
                    logoutRequestMatcher(new AntPathRequestMatcher("/logout","GET")).
            logoutSuccessUrl("/").
            permitAll();
        } );
    }

    @Override
    public void configure(WebSecurity web) throws Exception {
        super.configure(web);
        web.
        ignoring().
        antMatchers("/resources/**", "/static/**","/webjars/**");
    }

    @Bean
    PasswordEncoder passwordEncoder() {
        return new BCryptPasswordEncoder();
    }

    @Bean
    UserDetailsService AppUserDetailsService() {
        return new UserDetailsService() {
            @Override
            public UserDetails loadUserByUsername(String s) throws UsernameNotFoundException {
                return userRepository.findByUsername(s).orElseThrow(() -> new UsernameNotFoundException("User : " + s + " not found"));
            }
        };
    }

}
package orchowski.tomasz.ecommercedemo.controller.item;

import orchowski.tomasz.ecommercedemo.security.permision.PermissionStoreItemCreate;
import orchowski.tomasz.ecommercedemo.security.permision.PermissionStoreItemRead;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;

@Controller
@RequestMapping("/item")
public class itemController {

    @PermissionStoreItemCreate
    @GetMapping("/create")
    public String itemAddController() {

        return "item/create";
    }

    @PermissionStoreItemRead
    @GetMapping("/show")
    public String itemRead(Model model) {

        return "item/show";
    }
}
@Retention(RetentionPolicy.RUNTIME)
@PreAuthorize("hasAuthority('store.item.read')")
public @interface PermissionStoreItemRead {
}

这是我对“/item/show”有问题的模板页面

<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org"
      xmlns:sec="http://www.thymeleaf.org/extras/spring-security">
<head>
    <meta charset="UTF-8">
    <title>store</title>
    <link th:rel="stylesheet" th:href="@{webjars/bootstrap/5.0.1/css/bootstrap.min.css}">

</head>
<body>

<div class="container">
    <div class="row">
        <div class="col-sm-12">
            <nav th:replace="fragments/navbar :: nav"></nav>
        </div>
    </div>

    <div class="alert alert-warning" role="alert">Tudududu</div>
    <h1>Lista</h1>
</div>

<script th:src="@{webjars/jquery/3.0.0/jquery.min.js}"></script>
<script th:src="@{webjars/popper.js/2.9.2/umd/popper.js}"></script>
<script th:src="@{webjars/bootstrap/5.0.1/js/bootstrap.js}"></script>
</body>
</html>
zpqajqem

zpqajqem1#

问题出在thymeleaf'item/show.html'中正确的模板是

<!DOCTYPE html>
    <html lang="en" xmlns:th="http://www.thymeleaf.org"
          xmlns:sec="http://www.thymeleaf.org/extras/spring-security">
    <head>
        <meta charset="UTF-8">
        <title>store</title>
        <link th:rel="stylesheet" th:href="@{/webjars/bootstrap/5.0.1/css/bootstrap.min.css}">

    </head>
    <body>

    <div class="container">
        <div class="row">
            <div class="col-sm-12">
                <nav th:replace="fragments/navbar :: nav"></nav>
            </div>
        </div>

        <div class="alert alert-warning" role="alert">Tudududu</div>
        <h1>Lista</h1>
    </div>

    <script th:src="@{/webjars/jquery/3.0.0/jquery.min.js}"></script>
    <script th:src="@{/webjars/popper.js/2.9.2/umd/popper.js}"></script>
    <script th:src="@{/webjars/bootstrap/5.0.1/js/bootstrap.js}"></script>
    </body>
    </html>

相关问题