当前位置: 首页 > 知识库问答 >
问题:

带Spring靴和角的CORS不工作

柯永福
2023-03-14

我试图从一个应用程序(spring-boot应用程序)调用另一个应用程序(angularjs)上的RESTendpoint。应用程序正在下列主机和端口上运行。

  • REST应用程序,使用Spring Boot,http://localhost:8080
  • HTML应用程序,使用angularjs,http://localhost:50029
adminServices.factory('AdminService', ['$resource', '$http', 'conf', function($resource, $http, conf) {
    var s = {};
    s.isAdminLoggedIn = function(data) {
        return $http({
            method: 'GET',
            url: 'http://localhost:8080/api/admin/isloggedin',
            withCredentials: true,
            headers: {
                'X-Requested-With': 'XMLHttpRequest'
            }
        });
    };
    s.login = function(username, password) {
        var u = 'username=' + encodeURI(username);
        var p = 'password=' + encodeURI(password);
        var r = 'remember_me=1';
        var data = u + '&' + p + '&' + r;

        return $http({
            method: 'POST',
            url: 'http://localhost:8080/login',
            data: data,
            headers: {'Content-Type': 'application/x-www-form-urlencoded'}
        });
    };
    return s;
}]);
adminControllers.controller('LoginController', ['$scope', '$http', 'AdminService', function($scope, $http, AdminService) {
    $scope.username = '';
    $scope.password = '';

    $scope.signIn = function() {
        AdminService.login($scope.username, $scope.password)
            .success(function(d,s) {
                if(d['success']) {
                    console.log('ok authenticated, call another REST endpoint');
                    AdminService.isAdminLoggedIn()
                        .success(function(d,s) {
                            console.log('i can access a protected REST endpoint after logging in');
                        })
                        .error(function(d, s) { 
                            console.log('huh, error checking to see if admin is logged in');
                            $scope.reset();
                        });
                } else {
                    console.log('bad credentials?');
                }
            })
            .error(function(d, s) {
                console.log('huh, error happened!');
            });
    };
}]);
@Component
@Order(Ordered.HIGHEST_PRECEDENCE)
public class CORSFilter implements Filter {

    @Override
    public void destroy() { }

    @Override
    public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain)
            throws IOException, ServletException {
        HttpServletResponse response = (HttpServletResponse) res;
        HttpServletRequest request = (HttpServletRequest) req;

        response.setHeader("Access-Control-Allow-Origin", "http://localhost:50029");
        response.setHeader("Access-Control-Allow-Methods", "POST, PUT, GET, OPTIONS, DELETE");
        response.setHeader("Access-Control-Max-Age", "3600");
        response.setHeader("Access-Control-Allow-Headers", "X-Requested-With, X-Auth-Token");
        response.setHeader("Access-Control-Allow-Credentials", "true");

        if(!"OPTIONS".equalsIgnoreCase(request.getMethod())) {
            chain.doFilter(req, res);
        }
    }

    @Override
    public void init(FilterConfig config) throws ServletException { }
}
@Configuration
@EnableWebSecurity
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {

    @Autowired
    private RestAuthenticationEntryPoint restAuthenticationEntryPoint;

    @Autowired
    private JsonAuthSuccessHandler jsonAuthSuccessHandler;

    @Autowired
    private JsonAuthFailureHandler jsonAuthFailureHandler;

    @Autowired
    private JsonLogoutSuccessHandler jsonLogoutSuccessHandler;

    @Autowired
    private AuthenticationProvider authenticationProvider;

    @Autowired
    private UserDetailsService userDetailsService;

    @Autowired
    private PersistentTokenRepository persistentTokenRepository;

    @Value("${rememberme.key}")
    private String rememberMeKey;

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http
            .csrf().disable()
            .exceptionHandling()
            .authenticationEntryPoint(restAuthenticationEntryPoint)
                .and()
            .authorizeRequests()
                .antMatchers("/api/admin/**").hasRole("ADMIN")
                .antMatchers("/", "/admin", "/css/**", "/js/**", "/fonts/**", "/api/**").permitAll()
                .anyRequest().authenticated()
                .and()
            .formLogin()
                .successHandler(jsonAuthSuccessHandler)
                .failureHandler(jsonAuthFailureHandler)
                .permitAll()
                .and()
            .logout()
                .deleteCookies("remember-me", "JSESSIONID")
                .logoutSuccessHandler(jsonLogoutSuccessHandler)
                .permitAll()
                .and()
            .rememberMe()
                .userDetailsService(userDetailsService)
                .tokenRepository(persistentTokenRepository)
                .rememberMeCookieName("REMEMBER_ME")
                .rememberMeParameter("remember_me")
                .tokenValiditySeconds(1209600)
                .useSecureCookie(false)
                .key(rememberMeKey);
    }

    @Autowired
    public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
        auth
            .authenticationProvider(authenticationProvider);
    }
}

处理程序所做的只是根据用户是否登录、身份验证失败或注销,写出类似{success:true}的JSON响应。RestAuthenticationEntryPoint如下所示。

@Component
public class RestAuthenticationEntryPoint implements AuthenticationEntryPoint {

    @Override
    public void commence(HttpServletRequest req, HttpServletResponse resp, AuthenticationException ex)
            throws IOException, ServletException {
        resp.sendError(HttpServletResponse.SC_UNAUTHORIZED, "Unauthorized");
    }

}

对我错过了什么或者做错了什么有什么想法吗?

共有1个答案

颜河
2023-03-14
import java.io.IOException;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

@Component
public class SimpleCORSFilter implements Filter {

private final Logger log = LoggerFactory.getLogger(SimpleCORSFilter.class);

public SimpleCORSFilter() {
    log.info("SimpleCORSFilter init");
}

@Override
public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException {

    HttpServletRequest request = (HttpServletRequest) req;
    HttpServletResponse response = (HttpServletResponse) res;

    response.setHeader("Access-Control-Allow-Origin", request.getHeader("Origin"));
    response.setHeader("Access-Control-Allow-Credentials", "true");
    response.setHeader("Access-Control-Allow-Methods", "POST, GET, OPTIONS, DELETE");
    response.setHeader("Access-Control-Max-Age", "3600");
    response.setHeader("Access-Control-Allow-Headers", "Content-Type, Accept, X-Requested-With, remember-me");

    chain.doFilter(req, res);
}

@Override
public void init(FilterConfig filterConfig) {
}

@Override
public void destroy() {
}

}

不需要额外定义这个过滤器,只需要添加这个类。Spring将为您扫描并添加。SimpleCorsFilter.下面是示例:spring-enable-cors

 类似资料:
  • 我的服务器运行在localhost:8080(spring boot app)上,前端运行在localhost:3000(angular app)上。问题是我想从前端向后端服务器发出请求。我熟悉cors,但对我来说不起作用。我已将此添加到我的服务器: ,但我仍然得到 XMLHttpRequest无法加载http://localhost:8080/cars.请求被重定向到http://localho

  • 我在我的Spring Boot应用程序中使用JWT。当我试图从Angular 6客户端登录时,我得到了CORS错误 我尝试为添加标题,甚至尝试使用一些chrome扩展,但仍然无法绕过CORS。我可以使用Postman访问登录API,并获得令牌。 Spring引导类 下面是我如何发出post请求来登录,这给了我一个错误 还有Angular中的接口

  • 我有一个Spring Boot项目,使用Jersey作为我的REST服务,并使用AngularJS进行我的前端开发。当我在不使用任何控制器的情况下运行它并转到index.html(位于resource/statig/index.html中)时,它运行得很好。当我添加一个控制器时,它呈现给出字符串“index.html”作为输出。Spring Boot配置: 球衣配置: 控制器类:

  • 我有一个在8888端口上运行的Spring Boot后端应用程序和一个在4200端口上运行的Angular前端应用程序。 在我的Spring Boot应用程序中,我定义了以下bean来处理CORS: 我的配置如下所示: 通过这种配置,一切正常,我可以从Angular应用程序成功调用我的API。 但我想启用CSRF,所以我将安全配置更改为: 我在Angular应用程序中添加了以下: 问题是始终返回。

  • 我创建了一个IntelliJ“空项目”,并添加了两个模块:一个用于Spring Boot(后端),一个用于Angular CLI(前端)。到目前为止,一切都很好。我的项目的文件结构 现在我把这个项目添加到GitLab中,但在克隆这个项目时遇到了一些问题,bc,由于某些原因,它有时只得到一个模块。我也遇到了。gitignore文件的问题,这需要在我的根项目中的特定模块之外。对于。gitlab-ci.

  • 我在下面的链接中添加了过滤器作为问题的答案 Spring Boot Data Rest+CORS不能正确启用选项/删除