简体   繁体   English

春季启动-在请求参数'_csrf'或标头'X-CSRF-TOKEN'上发现无效的CSRF令牌'null'

[英]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; 这是我的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;
            }
        }



    }
}  

This my WebSecurityConfiguration file 这是我的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;
        }


}

Postman Input As JSON for register API 邮递员输入为JSON的注册API

{ "firstName":"saravanan", "lastName":"sivaguru", "email":"sar@yopmail.com", "userName":"sarvan" } {“ 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" } 发生错误:{“时间戳”:1507181207207,“状态”:403,“错误”:“禁止”,“消息”:“在请求参数“ _csrf”或标头“ X-CSRF”上发现无效的CSRF令牌“空” -TOKEN'。“,”路径“:” / pmo / register“}

I tried to disable the csrf too but it does not works so kindly help to solve it 我也尝试禁用csrf,但是它不起作用,因此请帮助解决它

Add http.addFilterAfter(new CsrfTokenResponseHeaderFilter(), CsrfFilter.class); 添加http.addFilterAfter(new CsrfTokenResponseHeaderFilter(),CsrfFilter.class); inside 'configure' method of OAuth2ServerConfiguration Class. 在OAuth2ServerConfiguration类的'configure'方法中。

Check example in link CsrfTokenResponseHeaderFilter example 链接CsrfTokenResponseHeaderFilter示例中的检查示例

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 错误HTTP状态403-在请求参数&#39;_csrf&#39;或标头&#39;X-CSRF-TOKEN&#39;上发现无效的CSRF令牌&#39;null&#39; - Error HTTP Status 403 - Invalid CSRF Token 'null' was found on the request parameter '_csrf' or header 'X-CSRF-TOKEN' spring如何使用_csrf参数或X-CSRF-TOKEN标头在内部验证csrf令牌? - How does the spring internally validate the csrf token with _csrf parameter or X-CSRF-TOKEN header? HTTP状态403 - 在请求参数&#39;_csrf&#39;或标题&#39;X-CSRF-TOKEN&#39;上找到无效的CSRF令牌&#39;9ee6949c-c5dc-4d4b-9d55-46b75abc2994&#39; - HTTP Status 403 - Invalid CSRF Token '9ee6949c-c5dc-4d4b-9d55-46b75abc2994' was found on the request parameter '_csrf' or header 'X-CSRF-TOKEN' X-CSRF-TOKEN 不是由 Spring Boot 生成的 - X-CSRF-TOKEN is not generated by Spring Boot 发现无效的 CSRF 令牌 - Spring 引导和 Axios - Invalid CSRF token found - Spring Boot and Axios HTTP状态403 - 在请求参数上找到无效的CSRF令牌“null” - HTTP Status 403 - Invalid CSRF Token 'null' was found on the request parameter Spring 安全 csrf 已禁用,仍然找到无效的 CSRF 令牌 - Spring security csrf disabled, still get an Invalid CSRF token found 使用 x-csrf-token 身份验证连接到 rest Web 服务时出错 - Error connecting to rest webservice with x-csrf-token authentication 如何在 java REST 客户端中获取有效的 X-CSRF-TOKEN? - how to get valid X-CSRF-TOKEN in java REST Client? 405 方法不允许,spring 启动,但我使用 csrf 令牌 header - 405 Method Not Allowed, spring boot, but i used csrf token header
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM