Skip to content

Instantly share code, notes, and snippets.

@samie
Last active June 19, 2018 06:42
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save samie/9dcf26a6fbc034294e40 to your computer and use it in GitHub Desktop.
Save samie/9dcf26a6fbc034294e40 to your computer and use it in GitHub Desktop.
Using CORS with Vaadin
<html>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<head>
<!-- Add withCredentials to Vaadin requests to allow session cookies. Note: this affects to all XHRs on this page. -->
<script>
XMLHttpRequest.prototype._originalSend = XMLHttpRequest.prototype.send;
var sendWithCredentials = function(data) {
this.withCredentials = true;
this._originalSend(data);
};
XMLHttpRequest.prototype.send = sendWithCredentials;
</script>
<style>
/* Set size and styles for the application DIV */
#myapp {
width: 300px;
height: 300px;
border:1px solid #aaa;
box-shadow: 2px 2px 20px gray;
}
</style>
</head>
<body>
<!-- Load the Vaadin bootstrap -->
<script type="text/javascript" src="http://myvaadinappdomain.com/VAADIN/vaadinBootstrap.js"></script>
<!-- Placeholder for the vaadin application-->
<div id="myapp" class="v-app embedded">
<div class="v-app-loading"></div>
</div>
<!-- Start the Vaadin application from myvaadinappdomain.com -->
<script type="text/javascript">
window.onload= function() {
if (!window.vaadin) alert("Failed to load the Vaadin bootstrap");
vaadin.initApplication("myapp", {
"browserDetailsUrl": "http://myvaadinappdomain.com/",
"serviceUrl": "http://myvaadinappdomain.com/",
"widgetset": "com.vaadin.DefaultWidgetSet",
"theme": "reindeer",
"versionInfo": {"vaadinVersion": null},
"vaadinDir": "http://myvaadinappdomain.com/VAADIN/",
"heartbeatInterval": 300,
"debug": true,
});
}
</script>
</body>
</html>
@WebServlet(value = "/*", asyncSupported = true)
@VaadinServletConfiguration(productionMode = false, ui = MyVaadinUI.class)
public static class MyCORSServlet extends VaadinServlet {
/**
* Override to handle the CORS requests.
*/
@Override
protected void service(HttpServletRequest request,
HttpServletResponse response) throws ServletException,
IOException {
// Origin is needed for all CORS requests
String origin = request.getHeader("Origin");
if (origin != null && isAllowedRequestOrigin(origin)) {
// Handle a preflight "option" requests
if ("options".equalsIgnoreCase(request.getMethod())) {
response.addHeader("Access-Control-Allow-Origin", origin);
response.setHeader("Allow",
"GET, HEAD, POST, PUT, DELETE, TRACE, OPTIONS");
// allow the requested method
String method = request
.getHeader("Access-Control-Request-Method");
response.addHeader("Access-Control-Allow-Methods", method);
// allow the requested headers
String headers = request
.getHeader("Access-Control-Request-Headers");
response.addHeader("Access-Control-Allow-Headers", headers);
response.addHeader("Access-Control-Allow-Credentials",
"true");
response.setContentType("text/plain");
response.setCharacterEncoding("utf-8");
response.getWriter().flush();
return;
} // Handle UIDL post requests
else if ("post".equalsIgnoreCase(request.getMethod())) {
response.addHeader("Access-Control-Allow-Origin", origin);
response.addHeader("Access-Control-Allow-Credentials",
"true");
super.service(request, response);
return;
}
}
// All the other requests nothing to do with CORS
super.service(request, response);
}
/**
* Check that the page Origin header is allowed.
*/
private boolean isAllowedRequestOrigin(String origin) {
// TODO: Remember to limit the origins.
return origin.matches(".*");
}
}
@samie
Copy link
Author

samie commented Jun 12, 2015

Optionally, instead of extending the Servlet to provide the necessary header, you can also use ServletFilter. See this code: https://gist.github.com/el-mot/ade1c6b31206e04184a5

@ekovacs
Copy link

ekovacs commented Nov 11, 2016

The filter based gist link is now broken :-/

@sirbris
Copy link

sirbris commented Jun 19, 2018

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment