使用Grails 3配置CORS

时间:2016-10-06 13:35:07

标签: rest grails spring-security cors

我正在尝试使用此插件在Grails 3.1.12应用中启用CORS支持:https://github.com/appcela/grails3-cors-interceptor

我按照文档进行操作,这是我在application.groovy中的安全配置:

grails.plugin.springsecurity.controllerAnnotations.staticRules = [
[pattern: '/',               access: ['permitAll']],
[pattern: '/error',          access: ['permitAll']],
[pattern: '/index',          access: ['permitAll']],
[pattern: '/index.gsp',      access: ['permitAll']],
[pattern: '/shutdown',       access: ['permitAll']],
[pattern: '/assets/**',      access: ['permitAll']],
[pattern: '/**/js/**',       access: ['permitAll']],
[pattern: '/**/css/**',      access: ['permitAll']],
[pattern: '/**/images/**',   access: ['permitAll']],
[pattern: '/**/favicon.ico', access: ['permitAll']],
// EDIT: block all other URL access
[pattern: '/**', access: ['denyAll'], httpMethod: 'GET'],
[pattern: '/**', access: ['denyAll'], httpMethod: 'POST'],
[pattern: '/**', access: ['denyAll'], httpMethod: 'PUT'],
[pattern: '/**', access: ['denyAll'], httpMethod: 'DELETE']
]

grails.plugin.springsecurity.filterChain.chainMap = [
[pattern: '/assets/**',      filters: 'none'],
[pattern: '/**/js/**',       filters: 'none'],
[pattern: '/**/css/**',      filters: 'none'],
[pattern: '/**/images/**',   filters: 'none'],
[pattern: '/**/favicon.ico', filters: 'none'],
[pattern: '/api/login',      filters: 'securityCorsFilter,restAuthenticationFilter'],
// see http://alvarosanchez.github.io/grails-angularjs-springsecurity-workshop/
//  [pattern: '/**',             filters: 'JOINED_FILTERS'],
[
    pattern: '/api/**',
    filters: 'JOINED_FILTERS,-anonymousAuthenticationFilter,-exceptionTranslationFilter,-authenticationProcessingFilter,-securityContextPersistenceFilter,-rememberMeAuthenticationFilter'
]
]
// EDIT: Optimistic approach (restrict access by URL only) to allow 'OPTIONS' access for CORS
grails.plugin.springsecurity.rejectIfNoRule = false
grails.plugin.springsecurity.fii.rejectPublicInvocations = false

我的问题是,当我向任何/ api /某些端点发送OPTIONS请求而不提供授权标头时,我得到401状态,我不明白为什么。

2 个答案:

答案 0 :(得分:1)

好的,我注意到与sample project的一个关键区别。我的项目在控制器级别使用RestfulController@Secured注释,这就是OPTIONS上401的负责人。我在方法层面覆盖了所有保护它们的方法,现在我再也没有获得401了。

答案 1 :(得分:1)

你可以试试这个解决方案(对我有用,使用grails 3.1.x):

CrosFilter.java:

import org.springframework.web.filter.OncePerRequestFilter;
import javax.annotation.Priority;
import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@Priority(Integer.MIN_VALUE)
public class CorsFilter extends OncePerRequestFilter {

    public CorsFilter() { }

    @Override
    protected void doFilterInternal(HttpServletRequest req, HttpServletResponse resp, FilterChain chain)
            throws ServletException, IOException {

        String origin = req.getHeader("Origin");

        boolean options = "OPTIONS".equals(req.getMethod());
        if (options) {
            if (origin == null) return;
            resp.addHeader("Access-Control-Allow-Headers", "origin, authorization, accept, content-type, x-requested-with");
            resp.addHeader("Access-Control-Allow-Methods", "GET, HEAD, POST, PUT, DELETE, TRACE, OPTIONS");
            resp.addHeader("Access-Control-Max-Age", "3600");

        }

        resp.addHeader("Access-Control-Allow-Origin", origin == null || origin.equals("null") ? "*" : origin);
        resp.addHeader("Access-Control-Allow-Credentials", "true");

        if (!options) chain.doFilter(req, resp);
    }
}

如果您使用插件配置文件: 的src /主/常规/ pluginname / PluginNameGrailsPlugin.groovy:

 Closure doWithSpring() {
        { ->
            corsFilter(CorsFilter)
         }
}

用于Web应用程序配置文件: 的grails-app / CONF /弹簧/ resources.groovy:

beans = {
corsFilter(CorsFilter)
}