我正在尝试访问CustomWebSecurityExpressionRoot中的HttpServletRequest.getServerName()
request.getServerName()
这是我的代码:
public class CustomWebSecurityExpressionRoot extends WebSecurityExpressionRoot {
public CustomWebSecurityExpressionRoot(Authentication a, FilterInvocation fi) {
super(a, fi);
}
public boolean isLocal() {
return "localhost".equals(request.getServerName());
}
}
此表达式根目录在FilterSecurityInterceptor
中设置 @Override
public void configure(final WebSecurity web) throws Exception {
final HttpSecurity http = getHttp();
web.postBuildAction(() -> {
FilterSecurityInterceptor fsi = http.getSharedObject(FilterSecurityInterceptor.class);
fsi.setSecurityMetadataSource(metadataSource);
web.securityInterceptor(fsi);
});
}
然后我有一个数据库条目来设置" local和hasRole(" ADMIN")"它调用了这个表达式。
似乎有一个代理将ServletRequest包装为" DummyRequest"并且不支持所有其他方法。
但是当执行此操作时,我收到以下错误:
java.lang.UnsupportedOperationException: public abstract java.lang.String javax.servlet.ServletRequest.getServerName() is not supported
at org.springframework.security.web.UnsupportedOperationExceptionInvocationHandler.invoke(FilterInvocation.java:235) ~[spring-security-web-4.2.3.RELEASE.jar:4.2.3.RELEASE]
at com.sun.proxy.$Proxy134.getServerName(Unknown Source) ~[na:na]
at javax.servlet.ServletRequestWrapper.getServerName(ServletRequestWrapper.java:207) ~[tomcat-embed-core-8.5.16.jar:8.5.16]
答案 0 :(得分:0)
这是另一种选择
创建一个接收请求作为参数
的简单bean@Component
public class WebChecker {
public boolean isLocalHost(Authentication authentication, HttpServletRequest request) {
System.out.println("Server name" + request.getServerName());
return "localhost".equals(request.getServerName());
}
}
然后在您的安全配置中,您可以通过访问配置调用isLocalHost方法作为表达式,如下所示:
@Override
protected void configure(HttpSecurity http) throws Exception {
http
.authorizeRequests()
.antMatchers("/stores").access("@webChecker.isLocalHost(authentication,request)")
Spring Oficial网站26.2.1 Referring to Beans in Web Security Expressions
中提供了更多信息希望这个替代方案可以帮助你。