使用 Spring-boot 进行安全配置 [英] Security configuration with Spring-boot

查看:32
本文介绍了使用 Spring-boot 进行安全配置的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我为 Spring-Boot 创建了一个 Spring Security 配置类.我的登录页面有资源 css、js 和 ico 文件.出于安全原因,资源被拒绝并每次都重定向到登录页面.为什么 EnableWebMVCSecurity 不添加 Classpath 资源位置.在更改第二个代码段中的代码后,添加了 I Classpath 资源位置.不明白我在第一个代码片段中缺少什么资源.

<代码>@配置/** 启用 Spring Security 的 Web 安全支持并提供 Spring MVC 集成* 它还扩展了 WebSecurityConfigurerAdapter 并覆盖了它的几个方法来设置网络安全配置的一些细节.*/@EnableWebMvcSecurity公共类 WebSecurityConfig 扩展了 WebSecurityConfigurerAdapter {/*** 用 URL 路径定义的 configure(HttpSecurity) 方法应该是* 安全,哪些不应该.*/@覆盖protected void configure(HttpSecurity http) 抛出异常 {http.authorizeRequests().anyRequest().authenticated();//有一个由loginPage()指定的自定义/login"页面,每个人//允许查看.http.formLogin().loginPage("/login.html").permitAll().和().登出().permitAll().logoutSuccessUrl("/login.html");}@配置受保护的静态类 AuthenticationConfiguration 扩展GlobalAuthenticationConfigurerAdapter {@覆盖public void init(AuthenticationManagerBuilder auth) 抛出异常 {//至于 configure(AuthenticationManagerBuilder) 方法,它设置//具有单个用户的内存用户存储.该用户被赋予//用户名user",密码password",角色USER".授权.inMemoryAuthentication().withUser("user@domain.com").password("password").roles("USER");}}

我把代码改成

<代码>@配置/** 启用 Spring Security 的 Web 安全支持并提供 Spring MVC 集成* 它还扩展了 WebSecurityConfigurerAdapter 并覆盖了它的几个方法来设置网络安全配置的一些细节.*/公共类 WebSecurityConfig{@豆角,扁豆公共应用安全应用安全(){返回新的应用程序安全();}@豆角,扁豆公共 AuthenticationSecurity authenticationSecurity() {返回新的 AuthenticationSecurity();}@Order(SecurityProperties.ACCESS_OVERRIDE_ORDER)受保护的静态类 ApplicationSecurity 扩展了 WebSecurityConfigurerAdapter {@覆盖protected void configure(HttpSecurity http) 抛出异常 {http.authorizeRequests().anyRequest().authenticated();http.formLogin().loginPage("/login.html").permitAll().和().登出().permitAll().logoutSuccessUrl("/login.html");}}@Order(Ordered.HIGHEST_PRECEDENCE + 10)受保护的静态类 AuthenticationSecurity 扩展GlobalAuthenticationConfigurerAdapter {@覆盖public void init(AuthenticationManagerBuilder auth) 抛出异常 {授权.inMemoryAuthentication().withUser("user@domain.com").password("password").roles("USER");}}}

更改代码后,我注意到忽略路径已添加到过滤器中,并且我在日志中看到以下内容:

<前>[ost-startStop-1] o.s.s.web.DefaultSecurityFilterChain : 创建过滤器链:Ant [pattern='/css/**'], [][ost-startStop-1] o.s.s.web.DefaultSecurityFilterChain : 创建过滤器链:Ant [pattern='/js/**'], [][ost-startStop-1] o.s.s.web.DefaultSecurityFilterChain : 创建过滤器链:Ant [pattern='/images/**'], [][ost-startStop-1] o.s.s.web.DefaultSecurityFilterChain : 创建过滤器链:Ant [pattern='/**/favicon.ico'], [][ost-startStop-1] ossweb.DefaultSecurityFilterChain:创建过滤器链:org.springframework.security.web.util.matcher.AnyRequestMatcher@1, [org.springframework.security.web.context.request.async.WebAsyncManagerIntegrationFilter@4e3e0069, org.springframework.security.web.context.SecurityContextPersistenceFilter@3d2dd0cf, org.springframework.security.web.header.HeaderWriterFilter@33fc3b02, org.springframework.security.web.csrf.CsrfFilter@9b7a3ac, org.springframework.security..authentication.logout.LogoutFilter@267237ef, org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter@129495ef, org.springframework.security.web.authentication.ui.DefaultLoginPageGeneratingFilter@7db0a467, org.springframework.thentication.web.authentication.UsernamePasswordAuthenticationFilter@129495ef.BasicAuthenticationFilter@764d1dbd, org.springframework.security.web.savedrequest.RequestCacheAwareFilter@25a5268d, org.springframework.security.web.servletapi.SecurityContextHolderAwareRequestFilter@15c01d0c, org.springframework.security.web.authentication.AnonymousAuthenticationFilter@37818a3b,org.springframework.security.web.session.SessionManagementFilter@3fe57e49,org.springframework.security.web.access.ExceptionTranslationFilter@4278af59,org.springframework.security.web.access.intercept.FilterSecurityInterceptor@424bef91]

解决方案

根据 docs 您在第一个示例中使用 @EnableWebSecurity 禁用了 spring boot 自动配置,因此您必须手动显式忽略所有静态资源.在第二个示例中,您只需提供一个 WebSecurityConfigurer,它是在默认自动配置之上添加的.

I created a Spring Security configuration class for Spring-Boot. My login page has resources css, js and ico files. The resources are getting denied for security reasons and redirected to login page each time. Why does EnableWebMVCSecurity not add the Classpath resource location. After changing the code as in the second snippet the I Classpath resource location is added. dont understand what I am missing for the resources in the first code snippet.


@Configuration

/*
 * Enable Spring Security’s web security support and provide the Spring MVC integration
 * It also extends WebSecurityConfigurerAdapter and overrides a couple of its methods to set some specifics of the web security configuration.
 */
@EnableWebMvcSecurity
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {

/**
 * The configure(HttpSecurity) method defines with URL paths should be 
     * secured and which should not. 
     */
    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http
        .authorizeRequests()
            .anyRequest().authenticated();

//      There is a custom "/login" page specified by loginPage(), and everyone 
//      is allowed to view it.      
        http
            .formLogin()
                .loginPage("/login.html")
                .permitAll()
                .and()
            .logout()
                .permitAll().logoutSuccessUrl("/login.html");
    }

    @Configuration
    protected static class AuthenticationConfiguration extends
            GlobalAuthenticationConfigurerAdapter {
        @Override
        public void init(AuthenticationManagerBuilder auth) throws Exception {
//          As for the configure(AuthenticationManagerBuilder) method, it sets up 
//          an in-memory user store with a single user. That user is given a 
//          username of "user", a password of "password", and a role of "USER".
            auth
                    .inMemoryAuthentication()
                    .withUser("user@domain.com").password("password").roles("USER");
        }
   }

I got this working by changing the code to


@Configuration
/*
 * Enable Spring Security’s web security support and provide the Spring MVC integration
 * It also extends WebSecurityConfigurerAdapter and overrides a couple of its methods to set some specifics of the web security configuration.
 */
public class WebSecurityConfig{

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

    @Bean
    public AuthenticationSecurity authenticationSecurity() {
        return new AuthenticationSecurity();
    }

    @Order(SecurityProperties.ACCESS_OVERRIDE_ORDER)
    protected static class ApplicationSecurity extends WebSecurityConfigurerAdapter {
        @Override
        protected void configure(HttpSecurity http) throws Exception {
            http
            .authorizeRequests()
                .anyRequest().authenticated();
            http
                .formLogin()
                    .loginPage("/login.html")
                    .permitAll()
                    .and()
                .logout()
                    .permitAll().logoutSuccessUrl("/login.html");

        }
    }

    @Order(Ordered.HIGHEST_PRECEDENCE + 10)
    protected static class AuthenticationSecurity extends
            GlobalAuthenticationConfigurerAdapter {
        @Override
        public void init(AuthenticationManagerBuilder auth) throws Exception {
            auth
            .inMemoryAuthentication()
            .withUser("user@domain.com").password("password").roles("USER");

        }
    }   
}

After changing the code I noticed that the Ignore paths were added to the filter and I see the following in logs:

[ost-startStop-1] o.s.s.web.DefaultSecurityFilterChain     : Creating filter chain: Ant [pattern='/css/**'], []
[ost-startStop-1] o.s.s.web.DefaultSecurityFilterChain     : Creating filter chain: Ant [pattern='/js/**'], []
[ost-startStop-1] o.s.s.web.DefaultSecurityFilterChain     : Creating filter chain: Ant [pattern='/images/**'], []
[ost-startStop-1] o.s.s.web.DefaultSecurityFilterChain     : Creating filter chain: Ant [pattern='/**/favicon.ico'], []
[ost-startStop-1] o.s.s.web.DefaultSecurityFilterChain     : Creating filter chain: org.springframework.security.web.util.matcher.AnyRequestMatcher@1, [org.springframework.security.web.context.request.async.WebAsyncManagerIntegrationFilter@4e3e0069, org.springframework.security.web.context.SecurityContextPersistenceFilter@3d2dd0cf, org.springframework.security.web.header.HeaderWriterFilter@33fc3b02, org.springframework.security.web.csrf.CsrfFilter@9b7a3ac, org.springframework.security.web.authentication.logout.LogoutFilter@267237ef, org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter@129495ef, org.springframework.security.web.authentication.ui.DefaultLoginPageGeneratingFilter@7db0a467, org.springframework.security.web.authentication.www.BasicAuthenticationFilter@764d1dbd, org.springframework.security.web.savedrequest.RequestCacheAwareFilter@25a5268d, org.springframework.security.web.servletapi.SecurityContextHolderAwareRequestFilter@15c01d0c, org.springframework.security.web.authentication.AnonymousAuthenticationFilter@37818a3b, org.springframework.security.web.session.SessionManagementFilter@3fe57e49, org.springframework.security.web.access.ExceptionTranslationFilter@4278af59, org.springframework.security.web.access.intercept.FilterSecurityInterceptor@424bef91]

解决方案

Per the docs you have disabled the spring boot autoconfig in the first example by using @EnableWebSecurity, so you would have to explicitly ignore all the static resources manually. In the second example you simply provide a WebSecurityConfigurer which is additive on top of the default autoconfig.

这篇关于使用 Spring-boot 进行安全配置的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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