gpt4 book ai didi

Java Spring 如何在 webapplicationinitializer 中强制使用 https ssl?

转载 作者:塔克拉玛干 更新时间:2023-11-03 03:51:39 25 4
gpt4 key购买 nike

为了在 web.xml 中强制使用 https,我使用了这个代码片段:

<security-constraint>
<web-resource-collection>
<url-pattern>/*</url-pattern>
</web-resource-collection>
<user-data-constraint>
<transport-guarantee>CONFIDENTIAL</transport-guarantee>
</user-data-constraint>
</security-constraint>

在 Spring Java Config 中有对应的吗?我已经知道我需要一个 ServletSecurityElement。但是我如何它连接到其余部分?

public class WebAppInitializer implements WebApplicationInitializer {
@Override
public void onStartup(ServletContext container) throws ServletException {
AnnotationConfigWebApplicationContext context = new AnnotationConfigWebApplicationContext();
container.addListener(new ContextLoaderListener(context));
context.register(PersistenceJPAConfig.class);

FilterRegistration filter = container.addFilter("wicket.myproject", WicketFilter.class);
filter.setInitParameter("applicationClassName", WicketApplication.class.getName());
filter.setInitParameter(WicketFilter.FILTER_MAPPING_PARAM, "/*");
filter.addMappingForUrlPatterns(null, false, "/*");

HttpConstraintElement forceHttpsConstraint = new HttpConstraintElement(ServletSecurity.TransportGuarantee.CONFIDENTIAL, "");
ServletSecurityElement securityElement = new ServletSecurityElement(forceHttpsConstraint);
}
}

最佳答案

正如 John Thompson 指出的那样,您就在那里。您只需要将您定义的安全元素添加到 servlet。另一方面,我注意到您将 "" 作为 HttpConstraintElement 的 roleNames 参数。这实际上会导致所有没有 "" 角色的人都被拒绝。如果您希望它正常工作(强制 https),请不要提供任何角色。最后这对我有用:

public class ApplicationInitializer implements WebApplicationInitializer {

private static final String DISPATCHER_SERVLET_NAME = "dispatcher";
private static final String DISPATCHER_SERVLET_MAPPING = "/";

@Override
public void onStartup(ServletContext container) throws ServletException {
// Create the dispatcher servlet's Spring application context
AnnotationConfigWebApplicationContext dispatcherContext = new AnnotationConfigWebApplicationContext();
dispatcherContext.register(ApplicationConfiguration.class);

// Register and map the dispatcher servlet
ServletRegistration.Dynamic dispatcher = container.addServlet(DISPATCHER_SERVLET_NAME, new DispatcherServlet(dispatcherContext));
dispatcher.setLoadOnStartup(1);
dispatcher.addMapping(DISPATCHER_SERVLET_MAPPING);

// Force HTTPS, and don't specify any roles for this constraint
HttpConstraintElement forceHttpsConstraint = new HttpConstraintElement(ServletSecurity.TransportGuarantee.CONFIDENTIAL);
ServletSecurityElement securityElement = new ServletSecurityElement(forceHttpsConstraint);

// Add the security element to the servlet
dispatcher.setServletSecurity(securityElement);
}
}

关于Java Spring 如何在 webapplicationinitializer 中强制使用 https ssl?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28509275/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com