Spring引导 - 在请求参数'_csrf'或标题'X-CSRF-TOKEN'上找到无效的CSRF令牌'null'

时间:2017-10-05 05:44:18

标签: java spring spring-boot oauth-2.0

这是我的OAUTH2配置文件    包pmo.oauth;

import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.ServletContext;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.oauth2.common.DefaultOAuth2AccessToken;
import org.springframework.security.oauth2.common.OAuth2AccessToken;
import org.springframework.security.oauth2.config.annotation.configurers.ClientDetailsServiceConfigurer;
import org.springframework.security.oauth2.config.annotation.web.configuration.AuthorizationServerConfigurerAdapter;
import org.springframework.security.oauth2.config.annotation.web.configuration.EnableAuthorizationServer;
import org.springframework.security.oauth2.config.annotation.web.configuration.EnableResourceServer;
import org.springframework.security.oauth2.config.annotation.web.configuration.ResourceServerConfigurerAdapter;
import org.springframework.security.oauth2.config.annotation.web.configurers.AuthorizationServerEndpointsConfigurer;
import org.springframework.security.oauth2.config.annotation.web.configurers.ResourceServerSecurityConfigurer;
import org.springframework.security.oauth2.provider.OAuth2Authentication;
import org.springframework.security.oauth2.provider.token.DefaultTokenServices;
import org.springframework.security.oauth2.provider.token.TokenEnhancer;
import org.springframework.security.oauth2.provider.token.TokenStore;
import org.springframework.security.oauth2.provider.token.store.InMemoryTokenStore;

import pmo.messages.MessageConstants;
import pmo.service.CustomUserDetailsService;

@Configuration
public class OAuth2ServerConfiguration {



    private static final String RESOURCE_ID = "restservice";

    @Configuration
    @EnableResourceServer
    protected static class ResourceServerConfiguration extends
    ResourceServerConfigurerAdapter {

        @Override
        public void configure(ResourceServerSecurityConfigurer resources) {
            resources
            .resourceId(RESOURCE_ID);
        }

        @Override
        public void configure(HttpSecurity http) throws Exception {
            /*          http.sessionManagement()
            .sessionFixation()
            .newSession();

        http.csrf().disable();*/
            /*     http.sessionManagement()
                .sessionCreationPolicy(SessionCreationPolicy.IF_REQUIRED).maximumSessions(1);*/
            System.out.println(http.headers());
            http
            .csrf().disable()
            .authorizeRequests()
            /*to avoid Oauth authentication and authorization for api*/
            /*start*/
            .antMatchers("/login**","/register**","/forgotpassword**","/resetpassword**","/verifyuser**","/allcountry**","/validateverificationlink**").permitAll()
            /*End*/
            .anyRequest()
            .fullyAuthenticated();
        }
    }

    @Configuration
    @EnableAuthorizationServer
    public static class AuthorizationServerConfiguration extends AuthorizationServerConfigurerAdapter {

        @Autowired
        ServletContext ctx;

        private TokenStore tokenStore = new InMemoryTokenStore();

        @Autowired
        @Qualifier("authenticationManagerBean")
        private AuthenticationManager authenticationManager;

        @Autowired
        private CustomUserDetailsService userDetailsService;

        @Override
        public void configure(AuthorizationServerEndpointsConfigurer endPoints){
            endPoints
            .tokenStore(this.tokenStore)
            .authenticationManager(this.authenticationManager)
            .userDetailsService(userDetailsService)
            .tokenEnhancer(tokenEnhancer());
        }

        @Override
        public void configure(ClientDetailsServiceConfigurer clients) throws Exception {

            clients
            .inMemory()  
            .withClient(MessageConstants.OAUTHPMO)
            .authorizedGrantTypes("password","refresh_token")
            .authorities("USER")
            .scopes("read","write")
            .resourceIds(RESOURCE_ID)
            /*.secret(MessageConstants.OAUTHSOC).accessTokenValiditySeconds(15);*/
            .secret(MessageConstants.OAUTHPMO).accessTokenValiditySeconds(5000000);
            /*  clients.notifyAll();*/
        }

        @Bean
        /*      @Scope(value = "session")*/
        @Primary
        public DefaultTokenServices tokenServices() {
            DefaultTokenServices tokenServices = new DefaultTokenServices();
            tokenServices.setSupportRefreshToken(true);
            System.out.println("oauth");
            tokenServices.setTokenStore(this.tokenStore);
            tokenServices.setTokenEnhancer(tokenEnhancer());
            return tokenServices;
        }   



        @Bean
        public TokenEnhancer tokenEnhancer() {
            return new CustomTokenEnhancer();
        }

        public class CustomTokenEnhancer implements TokenEnhancer {
            @Override
            public OAuth2AccessToken enhance(OAuth2AccessToken accessToken, OAuth2Authentication authentication) {
                User user = (User) authentication.getPrincipal();

                final Map<String, Object> additionalInfo = new HashMap<>();

                List<String> tokenValues = new ArrayList<String>();
                Collection<OAuth2AccessToken> tokens = tokenStore.findTokensByClientId(MessageConstants.OAUTHPMO); 
                if (tokens!=null){
                    for (OAuth2AccessToken token:tokens){
                        tokenValues.add(token.getValue());
                    }
                }
                pmo.domain.User us = userDetailsService.viewProfile(user.getUsername());
                additionalInfo.put("User_id", us.getUserId());
                additionalInfo.put("User_type", us.getUserType());
                ((DefaultOAuth2AccessToken) accessToken).setAdditionalInformation(additionalInfo);
                us.setAccess_token(accessToken.getValue());
                //us.setAuditDate(new Date());
                ctx.setAttribute("LOGGED_USER", us);                                        
                return accessToken;
            }
        }



    }
}  

这是我的WebSecurityConfiguration文件

package pmo.oauth;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.boot.web.servlet.ServletListenerRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.Ordered;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.encoding.ShaPasswordEncoder;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.core.session.SessionRegistry;
import org.springframework.security.core.session.SessionRegistryImpl;
/*import org.springframework.security.web.csrf.CsrfTokenRepository;
import org.springframework.security.web.csrf.HttpSessionCsrfTokenRepository;*/
import org.springframework.security.web.session.HttpSessionEventPublisher;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.UrlBasedCorsConfigurationSource;
import org.springframework.web.filter.CorsFilter;

import pmo.service.CustomUserDetailsService;

@Configuration
@EnableWebSecurity
public class WebSecurityConfiguration extends WebSecurityConfigurerAdapter{

    @Autowired
    private CustomUserDetailsService userDetailsService;


    @Override
    protected void configure(HttpSecurity http) throws Exception {

        http.authorizeRequests()
        .anyRequest()
        .fullyAuthenticated();
         //http.csrf()
        //.csrfTokenRepository(csrfTokenRepository());
        //http.csrf().disable();
    }

    /*private CsrfTokenRepository csrfTokenRepository() 
    { 
        HttpSessionCsrfTokenRepository repository = new HttpSessionCsrfTokenRepository(); 
        repository.setSessionAttributeName("_csrf");
        return repository; 
    }*/

    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.userDetailsService(userDetailsService).passwordEncoder(new ShaPasswordEncoder(512));
    }

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

     @Bean
        SessionRegistry sessionRegistry() {            
            return new SessionRegistryImpl();
        }

        @SuppressWarnings({ "rawtypes", "unchecked" })
        @Bean
        public static ServletListenerRegistrationBean httpSessionEventPublisher() {        
            return new ServletListenerRegistrationBean(new HttpSessionEventPublisher());
        }

     @Bean
        public FilterRegistrationBean corsFilter() {
            UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
            CorsConfiguration config = new CorsConfiguration();
            config.setAllowCredentials(true);
            config.addAllowedOrigin("*");
            config.addAllowedHeader("*");
            config.addAllowedMethod("*");
            source.registerCorsConfiguration("/**", config);
            FilterRegistrationBean bean = new FilterRegistrationBean(new CorsFilter(source));
            bean.setOrder(Ordered.HIGHEST_PRECEDENCE);
            return bean;
        }


}

邮递员输入为寄存器API的JSON

{     “名字”:“saravanan”     “姓氏”:“sivaguru”     “电子邮件”:“sar@yopmail.com”     “username” 的: “sarvan” }

发生错误: {     “timestamp”:1507181207207,     “状态”:403,     “错误”:“禁止”,     “message”:“在请求参数'_csrf'或标题'X-CSRF-TOKEN'上找到”无效的CSRF令牌'null'。“,     “path”:“/ pmo / register” }

我也试图禁用csrf,但它不起作用,所以帮助解决它

1 个答案:

答案 0 :(得分:0)

添加http.addFilterAfter(new CsrfTokenResponseHeaderFilter(),CsrfFilter.class); 内部&#39;配置&#39; OAuth2ServerConfiguration类的方法。

检查链接CsrfTokenResponseHeaderFilter example

中的示例