当前位置: 首页 > 知识库问答 >
问题:

使用spring启动的安全配置

谢骏奇
2023-03-14

我为spring-boot创建了一个spring安全配置类。我的登录页面有资源css、js和ico文件。这些资源由于安全原因而被拒绝,并且每次都被重定向到登录页面。为什么EnableWebMVCSecurity不添加类路径资源位置。在更改代码后,如第二个代码片段所示,将添加I Classpath资源位置。不明白第一段代码中的资源缺少什么。


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

我通过将代码更改为


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

        }
    }   
}

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

[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]

共有2个答案

邹德泽
2023-03-14

创建扩展WebSecurityConfigurerAdapter的配置文件,并使用@EnableWebSecurity注释该类

您可以重写configure(HttpSecurity http)等方法,以添加如下所示的基本安全性

@Configuration
@EnableWebSecurity
public class AppWebSecurityConfigurer extends WebSecurityConfigurerAdapter {
    @Override
    protected void configure(HttpSecurity http) throws Exception {    
        http
            .csrf().disable()
            .authorizeRequests()
                .anyRequest().permitAll();
        }
}
江浩慨
2023-03-14

对于第一个示例中的文档,您使用@enablewebsecurity禁用了spring boot自动配置,因此您必须手动显式忽略所有静态资源。在第二个示例中,您只需提供一个WebSecurityConfigureer,它是默认AutoConfig之上的附加功能

 类似资料:
  • 我正在使用Spring引导安全层来验证和授权user.Now,我想使用多超文本传输协议安全配置做一些示例应用程序。我有这样的场景,比如将有两个具有不同URL映射的登录页面(“/Management ementLogin”、“/thersLogin”)。 我可以理解如何配置多httpSecurity配置,但我需要验证用户从两个tables.If管理用户登录我需要验证用户从管理表通过DAO层使用否则,

  • 我的spring boot应用程序有一个application类。当我(作为应用程序)运行它时,它会在嵌入式servlet容器(在我的例子中是Tomcat)中启动自己。以某种方式(我想是通过应用程序的@Annotations),加载了同一包中的WebSecurityConfig(扩展WebSecurityConfigurerAdapter)。 WebSecurityConfig包含两个重要的配置信

  • 然后我添加了一个SecurityConfig。从那时起,CorsFilter停止工作,我在angular应用程序中得到了一个异常: CORS策略阻止了从origin“http://localhost:8080/users/999/folders/%2f/media/”从“http://localhost:4200”访问“http://localhost:8080/users/999/folders

  • 我正在尝试使用新的基于组件的(没有WebSecurityConfigurerAdapter)配置,并按如下方式设置我的安全配置: 安全配置.java文件 但是当我运行应用程序并尝试记录用户时,即使我在安全配置中将BCryptPassword编码器作为bean,也会出现以下错误: 错误堆栈跟踪* 在新组件配置中设置PasswordEncoder的正确方法是什么? 编辑:添加登录逻辑 AppUserS

  • 2020-05-09 17:28:38.521信息21308---[restartedMain]O.A.C.C.C.[Tomcat].[localhost].[/]:初始化Spring embedded WebApplicationContext 2020-05-09 17:28:38.527信息21308--[restartedMain]O.s.Web.context.ContextLoader

  • 我正在做一个测试项目,为我们未来的项目尝试SpringBoot。 我们正在使用jasig CAS,我正在尝试配置Spring Boot和嵌入式tomcat服务器。 所以我加入了pom。xml spring启动程序安全性 之后,我尝试配置WebSecurityConfig- 这里是第一个问题:类组织。springframework。安全中科院。网状物应用程序未重新确认CasAuthenticatio