gpt4 book ai didi

java - Spring boot - 在请求参数 'null' 或 header '_csrf' 上发现无效的 CSRF token 'X-CSRF-TOKEN'

转载 作者:太空宇宙 更新时间:2023-11-04 11:04:36 26 4
gpt4 key购买 nike

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


}

postman 输入作为 JSON 用于注册 API

{
"firstName":"saravanan",
"姓氏":"sivaguru",
"电子邮件":"sar@yopmail.com",
“用户名”:“sarvan”
}

发生了错误:
{
“时间戳”:1507181207207,
“状态”:403,
“错误”:“禁止”,
"message": "在请求参数 '_csrf' 或 header 'X-CSRF-TOKEN' 上发现无效的 CSRF Token 'null'。",
“路径”:“/pmo/注册”
}

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

最佳答案

添加http.addFilterAfter(new CsrfTokenResponseHeaderFilter(), CsrfFilter.class);
在 OAuth2ServerConfiguration 类的“配置”方法中。

检查链接中的示例 CsrfTokenResponseHeaderFilter example

关于java - Spring boot - 在请求参数 'null' 或 header '_csrf' 上发现无效的 CSRF token 'X-CSRF-TOKEN',我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46578621/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com