首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >Spring boot -在请求参数'_csrf‘或标头'X- CSRF - Token’上发现无效的CSRF内标识'null‘

Spring boot -在请求参数'_csrf‘或标头'X- CSRF - Token’上发现无效的CSRF内标识'null‘
EN

Stack Overflow用户
提问于 2017-10-05 13:44:18
回答 1查看 3.5K关注 0票数 1

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

代码语言:javascript
复制
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文件

代码语言:javascript
复制
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输入作为注册API的JSON

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

出错:{ "timestamp":1507181207207,"status":403," Error ":“已禁用”,"message":“在请求参数'_csrf‘或标头’X- CSRF - Token‘上发现无效的CSRF标记'null’。”,"path":"/pmo/register“}

我也试过禁用csrf,但它不起作用,所以很好地帮助解决它

EN

回答 1

Stack Overflow用户

发布于 2018-06-01 04:33:50

在OAuth2ServerConfiguration类的'configure‘方法中添加http.addFilterAfter(新的CsrfTokenResponseHeaderFilter(),CsrfFilter.class)。

链接CsrfTokenResponseHeaderFilter example中的检查示例

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/46578621

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档