java - Spring 安全 405

标签 java spring spring-mvc

我的 Spring 应用程序有以下配置:

@Configuration
@EnableWebSecurity
public class MultipleHttpSecurityConfig {

    @Autowired
    @Qualifier("customUserDetailsService")
    UserDetailsService userDetailsService;

    @Autowired
    public void configureGlobalSecurity(AuthenticationManagerBuilder auth) throws Exception {
        auth.userDetailsService(userDetailsService);
        auth.authenticationProvider(authenticationProvider());
    }

    @Bean
    public PlaintextPasswordEncoder passwordEncoder() {
        return new PlaintextPasswordEncoder();
    }

    @Bean
    public DaoAuthenticationProvider authenticationProvider() {
        DaoAuthenticationProvider authenticationProvider = new DaoAuthenticationProvider();
        authenticationProvider.setUserDetailsService(userDetailsService);
        authenticationProvider.setPasswordEncoder(passwordEncoder());
        return authenticationProvider;
    }

    @Bean
    public AuthenticationTrustResolver getAuthenticationTrustResolver() {
        return new AuthenticationTrustResolverImpl();
    }

    @Configuration
    @Order(1)
    public static class ApiWebSecurityConfigurationAdapter extends WebSecurityConfigurerAdapter {

        private static String REALM="MY_REALM";

        protected void configure(HttpSecurity http) throws Exception {

            http.csrf().disable()
            .authorizeRequests()
            .antMatchers("/api/**").access("hasRole('ADMIN') or hasRole('SUPERADMIN')")
            .and().httpBasic().realmName(REALM).authenticationEntryPoint(getBasicAuthEntryPoint())
            .and().sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS);
        }

        @Bean
        public CustomBasicAuthenticationEntryPoint getBasicAuthEntryPoint(){
            return new CustomBasicAuthenticationEntryPoint();
        }
    }

    @Configuration
    public static class FormLoginWebSecurityConfigurerAdapter extends WebSecurityConfigurerAdapter {

        @Autowired
        PersistentTokenRepository tokenRepository;

        @Autowired
        @Qualifier("customUserDetailsService")
        UserDetailsService userDetailsService;

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

        @Bean
        public PersistentTokenBasedRememberMeServices getPersistentTokenBasedRememberMeServices() {
            PersistentTokenBasedRememberMeServices tokenBasedservice = new PersistentTokenBasedRememberMeServices(
                    "remember-me", userDetailsService, tokenRepository);
            return tokenBasedservice;
        }

        @Override
        protected void configure(HttpSecurity http) throws Exception {
            http.authorizeRequests().antMatchers("/", "/index").access("hasRole('ADMIN') or hasRole('SUPERADMIN')")
                    .antMatchers("/categories", "/category/**").access("hasRole('ADMIN') or hasRole('SUPERADMIN')")
                    .antMatchers("/companies", "/company/**").access("hasRole('ADMIN') or hasRole('SUPERADMIN')")
                    .antMatchers("/locations", "/location/**").access("hasRole('ADMIN') or hasRole('SUPERADMIN')").and()
                    .formLogin().loginPage("/login").loginProcessingUrl("/login").usernameParameter("username")
                    .passwordParameter("password").and().rememberMe().rememberMeParameter("remember-me")
                    .tokenRepository(tokenRepository).tokenValiditySeconds(86400).and().csrf().and().exceptionHandling()
                    .accessDeniedPage("/Access_Denied");
        }
    }

}

在 api url 处,我得到了想要的结果。但在 Web 登录时,我收到 HTTP 状态 405 - 不支持请求方法“POST”。有什么想法吗?

Spring框架是:4.3.7.RELEASE Spring安全:4.2.2.RELEASE 调试是:

   2017-04-11 19:30:12 DEBUG AntPathRequestMatcher:157 - Checking match of request : '/login'; against '/resources/**'
2017-04-11 19:30:12 DEBUG FilterChainProxy:325 - /login at position 1 of 11 in additional filter chain; firing Filter: 'WebAsyncManagerIntegrationFilter'
2017-04-11 19:30:12 DEBUG FilterChainProxy:325 - /login at position 2 of 11 in additional filter chain; firing Filter: 'SecurityContextPersistenceFilter'
2017-04-11 19:30:12 DEBUG FilterChainProxy:325 - /login at position 3 of 11 in additional filter chain; firing Filter: 'HeaderWriterFilter'
2017-04-11 19:30:12 DEBUG HstsHeaderWriter:130 - Not injecting HSTS header since it did not match the requestMatcher org.springframework.security.web.header.writers.HstsHeaderWriter$SecureRequestMatch
er@9f37d03
2017-04-11 19:30:12 DEBUG FilterChainProxy:325 - /login at position 4 of 11 in additional filter chain; firing Filter: 'LogoutFilter'
2017-04-11 19:30:12 DEBUG OrRequestMatcher:65 - Trying to match using Ant [pattern='/logout', GET]
2017-04-11 19:30:12 DEBUG AntPathRequestMatcher:137 - Request 'POST /login' doesn't match 'GET /logout
2017-04-11 19:30:12 DEBUG OrRequestMatcher:65 - Trying to match using Ant [pattern='/logout', POST]
2017-04-11 19:30:12 DEBUG AntPathRequestMatcher:157 - Checking match of request : '/login'; against '/logout'
2017-04-11 19:30:12 DEBUG OrRequestMatcher:65 - Trying to match using Ant [pattern='/logout', PUT]
2017-04-11 19:30:12 DEBUG AntPathRequestMatcher:137 - Request 'POST /login' doesn't match 'PUT /logout
2017-04-11 19:30:12 DEBUG OrRequestMatcher:65 - Trying to match using Ant [pattern='/logout', DELETE]
2017-04-11 19:30:12 DEBUG AntPathRequestMatcher:137 - Request 'POST /login' doesn't match 'DELETE /logout
2017-04-11 19:30:12 DEBUG OrRequestMatcher:72 - No matches found
2017-04-11 19:30:12 DEBUG FilterChainProxy:325 - /login at position 5 of 11 in additional filter chain; firing Filter: 'BasicAuthenticationFilter'
2017-04-11 19:30:12 DEBUG FilterChainProxy:325 - /login at position 6 of 11 in additional filter chain; firing Filter: 'RequestCacheAwareFilter'
2017-04-11 19:30:12 DEBUG FilterChainProxy:325 - /login at position 7 of 11 in additional filter chain; firing Filter: 'SecurityContextHolderAwareRequestFilter'
2017-04-11 19:30:12 DEBUG FilterChainProxy:325 - /login at position 8 of 11 in additional filter chain; firing Filter: 'AnonymousAuthenticationFilter'
2017-04-11 19:30:12 DEBUG AnonymousAuthenticationFilter:100 - Populated SecurityContextHolder with anonymous token: 'org.springframework.security.authentication.AnonymousAuthenticationToken@6fa90ed4:
Principal: anonymousUser; Credentials: [PROTECTED]; Authenticated: true; Details: org.springframework.security.web.authentication.WebAuthenticationDetails@fffc7f0c: RemoteIpAddress: 127.0.0.1; Session
Id: B6EBB4A5A07FDC44D8E19748CE6D5E5E; Granted Authorities: ROLE_ANONYMOUS'
2017-04-11 19:30:12 DEBUG FilterChainProxy:325 - /login at position 9 of 11 in additional filter chain; firing Filter: 'SessionManagementFilter'
2017-04-11 19:30:12 DEBUG FilterChainProxy:325 - /login at position 10 of 11 in additional filter chain; firing Filter: 'ExceptionTranslationFilter'
2017-04-11 19:30:12 DEBUG FilterChainProxy:325 - /login at position 11 of 11 in additional filter chain; firing Filter: 'FilterSecurityInterceptor'
2017-04-11 19:30:12 DEBUG AntPathRequestMatcher:157 - Checking match of request : '/login'; against '/api/**'
2017-04-11 19:30:12 DEBUG FilterSecurityInterceptor:210 - Public object - authentication not attempted
2017-04-11 19:30:12 DEBUG FilterChainProxy:310 - /login reached end of additional filter chain; proceeding with original chain
2017-04-11 19:30:12 DEBUG DispatcherServlet:865 - DispatcherServlet with name 'dispatcher' processing POST request for [/HeliosCMS/login]
2017-04-11 19:30:12 DEBUG RequestMappingHandlerMapping:310 - Looking up handler method for path /login
2017-04-11 19:30:12 DEBUG ExceptionHandlerExceptionResolver:133 - Resolving exception from handler [null]: org.springframework.web.HttpRequestMethodNotSupportedException: Request method 'POST' not sup
ported
2017-04-11 19:30:12 DEBUG ResponseStatusExceptionResolver:133 - Resolving exception from handler [null]: org.springframework.web.HttpRequestMethodNotSupportedException: Request method 'POST' not suppo
rted
2017-04-11 19:30:12 DEBUG DefaultHandlerExceptionResolver:133 - Resolving exception from handler [null]: org.springframework.web.HttpRequestMethodNotSupportedException: Request method 'POST' not suppo
rted
2017-04-11 19:30:12 WARN  PageNotFound:215 - Request method 'POST' not supported
2017-04-11 19:30:12 DEBUG DispatcherServlet:1044 - Null ModelAndView returned to DispatcherServlet with name 'dispatcher': assuming HandlerAdapter completed request handling
2017-04-11 19:30:12 DEBUG DispatcherServlet:1000 - Successfully completed request
2017-04-11 19:30:12 DEBUG ExceptionTranslationFilter:116 - Chain processed normally
2017-04-11 19:30:12 DEBUG SecurityContextPersistenceFilter:119 - SecurityContextHolder now cleared, as request processing completed

最佳答案

也许这是一个映射问题,因为 /login 页面是由 API 处理程序处理的,因此 POST 永远不会到达登录 Controller 。

API 处理程序的映射是什么?它应该是 /api/* 而不是 //*

如果您将 AbstractDispatcherServletInitializer 子类化以配置 API 模块,则应该类似于:

       @Override
       protected String[] getServletMappings() {
        return new String[] { "/api/*" };
       }

如果这不是我认为的问题,阅读日志,找不到 /login 的处理程序,所以您应该调查映射。也许 API 映射足够严格,但 Web 映射不是 /。没有看到配置很难说。

您在 GET 中看到 /login 了吗?

关于java - Spring 安全 405,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43351705/

相关文章:

java - 在Spring集成中,如何在路由器 channel 中使用Util常量

java - spring mvc 防止直接访问方法

java - Spring Boot Controller 测试,空指针异常

java - Spring mvc 项目中的 org.springframework.beans.factory.CannotLoadBeanClassException

java - GAE 和多客户端应用程序

java URL在浏览器中有效,但在客户端程序中无效

Java Rx Observable 方法 switchIfEmpty

windows - 指定 Java WebStart 应用程序的 JRE 位置

java - 注入(inject)的 SolrTemplate 资源未连接到 HttpSolrServer

java - JBOSS 服务器 5.0.1.GA 上的部署问题