简体   繁体   中英

Spring boot - Invalid CSRF Token 'null' was found on the request parameter '_csrf' or header 'X-CSRF-TOKEN'

This my OAUTH2 Configuration file package 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;
            }
        }



    }
}  

This my WebSecurityConfiguration file

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;
        }


}

Postman Input As JSON for register API

{ "firstName":"saravanan", "lastName":"sivaguru", "email":"sar@yopmail.com", "userName":"sarvan" }

Error occured: { "timestamp": 1507181207207, "status": 403, "error": "Forbidden", "message": "Invalid CSRF Token 'null' was found on the request parameter '_csrf' or header 'X-CSRF-TOKEN'.", "path": "/pmo/register" }

I tried to disable the csrf too but it does not works so kindly help to solve it

Add http.addFilterAfter(new CsrfTokenResponseHeaderFilter(), CsrfFilter.class); inside 'configure' method of OAuth2ServerConfiguration Class.

Check example in link CsrfTokenResponseHeaderFilter example

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM