001/******************************************************************************* 002 * Copyright 2018 The MIT Internet Trust Consortium 003 * 004 * Portions copyright 2011-2013 The MITRE Corporation 005 * 006 * Licensed under the Apache License, Version 2.0 (the "License"); 007 * you may not use this file except in compliance with the License. 008 * You may obtain a copy of the License at 009 * 010 * http://www.apache.org/licenses/LICENSE-2.0 011 * 012 * Unless required by applicable law or agreed to in writing, software 013 * distributed under the License is distributed on an "AS IS" BASIS, 014 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 015 * See the License for the specific language governing permissions and 016 * limitations under the License. 017 *******************************************************************************/ 018/** 019 * 020 */ 021package org.mitre.oauth2.web; 022 023import java.io.IOException; 024 025import javax.servlet.FilterChain; 026import javax.servlet.ServletException; 027import javax.servlet.http.HttpServletRequest; 028import javax.servlet.http.HttpServletResponse; 029 030import org.springframework.stereotype.Component; 031import org.springframework.web.filter.OncePerRequestFilter; 032 033/** 034 * 035 * Implements Cross-Origin Resource Sharing (CORS) headers. This filter adds the CORS 036 * headers to all requests that pass through it, and as such it should be used only 037 * on endpoints that require CORS support. 038 * 039 * @author jricher 040 * 041 */ 042@Component("corsFilter") 043public class CorsFilter extends OncePerRequestFilter { 044 045 /* (non-Javadoc) 046 * @see javax.servlet.Filter#doFilter(javax.servlet.ServletRequest, javax.servlet.ServletResponse, javax.servlet.FilterChain) 047 */ 048 @Override 049 public void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws IOException, ServletException { 050 051 response.addHeader("Access-Control-Allow-Origin", "*"); 052 if (request.getHeader("Access-Control-Request-Method") != null && "OPTIONS".equals(request.getMethod())) { 053 // CORS "pre-flight" request 054 response.addHeader("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE"); 055 response.addHeader("Access-Control-Allow-Headers", "X-Requested-With,Origin,Content-Type, Accept, Authorization"); 056 } 057 filterChain.doFilter(request, response); 058 } 059 060}