问题:get请求可以通过验证,并获取数据:
CloseableHttpClient httpclient = HttpClientBuilder.create().build();
HttpGet post = new HttpGet(url);
// 要进行一个Http头信息配置
String auth = "admin:admin";
String encodedAuth =
Base64Utils.encodeToString(auth.getBytes(java.nio.charset.Charset.forName("US-ASCII")));
// System.out.println(encodedAuth);
// 在进行授权的头信息内容配置的时候加密的信息一定要与“Basic”之间有一个空格
String authHeader = "Basic " + new String(encodedAuth);
BasicHeader header = new BasicHeader("Authorization", authHeader);
post.setHeader(header);
JSONObject response = null;
try {
HttpResponse res = httpclient.execute(post);
System.out.println("res=========" + res);
} catch (Exception e) {
throw new RuntimeException(e);
}
return response;
}
返回结果:200
POST请求:
CloseableHttpClient httpclient = HttpClientBuilder.create().build();
HttpPost post = new HttpPost(url);
// 要进行一个Http头信息配置
String auth = "admin:admin";
String encodedAuth = Base64Utils.encodeToString(auth.getBytes(java.nio.charset.Charset.forName("US-ASCII")));
// System.out.println(encodedAuth);
// 在进行授权的头信息内容配置的时候加密的信息一定要与“Basic”之间有一个空格
String authHeader = "Basic " + new String(encodedAuth);
BasicHeader header = new BasicHeader("Authorization", authHeader);
post.setHeader(header);
JSONObject response = null;
try {
StringEntity s = new StringEntity(json.toString());
s.setContentEncoding("UTF-8");
s.setContentType("application/json");//发送json数据需要设置contentType
post.setEntity(s);
HttpResponse res = httpclient.execute(post);
System.out.println("res=========" + res);
if(res.getStatusLine().getStatusCode() == HttpStatus.SC_OK){
String result = EntityUtils.toString(res.getEntity());// 返回json格式:
response = JSONObject.parseObject(result);
}
} catch (Exception e) {
throw new RuntimeException(e);
}
return response;
}
返回401 其原因是通过我们自定义的过滤器以外的post请求都需要进行token验证。
所以2种办法:
- 自己复写过滤器:(需要在config配置)// http.csrf().requireCsrfProtectionMatcher(new CsrfSecurityRequestMatcher()); 或者直接禁用CSRF:
import org.springframework.context.annotation.Configuration;
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.crypto.bcrypt.BCryptPasswordEncoder;
@Configuration
@EnableWebSecurity
public class WebSecurityConfigurer extends WebSecurityConfigurerAdapter {
@Override
protected void configure(HttpSecurity http) throws Exception {
// http.csrf().requireCsrfProtectionMatcher(requestMatcher());
http.httpBasic().and().csrf().disable();
}
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
//inMemoryAuthentication 从内存中获取
auth.inMemoryAuthentication().passwordEncoder(new BCryptPasswordEncoder()).withUser("admin").password(new BCryptPasswordEncoder().encode("admin")).roles("USER");
}
}