java Spring Boot 中 Spring Security 的 XML 配置

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/26332051/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-11-02 09:43:36  来源:igfitidea点击:

XML configuration of Spring Security in Spring Boot

javaspringspring-securityspring-boot

提问by zeal

I'd like to use XML based configuration to Spring Security. The first idea was to use SHA-256 or any other hashing function for user passwords. I could not find a nice way to solve this with plain java., so I started to configure things in xml. That was the point, when it started to get interesting.

我想对 Spring Security 使用基于 XML 的配置。第一个想法是对用户密码使用 SHA-256 或任何其他散列函数。我找不到用纯 java 解决这个问题的好方法,所以我开始在 xml 中配置东西。这就是重点,当它开始变得有趣时。

My configuration:

我的配置:

  • spring-boot 1.1.8.RELEASE
  • spring-boot-starter-* at 1.1.8
  • tomcat-embed-jasper:8.0.8
  • 弹簧引导 1.1.8.RELEASE
  • spring-boot-starter-* 在 1.1.8
  • tomcat-embed-jasper:8.0.8

spring-security.xml:

弹簧security.xml:

<beans:beans xmlns="http://www.springframework.org/schema/security"
             xmlns:beans="http://www.springframework.org/schema/beans"
             xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
             xmlns:jdbc="http://www.springframework.org/schema/jdbc"
             xsi:schemaLocation="http://www.springframework.org/schema/beans
           http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
           http://www.springframework.org/schema/security
           http://www.springframework.org/schema/security/spring-security.xsd>

    <http pattern="/css/**" security="none"/>
    <http pattern="/login.html*" security="none"/>

    <http>
        <intercept-url pattern="/**" access="ROLE_USER" />
        <form-login login-page='/login.html'/>
    </http>

    <authentication-manager>

        <authentication-provider>
            <user-service>
                <user name="admin" password="admin"
                      authorities="ROLE_USER, ROLE_ADMIN"/>
                <user name="bob" password="bob"
                      authorities="ROLE_USER"/>
            </user-service>
        </authentication-provider>
    </authentication-manager>

</beans:beans>

I load the xml file in the class, where the public static void maincan be found:

我在类中加载 xml 文件,public static void main可以在其中找到:

@Configuration
@ComponentScan
@EnableAutoConfiguration
@Order(HIGHEST_PRECEDENCE)
@ImportResource({
        "/spring-security.xml"
})
public class PhrobeBootApplication extends SpringBootServletInitializer {
...
}

But I get the following exception on any pageload:

但是我在任何页面加载时都会收到以下异常:

[ERROR] org.apache.catalina.core.ContainerBase.[Tomcat].[localhost].[/].[dispatcherServlet] - Servlet.service() for servlet [dispatcherServlet] in context with path [] threw exception
org.springframework.security.authentication.AuthenticationCredentialsNotFoundException: An Authentication object was not found in the SecurityContext 
...

So it seems like the configuration from resources/WEB-INF/web.xmldoesn't load, if I have a good understanding from the documentation,I should use it when using just plain spring, without the boot. (the filters should be configured). Am I right?

所以似乎resources/WEB-INF/web.xml没有加载配置,如果我对文档有很好的理解,我应该在只使用普通弹簧时使用它,没有引导。(应配置过滤器)。我对吗?

Why is this error happens? Is there a better way to use xml based configuration for spring-security in spring-boot? Does web.xml even load by tomcat?

为什么会发生这个错误?有没有更好的方法可以在 spring-boot 中使用基于 xml 的 spring-security 配置?web.xml 是否甚至被 tomcat 加载?

采纳答案by zeal

According to the statement by Dave Syerin the recent version of spring boot the best way to configure the spring security is with Java configuration.

根据Dave Syer在最新版本的 spring boot 中的声明,配置 spring 安全性的最佳方法是使用 Java 配置。

I needed an SHA-256 encoder, but I haven't find any simple and good solution for implementing one. You just need to configure the jdbcAuthentication with the passwordEncoder. This is really really simple:

我需要一个 SHA-256 编码器,但我还没有找到任何简单而好的解决方案来实现它。您只需要使用 passwordEncoder 配置 jdbcAuthentication。这真的很简单:

@EnableWebSecurity
public class SpringSecurityConfigurer extends WebMvcConfigurerAdapter {

    @Override
    public void addViewControllers(ViewControllerRegistry registry) {
        registry.addViewController("/login").setViewName("login");
    }

    @Bean
    public ApplicationSecurity applicationSecurity() {
        return new ApplicationSecurity();
    }

    @Order(SecurityProperties.ACCESS_OVERRIDE_ORDER)
    protected static class ApplicationSecurity extends WebSecurityConfigurerAdapter {

        @Autowired
        private SecurityProperties security;

        @Autowired
        private DataSource dataSource;

        @Override
        protected void configure(HttpSecurity http) throws Exception {
            http.authorizeRequests().antMatchers("/css/**").permitAll().anyRequest().fullyAuthenticated()
                    .and().formLogin().loginPage("/login").failureUrl("/login?error").permitAll()
                    .and().logout().logoutRequestMatcher(new AntPathRequestMatcher("/logout")).logoutSuccessUrl("/login");
        }

        PasswordEncoder sha256PasswordEncoder = new PasswordEncoder() {
            @Override
            public String encode(CharSequence rawPassword) {
                return Hashing.sha256().hashString(rawPassword, Charsets.UTF_8).toString();
            }

            @Override
            public boolean matches(CharSequence rawPassword, String encodedPassword) {
                return encodedPassword.equals(Hashing.sha256().hashString(rawPassword, Charsets.UTF_8).toString());
            }
        };

        @Override
        public void configure(AuthenticationManagerBuilder auth) throws Exception {
            auth.jdbcAuthentication()
                    .dataSource(this.dataSource)
                    .passwordEncoder(sha256PasswordEncoder);
        }

    }

}

回答by Sum

I was getting the same issue then I changed the path of XML file and kept it as in src/main/resources/spring. It's working fine.

我遇到了同样的问题,然后我更改了 XML 文件的路径并将其保留为src/main/resources/spring. 它工作正常。

@SpringBootApplication

@ImportResource("classpath:/spring/spring-security.xml")

回答by Dave Syer

I haven't tried this (because there really isn't anything you can't do with Java configuration), but you would have to eliminate the Spring Boot-provided WebSecurityConfigurers(and @EnableWebSecurity). I think to do that is maybe more complicated than it needs to be (but then again no-one needs to use XML). You would have to exclude SecurityAutoConfigurationin your @EnableAutoConfigurationand then deal with problems as they arise (you might need a bean of type SecurityPropertiesstill for example, and you probably can't use the Actuator without some more messing about).

我还没有尝试过这个(因为真的没有什么是你不能用 Java 配置做的),但是你必须消除 Spring Boot 提供的WebSecurityConfigurers(和@EnableWebSecurity)。我认为这样做可能比它需要的更复杂(但是再次没有人需要使用 XML)。您将不得不排除SecurityAutoConfiguration在您的@EnableAutoConfiguration问题中,然后在出现问题时进行处理(SecurityProperties例如,您可能仍然需要一个类型为bean 的 bean ,并且您可能无法使用 Actuator 而不进行更多的处理)。

I'm not sure what you mean about "configuration from resources/WEB-INF/web.xml" since a) it's a Spring Boot app and b) even if it wasn't there wouldn't be a resources/WEB-INF/web.xml.

我不确定“配置来自resources/WEB-INF/web.xml”是什么意思,因为 a)它是一个 Spring Boot 应用程序,b)即使不是,也不会有resources/WEB-INF/web.xml.