首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >CORS阻断角7和弹簧5

CORS阻断角7和弹簧5
EN

Stack Overflow用户
提问于 2019-10-04 00:40:26
回答 1查看 1.1K关注 0票数 0

我正在运行一个Spring 5与Security和Range7项目,并试图连接前端,但不断收到这条错误消息。我应该注意到,这些项目是我计算机上的两个不同的目录。

OS后端> spring

OS前端>角

代码语言:javascript
复制
Access to XMLHttpRequest at 'http://localhost:8080/login' from origin 'http://localhost:4200' 
has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the
requested resource.

我已经在堆栈溢出上经历过一堆线程,但是没有一条会有帮助。

据我所收集到的问题是我的spring安全配置

春季安全文件

代码语言:javascript
复制
package com.starter_kit.auth;

import com.starter_kit.auth.Auth.CustomizeAuthenticationSuccessHandler;
import com.starter_kit.auth.Company.CompanyRepo;
import com.starter_kit.auth.Users.UserRepo;
import com.starter_kit.auth.Users.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.web.util.matcher.AntPathRequestMatcher;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.CorsConfigurationSource;
import org.springframework.web.cors.UrlBasedCorsConfigurationSource;

import java.util.Arrays;

@Configuration
@EnableWebSecurity
public class AppSecurityConfig extends WebSecurityConfigurerAdapter {

    // code

    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        UserDetailsService userDetailsService = mongoUserDetails();
        auth
                .userDetailsService(userDetailsService)
                .passwordEncoder(bCryptPasswordEncoder);
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http
                .authorizeRequests()
                .antMatchers("/").permitAll()
                .antMatchers("/login").permitAll()
                .antMatchers("/register").permitAll()
                .antMatchers("/dashboard/").hasAuthority("ADMIN").anyRequest()
                .authenticated().and().csrf().disable().formLogin().successHandler(customizeAuthenticationSuccessHandler)
                .loginPage("/login").failureUrl("/login?error=true")
                .usernameParameter("email")
                .passwordParameter("password")
                .and().logout()
                .logoutRequestMatcher(new AntPathRequestMatcher("/logout"))
                .logoutSuccessUrl("/").and().exceptionHandling();
    }

    @Bean
    CorsConfigurationSource corsConfigurationSource() {
        CorsConfiguration configuration = new CorsConfiguration();
        configuration.setAllowedOrigins(Arrays.asList("/**"));
        configuration.setAllowedMethods(Arrays.asList("GET","POST","DELETE","PUT"));
        UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
        source.registerCorsConfiguration("/**", configuration);
        return source;
    }

}

弹簧控制器

代码语言:javascript
复制
@RestController
@CrossOrigin(origins = "http://localhost:4200")
@RequestMapping("/")
public class LoginController {
    @Autowired
    private UserService userService;

    @PostMapping(path = "/login", consumes = MediaType.APPLICATION_JSON_UTF8_VALUE)
    public UserDetails login(@RequestBody User user) {
        return userService.loadUserByUsername(user.getEmail());
    }
}

和我的角形TS HTTP调用

代码语言:javascript
复制
private loginAuth: string = "http://localhost:8080/login";
  public headers = new HttpHeaders({ "Access-Control-Allow-Credentials": "true" })

  public loginUser(user: any) {
    return this.http.post(
      this.loginAuth,
      user,
      { headers: this.headers }
    );
  }

任何帮助都是很好的

EN

回答 1

Stack Overflow用户

发布于 2019-10-08 15:27:41

Spring提供了一个开箱即用的解决方案,以从授权检查中排除选项请求。

代码语言:javascript
复制
@Override
protected void configure(HttpSecurity http) throws Exception {
    http.cors().authorizeRequests() ...

}

cors()方法将把Spring提供的CorsFilter添加到应用程序上下文中,从而绕过对选项请求的授权检查。

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/58228488

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档