我正在寻找一种在我的 Spring 应用程序中实现维护模式的方法。
当应用程序处于维护模式时,role = MAINTENANCE
应该只允许用户登录。其他所有人都会被重定向到登录页面。
现在我刚刚建立了一个过滤器:
@Component
public class MaintenanceFilter extends GenericFilterBean {
@Autowired SettingStore settings;
@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
if(settingStore.get(MaintenanceMode.KEY).isEnabled()) {
HttpServletResponse res = (HttpServletResponse) response;
res.setStatus(HttpServletResponse.SC_SERVICE_UNAVAILABLE);
} else {
chain.doFilter(request, response);
}
}
}
并使用以下方法添加:
@Override
protected void configure(HttpSecurity http) throws Exception {
http
// omitted other stuff
.addFilterAfter(maintenanceFilter, SwitchUserFilter.class);
}
因为据我所知SwitchUserFilter
应该是 Spring Security 过滤器链中的最后一个过滤器。
现在每个请求都会被 503 响应取消。虽然没有办法访问登录页面。
如果我向过滤器添加重定向,这将导致无限循环,因为对登录页面的访问也被拒绝。
此外,我想不出一种获取当前用户角色的好方法。还是我应该一起去SecurityContextHolder
?
我正在寻找一种方法将每个用户重定向到登录页面(可能使用查询参数?maintenance=true
)并且每个用户role = MAINTENANCE
都可以使用该应用程序。
所以过滤器/拦截器的行为应该像:
if(maintenance.isEnabled()) {
if(currentUser.hasRole(MAINTENANCE)) {
// this filter does nothing
} else {
redirectTo(loginPage?maintenance=true);
}
}