¿Cómo puedo obligar a acceder a una página solo a través de HTTPS? Necesito hacer esto a través del archivo de configuración Spring MVC 3.Spring mvc 3 - Acceso HTTPS
Respuesta
Primavera-seguridad tiene una configuración tal. see here para saber cómo hacerlo. En pocas palabras - se fuerza el canal a utilizar https:
<http>
<intercept-url pattern="/secure/**" access="ROLE_USER"
requires-channel="https"/>
<intercept-url pattern="/**" access="ROLE_USER"
requires-channel="any"/>
</http>
Si no desea utilizar resortes de seguridad, aquí está un interceptor que escribí:
@Component
public class SslInterceptor extends HandlerInterceptorAdapter {
// no need to inject it for now..
private PathMatcher pathMatcher = new AntPathMatcher();
@Value("${base.url.secure}")
private String secureRoot;
@Resource(name="secureLocations")
private List<String> secureLocations;
@Value("${use.ssl}")
private boolean useSsl;
@Override
public boolean preHandle(HttpServletRequest request,
HttpServletResponse response, Object handler) throws Exception {
if (useSsl && !request.isSecure() && shouldForceSecure(request.getRequestURI())) {
String redirectUrl = secureRoot + request.getRequestURI();
if (request.getQueryString() != null) {
redirectUrl += "?" + request.getQueryString();
}
// force session creation - thus it will be accessible to both the
// secure and the insecure contexts
request.getSession(true);
response.sendRedirect(redirectUrl);
return false;
}
return true;
}
private boolean shouldForceSecure(String path) {
for (String pattern : secureLocations) {
if (pathMatcher.match(pattern, path)) {
return true;
}
}
return false;
}
}
Puede hacerlo en su configuración de Tomcat.
intente agregar redirectPort = "" en server.xml al conector HTTP.
Espero que ayude.
Actualización:
este artículo se explicará cómo tratar con SSL y tiene una gran cantidad de un ejemplos.
Bueno, sólo ayuda si están utilizando Tomcat ... – skaffman
de acuerdo, pero cada servidor de aplicaciones tiene tales opciones incluso IIS :). Simplemente escribí la idea de lo que debería hacerse. –
Por favor, puede dar un ejemplo –
Para un enfoque basado en la anotación sin Spring Security I escribió un interceptor y una nueva anotación: método de controlador de
/**
* Request mapping annotation to enforce secure or insecure requests.
* Per default the annotated mapping is enforced to be secure.
*
* @see org.springframework.web.bind.annotation.RequestMapping
*/
@Target({ElementType.METHOD, ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Mapping
public @interface RequestProtocol {
boolean secure() default true;
}
Así que usted puede simplemente declarar una (aquí por REST) así:
@RequestMapping(value = "/secret", method = RequestMethod.GET)
@RequestProtocol(secure = true)
@ResponseBody
public Result doSecure(@Valid Model model) {
return doSomething(model));
}
Para habilitar la asignación, utilice un interceptor que redirija el protocolo incorrecto. También puede hacer un manejo más simple simplemente enviando una respuesta PROHIBIDA.
/**
* Interceptor to send a redirect on security enforced mappings with wrong type of request.
*
* @see RequestProtocol
*/
class RequestProtocolInterceptor extends HandlerInterceptorAdapter {
private static final int PORT_DIFF = 443 - 80;
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws IOException {
Boolean secure = checkSecure(handler);
if (secure != null && request.isSecure() != secure) {
response.sendRedirect(switchSecure(secure, request.getRequestURL()));
return false;
}
return true;
}
private Boolean checkSecure(Object handler) {
if (handler instanceof HandlerMethod) {
HandlerMethod method = (HandlerMethod)handler;
RequestProtocol annotation = method.getMethodAnnotation(RequestProtocol.class);
if (annotation == null) {
annotation = AnnotationUtils.findAnnotation(method.getBeanType(), RequestProtocol.class);
}
return annotation == null ? null : annotation.secure();
}
return null;
}
private String switchSecure(boolean secure, StringBuffer url) {
int endSchema = url.indexOf("://");
url.replace(0, endSchema, secure ? "https" : "http");
int startPort = url.indexOf(":", endSchema + 3);
if (startPort != -1) {
int endPort = url.indexOf("/", startPort);
int port = Integer.parseInt(url.substring(startPort + 1, endPort));
port += secure ? PORT_DIFF : -PORT_DIFF;
url.replace(startPort + 1, endPort, String.valueOf(port));
}
return url.toString();
}
}
Para habilitar el interceptor basado en una anotación de configuración pura de manantial, utilice el WebMvcConfigurerAdapter:
@Configuration
@EnableWebMvc
public class MyConfiguration extends WebMvcConfigurerAdapter {
@Override
public void addInterceptors(InterceptorRegistry registry) {
registry.addInterceptor(new RequestProtocolInterceptor());
}
}
- 1. Spring 3 MVC Nesting RequestMapping
- 2. Spring 3 JSON con MVC
- 3. ¿Cómo desarrollar el sitio https con Spring 3.x?
- 4. Spring 3 MVC y asistentes modales
- 5. Spring MVC 3: asignación ambigua hallada
- 6. Cómo usar Servlet 3 @WebServlet & async con Spring MVC 3?
- 7. Acceso para solicitar IP fuente en Spring 3 Aplicación web MVC
- 8. Acceso a las propiedades de la aplicación en Spring-MVC
- 9. Struts2 vs Spring 3
- 10. GitHub - acceso HTTPS
- 11. Spring MVC vinculante
- 12. Acceso a los beans Spring MVC DI de jsp
- 13. Control de acceso basado en roles con Spring MVC
- 14. Primeros pasos con Spring 3 Web MVC - Configuración de todo
- 15. ¿Cómo implementar una barra de progreso usando Spring 3 MVC?
- 16. Spring 3 MVC y Apache Tiles 2 Error de integración
- 17. Spring 3 MVC: Mostrar mensaje de validación con validador personalizado
- 18. Spring MVC 3, Interceptor en todos excluyendo algunas rutas definidas
- 19. Spring 3 MVC - formulario: errores que no muestran los errores
- 20. Spring MVC 3 - ¿Responde a la solicitud con un 404?
- 21. Spring MVC 3: Devolver XML a través de @ResponseBody
- 22. Spring 3 MVC que accede a HttpRequest desde el controlador
- 23. Enlace/incluir css en FreeMarker usando Spring 3 MVC
- 24. Spring 3 MVC espacio de nombres y i18n
- 25. Spring MVC 3 - etiquetas personalizadas en <form:select>
- 26. Spring 3 MVC dispatcher xml y applicationContext xml
- 27. Cómo implementar la paginación en Spring MVC 3
- 28. Cómo heredar RequestMappings en una Spring 3 MVC REST API
- 29. Java: Spring security 3 Jerarquía de roles
- 30. ServletContext y Spring MVC
Gracias Bozho. El ejemplo se ve genial. También puede compartir conmigo cómo se puede hacer usando la configuración de seguridad de primavera. –
ver actualizado .... – Bozho
Exactamente lo que quiero. De hecho, vi este artículo antes de publicar la pregunta. Soy nuevo en Spring MVC. Puse el archivo de configuración de Spring pero estaba obteniendo errores de análisis. Sé que estoy pidiendo demasiado, pero ¿pueden darme un archivo XML de muestra? Gracias Bozho. –