Spring社交Twitter HTTP状态405 - 请求方法' POST'不支持

时间:2016-11-23 19:56:15

标签: spring spring-mvc spring-security spring-social-twitter

朋友我正在使用 Spring Mvc 4.2.5 Spring Security 4.0.4 Spring Social 1.1.2 twitter api 。一切正常connectcontroller处理获取/connect/twitter/connect。但是当我发送来自 twitterConnect.jsp 的帖子请求时,它给出了405错误

这是我的 SocialConfiguration 代码

@Configuration
@EnableSocial
@PropertySource(value = { "classpath:twitter.properties" })
public class SpringSocialConfig implements SocialConfigurer {
    static final Logger logger = Logger.getLogger(SpringSocialConfig.class);
@Autowired
private DataSource dataSource;

//
// SocialConfigurer implementation methods
//


@Override
public void addConnectionFactories(ConnectionFactoryConfigurer cfConfig, Environment env) {
    logger.info("at addconnectionFactory adding consumerkey");
    System.out.println("at add Connection FActory");
    cfConfig.addConnectionFactory(new TwitterConnectionFactory(env.getProperty("twitter.consumerKey"), env.getProperty("twitter.consumerSecret")));
}


@Override
public UsersConnectionRepository getUsersConnectionRepository(ConnectionFactoryLocator connectionFactoryLocator) {
    logger.info("crateing jdbcuserconnection repository");
    return new JdbcUsersConnectionRepository(dataSource, connectionFactoryLocator, Encryptors.noOpText());
}


// API Binding Beans
//


@Bean
@Scope(value="request", proxyMode=ScopedProxyMode.INTERFACES)
public Twitter twitter(ConnectionRepository repository) {
    Connection<Twitter> connection = repository.findPrimaryConnection(Twitter.class);
    logger.info("crateing connection Twitter");
    return connection != null ? connection.getApi() : null;
}



//
// Web Controller and Filter Beans
//
@Bean
public ConnectController connectController(ConnectionFactoryLocator connectionFactoryLocator, ConnectionRepository connectionRepository) {
    ConnectController connectController = new ConnectController(connectionFactoryLocator, connectionRepository);
    logger.info("At connect Controller");
    System.out.println("hi iam running");
    return connectController;
}

@Bean
public ReconnectFilter apiExceptionHandler(UsersConnectionRepository usersConnectionRepository, UserIdSource userIdSource) {
    return new ReconnectFilter(usersConnectionRepository, userIdSource);
}


@Override
public UserIdSource getUserIdSource() {
    return new UserIdSource() {         
        @Override
        public String getUserId() {
            Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
            if (authentication == null) {
                throw new IllegalStateException("Unable to get a ConnectionRepository: no user signed in");
            }
            return authentication.getName();
        }
    };
}
}

这是我的 SecurityConfiguration

@Configuration
@EnableWebSecurity
public class SecurityConfiguration extends WebSecurityConfigurerAdapter {

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

    @Autowired
    PersistentTokenRepository tokenRepository;


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

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.authorizeRequests()
        .antMatchers("/", "/home").permitAll()
        .antMatchers("/signup/**").anonymous()
        .antMatchers("/dashboard/**","/add_t_accounts/**").access("hasRole('USER')")
        .and().formLogin().loginPage("/login").loginProcessingUrl("/login").defaultSuccessUrl("/dashboard")
        .usernameParameter("userName").passwordParameter("password").and()
        .rememberMe().rememberMeParameter("remember-me").tokenRepository(tokenRepository)
        .tokenValiditySeconds(86400).and().csrf()
        .and().exceptionHandling().accessDeniedPage("/Access_Denied");
    }

    @Bean
    public PasswordEncoder passwordEncoder() {
        return new BCryptPasswordEncoder();
    }

    @Bean
    public TextEncryptor textEncryptor() {
        return Encryptors.noOpText();
}


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

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

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

    @Bean(name="authenticationManager")
    @Override
    public AuthenticationManager authenticationManagerBean() throws Exception {
        return super.authenticationManagerBean();
    }

}

我在控制台上得到这个

enter code hereo
  INFO : org.springframework.web.context.ContextLoader - Root WebApplicationContext: initialization started
    INFO : org.springframework.web.context.support.AnnotationConfigWebApplicationContext - Refreshing Root WebApplicationContext: startup date [Thu Nov 24 05:04:03 IST 2016]; root of context hierarchy
    INFO : org.springframework.web.context.support.AnnotationConfigWebApplicationContext - Registering annotated classes: [class org.springframework.social.showcase.config.MainConfig,class org.springframework.social.showcase.config.WebMvcConfig,class org.springframework.social.showcase.config.SecurityConfig,class org.springframework.social.showcase.config.SocialConfig]
    WARN : org.springframework.context.annotation.ConfigurationClassEnhancer - @Bean method MainConfig.propertyPlaceHolderConfigurer is non-static and returns an object assignable to Spring's BeanFactoryPostProcessor interface. This will result in a failure to process annotations such as @Autowired, @Resource and @PostConstruct within the method's declaring @Configuration class. Add the 'static' modifier to this method to avoid these container lifecycle issues; see @Bean javadoc for complete details
    INFO : org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor - JSR-330 'javax.inject.Inject' annotation found and supported for autowiring
    INFO : org.springframework.web.servlet.mvc.method.annotation.ExceptionHandlerExceptionResolver - Detected @ExceptionHandler methods in exceptionHandlingControllerAdvice
    INFO : org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter - Looking for @ControllerAdvice: Root WebApplicationContext: startup date [Thu Nov 24 05:04:03 IST 2016]; root of context hierarchy
    INFO : org.springframework.web.servlet.handler.SimpleUrlHandlerMapping - Mapped URL path [/resources/**] onto handler of type [class org.springframework.web.servlet.resource.ResourceHttpRequestHandler]
    INFO : org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping - Mapped "{[/],methods=[],params=[],headers=[],consumes=[],produces=[],custom=[]}" onto public java.lang.String org.springframework.social.showcase.HomeController.home(java.security.Principal,org.springframework.ui.Model)
    INFO : org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping - Mapped "{[/signin],methods=[GET],params=[],headers=[],consumes=[],produces=[],custom=[]}" onto public void org.springframework.social.showcase.signin.SigninController.signin()
    INFO : org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping - Mapped "{[/signup],methods=[GET],params=[],headers=[],consumes=[],produces=[],custom=[]}" onto public org.springframework.social.showcase.signup.SignupForm org.springframework.social.showcase.signup.SignupController.signupForm(org.springframework.web.context.request.WebRequest)
    INFO : org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping - Mapped "{[/signup],methods=[POST],params=[],headers=[],consumes=[],produces=[],custom=[]}" onto public java.lang.String org.springframework.social.showcase.signup.SignupController.signup(org.springframework.social.showcase.signup.SignupForm,org.springframework.validation.BindingResult,org.springframework.web.context.request.WebRequest)
    INFO : org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping - Mapped "{[/twitter/friends],methods=[GET],params=[],headers=[],consumes=[],produces=[],custom=[]}" onto public java.lang.String org.springframework.social.showcase.twitter.TwitterFriendsController.friends(org.springframework.ui.Model)
    INFO : org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping - Mapped "{[/twitter/followers],methods=[GET],params=[],headers=[],consumes=[],produces=[],custom=[]}" onto public java.lang.String org.springframework.social.showcase.twitter.TwitterFriendsController.followers(org.springframework.ui.Model)
    INFO : org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping - Mapped "{[/twitter/messages],methods=[POST],params=[],headers=[],consumes=[],produces=[],custom=[]}" onto public java.lang.String org.springframework.social.showcase.twitter.TwitterMessageController.sent(org.springframework.social.showcase.twitter.MessageForm)
    INFO : org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping - Mapped "{[/twitter/messages/sent],methods=[GET],params=[],headers=[],consumes=[],produces=[],custom=[]}" onto public java.lang.String org.springframework.social.showcase.twitter.TwitterMessageController.sent(org.springframework.ui.Model)
    INFO : org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping - Mapped "{[/twitter/messages],methods=[GET],params=[],headers=[],consumes=[],produces=[],custom=[]}" onto public java.lang.String org.springframework.social.showcase.twitter.TwitterMessageController.inbox(org.springframework.ui.Model)
    INFO : org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping - Mapped "{[/twitter],methods=[GET],params=[],headers=[],consumes=[],produces=[],custom=[]}" onto public java.lang.String org.springframework.social.showcase.twitter.TwitterProfileController.home(java.security.Principal,org.springframework.ui.Model)
    INFO : org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping - Mapped "{[/twitter/revoked],methods=[],params=[],headers=[],consumes=[],produces=[],custom=[]}" onto public void org.springframework.social.showcase.twitter.TwitterRevokedToken.simulateExpiredToken()
    INFO : org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping - Mapped "{[/twitter/search],methods=[GET],params=[],headers=[],consumes=[],produces=[],custom=[]}" onto public java.lang.String org.springframework.social.showcase.twitter.TwitterSearchController.showTrends(java.lang.String,org.springframework.ui.Model)
    INFO : org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping - Mapped "{[/twitter/timeline/{timelineType}],methods=[GET],params=[],headers=[],consumes=[],produces=[],custom=[]}" onto public java.lang.String org.springframework.social.showcase.twitter.TwitterTimelineController.showTimeline(java.lang.String,org.springframework.ui.Model)
    INFO : org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping - Mapped "{[/twitter/timeline],methods=[GET],params=[],headers=[],consumes=[],produces=[],custom=[]}" onto public java.lang.String org.springframework.social.showcase.twitter.TwitterTimelineController.showTimeline(org.springframework.ui.Model)
    INFO : org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping - Mapped "{[/twitter/tweet],methods=[POST],params=[],headers=[],consumes=[],produces=[],custom=[]}" onto public java.lang.String org.springframework.social.showcase.twitter.TwitterTimelineController.postTweet(java.lang.String)
    INFO : org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping - Mapped "{[/twitter/trends],methods=[GET],params=[],headers=[],consumes=[],produces=[],custom=[]}" onto public java.lang.String org.springframework.social.showcase.twitter.TwitterTrendsController.showTrends(org.springframework.ui.Model)
    INFO : org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping - Mapped "{[/signin/{providerId}],methods=[POST],params=[],headers=[],consumes=[],produces=[],custom=[]}" onto public org.springframework.web.servlet.view.RedirectView org.springframework.social.connect.web.ProviderSignInController.signIn(java.lang.String,org.springframework.web.context.request.NativeWebRequest)
    INFO : org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping - Mapped "{[/signin/{providerId}],methods=[GET],params=[oauth_token],headers=[],consumes=[],produces=[],custom=[]}" onto public org.springframework.web.servlet.view.RedirectView org.springframework.social.connect.web.ProviderSignInController.oauth1Callback(java.lang.String,org.springframework.web.context.request.NativeWebRequest)
    INFO : org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping - Mapped "{[/signin/{providerId}],methods=[GET],params=[error],headers=[],consumes=[],produces=[],custom=[]}" onto public org.springframework.web.servlet.view.RedirectView org.springframework.social.connect.web.ProviderSignInController.oauth2ErrorCallback(java.lang.String,java.lang.String,java.lang.String,java.lang.String,org.springframework.web.context.request.NativeWebRequest)
    INFO : org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping - Mapped "{[/signin/{providerId}],methods=[GET],params=[code],headers=[],consumes=[],produces=[],custom=[]}" onto public org.springframework.web.servlet.view.RedirectView org.springframework.social.connect.web.ProviderSignInController.oauth2Callback(java.lang.String,java.lang.String,org.springframework.web.context.request.NativeWebRequest)
    INFO : org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping - Mapped "{[/signin/{providerId}],methods=[GET],params=[],headers=[],consumes=[],produces=[],custom=[]}" onto public org.springframework.web.servlet.view.RedirectView org.springframework.social.connect.web.ProviderSignInController.canceledAuthorizationCallback()
    INFO : org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping - Mapped "{[/connect/{providerId}],methods=[POST],params=[],headers=[],consumes=[],produces=[],custom=[]}" onto public org.springframework.web.servlet.view.RedirectView org.springframework.social.connect.web.ConnectController.connect(java.lang.String,org.springframework.web.context.request.NativeWebRequest)
    INFO : org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping - Mapped "{[/connect/{providerId}],methods=[GET],params=[oauth_token],headers=[],consumes=[],produces=[],custom=[]}" onto public org.springframework.web.servlet.view.RedirectView org.springframework.social.connect.web.ConnectController.oauth1Callback(java.lang.String,org.springframework.web.context.request.NativeWebRequest)
    INFO : org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping - Mapped "{[/connect/{providerId}],methods=[GET],params=[error],headers=[],consumes=[],produces=[],custom=[]}" onto public org.springframework.web.servlet.view.RedirectView org.springframework.social.connect.web.ConnectController.oauth2ErrorCallback(java.lang.String,java.lang.String,java.lang.String,java.lang.String,org.springframework.web.context.request.NativeWebRequest)
    INFO : org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping - Mapped "{[/connect],methods=[GET],params=[],headers=[],consumes=[],produces=[],custom=[]}" onto public java.lang.String org.springframework.social.connect.web.ConnectController.connectionStatus(org.springframework.web.context.request.NativeWebRequest,org.springframework.ui.Model)
    INFO : org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping - Mapped "{[/connect/{providerId}],methods=[GET],params=[],headers=[],consumes=[],produces=[],custom=[]}" onto public java.lang.String org.springframework.social.connect.web.ConnectController.connectionStatus(java.lang.String,org.springframework.web.context.request.NativeWebRequest,org.springframework.ui.Model)
    INFO : org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping - Mapped "{[/connect/{providerId}],methods=[GET],params=[code],headers=[],consumes=[],produces=[],custom=[]}" onto public org.springframework.web.servlet.view.RedirectView org.springframework.social.connect.web.ConnectController.oauth2Callback(java.lang.String,org.springframework.web.context.request.NativeWebRequest)
    INFO : org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping - Mapped "{[/connect/{providerId}/{providerUserId}],methods=[DELETE],params=[],headers=[],consumes=[],produces=[],custom=[]}" onto public org.springframework.web.servlet.view.RedirectView org.springframework.social.connect.web.ConnectController.removeConnection(java.lang.String,java.lang.String,org.springframework.web.context.request.NativeWebRequest)
    INFO : org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping - Mapped "{[/connect/{providerId}],methods=[DELETE],params=[],headers=[],consumes=[],produces=[],custom=[]}" onto public org.springframework.web.servlet.view.RedirectView org.springframework.social.connect.web.ConnectController.removeConnections(java.lang.String,org.springframework.web.context.request.NativeWebRequest)
    INFO : org.springframework.security.web.DefaultSecurityFilterChain - Creating filter chain: Ant [pattern='/resources/**'], []
    INFO : org.springframework.security.web.DefaultSecurityFilterChain - Creating filter chain: org.springframework.security.web.util.matcher.AnyRequestMatcher@1, [org.springframework.security.web.context.request.async.WebAsyncManagerIntegrationFilter@70012279, org.springframework.security.web.context.SecurityContextPersistenceFilter@69061fc0, org.springframework.security.web.header.HeaderWriterFilter@12139505, org.springframework.security.web.csrf.CsrfFilter@5a005b47, org.springframework.security.web.authentication.logout.LogoutFilter@3170938b, org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter@4946d531, org.springframework.security.web.savedrequest.RequestCacheAwareFilter@5a45ee51, org.springframework.security.web.servletapi.SecurityContextHolderAwareRequestFilter@27698887, org.springframework.security.web.authentication.rememberme.RememberMeAuthenticationFilter@61a3002, org.springframework.security.web.authentication.AnonymousAuthenticationFilter@5a7e6f61, org.springframework.security.web.session.SessionManagementFilter@58c11f65, org.springframework.security.web.access.ExceptionTranslationFilter@18b43f5, org.springframework.security.web.access.intercept.FilterSecurityInterceptor@4986e68]
    INFO : org.springframework.web.context.ContextLoader - Root WebApplicationContext: initialization completed in 4999 ms
    Nov 24, 2016 5:04:08 AM org.apache.catalina.core.ApplicationContext log
    INFO: Initializing Spring FrameworkServlet 'dispatcher'
    INFO : org.springframework.web.servlet.DispatcherServlet - FrameworkServlet 'dispatcher': initialization started
    INFO : org.springframework.web.context.support.AnnotationConfigWebApplicationContext - Refreshing WebApplicationContext for namespace 'dispatcher-servlet': startup date [Thu Nov 24 05:04:08 IST 2016]; parent: Root WebApplicationContext
    INFO : org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor - JSR-330 'javax.inject.Inject' annotation found and supported for autowiring
    INFO : org.springframework.web.servlet.DispatcherServlet - FrameworkServlet 'dispatcher': initialization completed in 212 ms
    Nov 24, 2016 5:04:08 AM org.apache.coyote.AbstractProtocol start
    INFO: Starting ProtocolHandler ["http-nio-8090"]
    Nov 24, 2016 5:04:08 AM org.apache.coyote.AbstractProtocol start
    INFO: Starting ProtocolHandler ["ajp-nio-8099"]
    Nov 24, 2016 5:04:08 AM org.apache.catalina.startup.Catalina start
    INFO: Server startup in 23694 ms

1 个答案:

答案 0 :(得分:0)

我遇到了和你一样的问题。现在,我找到了原因。您在spring安全配置中包含csrf令牌控件。这就是为什么你需要在connectTwitter视图文件中添加csrf标记作为输入。