问题:get请求可以通过验证,并获取数据:
public static JSONObject doGet(String url){
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请求:
public static JSONObject doPost(String url, JSONObject json){
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种办法:
1. 自己复写过滤器:(需要在config配置)// http.csrf().requireCsrfProtectionMatcher(new CsrfSecurityRequestMatcher());
//
//import java.awt.List;
//import java.util.ArrayList;
//import java.util.regex.Pattern;
//
//import javax.servlet.http.HttpServletRequest;
//
//import org.springframework.security.web.util.matcher.RequestMatcher;
//
//public class CsrfSecurityRequestMatcher implements RequestMatcher {
//
// private Pattern allowedMethods = Pattern.compile("^(GET|HEAD|TRACE|OPTIONS)$");
//
// @Override
// public boolean matches(HttpServletRequest request) {
// java.util.List<String> unExecludeUrls = new ArrayList();
// //unExecludeUrls.add("/api/test");//(不允许post请求的url路径)此处根据自己的需求做相应的逻辑处理
//
// if (unExecludeUrls != null && unExecludeUrls.size() > 0) {
// String servletPath = request.getServletPath();
// request.getParameter("");
// for (String url : unExecludeUrls) {
// if (servletPath.contains(url)) {
// return true;
// }
// }
// }
// return allowedMethods.matcher(request.getMethod()).matches();
// }
//
//}
或者直接禁用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");
}
}
再次POST 返回200