request.getHeader(“X-HC-USER-NAME”);
header里的这个属性是中文,在经过springsecurity的时候会报错,“The request was rejected because the header value “äº?é?ªé£?” is not allowed”。
在SpringSecurity的配置文件中添加配置bean
@Bean
public StrictHttpFirewall httpFirewall() {
StrictHttpFirewall firewall = new StrictHttpFirewall();
firewall.setAllowedHeaderValues((header) -> {
String parsed = new String(header.getBytes(StandardCharsets.ISO_8859_1), StandardCharsets.UTF_8);
return ASSIGNED_AND_NOT_ISO_CONTROL_PATTERN.matcher(parsed).matches();
});
return firewall;
}
就不会报错了。之后获取header属性后转一下就可以了
String headerUsername = request.getHeader("X-HC-USER-NAME");
String decodeHeaderUserName = new String(headerUsername.getBytes(StandardCharsets.ISO_8859_1), StandardCharsets.UTF_8);
StrictHttpFirewall类
private void validateAllowedHeaderValue(String value) {
if (!StrictHttpFirewall.this.allowedHeaderValues.test(value)) {
throw new RequestRejectedException(
"The request was rejected because the header value \"" + value + "\" is not allowed.");
}
}
private static final Pattern ASSIGNED_AND_NOT_ISO_CONTROL_PATTERN = Pattern
.compile("[\\p{IsAssigned}&&[^\\p{IsControl}]]*");
private static final Predicate<String> ASSIGNED_AND_NOT_ISO_CONTROL_PREDICATE = (
s) -> ASSIGNED_AND_NOT_ISO_CONTROL_PATTERN.matcher(s).matches();
private Predicate<String> allowedHeaderNames = ASSIGNED_AND_NOT_ISO_CONTROL_PREDICATE;
private Predicate<String> allowedHeaderValues = ASSIGNED_AND_NOT_ISO_CONTROL_PREDICATE;
private Predicate<String> allowedParameterNames = ASSIGNED_AND_NOT_ISO_CONTROL_PREDICATE;
private Predicate<String> allowedParameterValues = (value) -> true;
可以看到是allowedHeaderValues匹配的正则表达式
打开springsecurity的官网,查找关键字allowedHeaderValues
看到有解决方案
@Bean
public StrictHttpFirewall httpFirewall() {
StrictHttpFirewall firewall = new StrictHttpFirewall();
firewall.setAllowedHeaderNames((header) -> true);
firewall.setAllowedHeaderValues((header) -> true);
firewall.setAllowedParameterNames((parameter) -> true);
return firewall;
}
@Bean
public StrictHttpFirewall httpFirewall() {
StrictHttpFirewall firewall = new StrictHttpFirewall();
Pattern allowed = Pattern.compile("[\\p{IsAssigned}&&[^\\p{IsControl}]]*");
Pattern userAgent = ...;
firewall.setAllowedHeaderValues((header) -> allowed.matcher(header).matches() || userAgent.matcher(header).matches());
return firewall;
}
firewall.setAllowedHeaderValues((header) -> {
String parsed = new String(header.getBytes(ISO_8859_1), UTF_8);
return allowed.matcher(parsed).matches();
});
我们这里适合用第3种
用Encoder.encode 和Decoder.decode在传输前后对header编解码。