Spring Boot 中 Spring Security 的 XML 配置 [英] XML configuration of Spring Security in Spring Boot

查看:89
本文介绍了Spring Boot 中 Spring Security 的 XML 配置的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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-boot 1.1.8.RELEASE
  • spring-boot-starter-* 1.1.8
  • tomcat-embed-jasper:8.0.8

spring-security.xml:

spring-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>

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

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

@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 
...

所以看起来 resources/WEB-INF/web.xml 的配置没有加载,如果我有一个好的 从文档中理解,我应该在只使用普通弹簧时使用它,没有引导.(应配置过滤器).我说得对吗?

So it seems like the configuration from resources/WEB-INF/web.xml doesn'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?

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

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?

推荐答案

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

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

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

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:

@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);
        }

    }

}

这篇关于Spring Boot 中 Spring Security 的 XML 配置的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆