首页 文章

spring CORS和angular not working:HTTP状态码403错误

提问于
浏览
1

我是角度和 spring 安全的新手 . 当我尝试使用基本身份验证从角度登录表单页面登录到其余 endpoints 时,我遇到CORS问题 . 我的Angular代码在http://localhost:4200上运行,而休息终点在http://localhost:8181上运行 . 我的angular login-form尝试向我在登录控制器中指定的http://localhost:8181/token发出请求 . 即使我在服务器端添加了cors配置,我也会收到此错误: -

无法加载http://localhost:8181/token:因此不允许对预检请求进行响应't pass access control check: No ' Access-Control-Allow-Origin ' header is present on the requested resource. Origin ' http://localhost:4200' . 响应具有HTTP状态代码403 .

(有角度的)login.service.ts: -

@Injectable()
export class LoginService {
  constructor(private http: Http) {}

  sendCredential(username: string, password: string) {
    const url = 'http://localhost:8181/token';
    const encodedCredential = username + ':' + password;
    const basicHeader = 'Basic ' + btoa(encodedCredential);
    const headers = new Headers();
    headers.append('Content-Type', 'application/x-wwww-form-urlencoded');
    headers.append('Authorization' ,  basicHeader);
    const opts = new RequestOptions({headers: headers});
    return this.http.get(url, opts);
  }

}

(spring)SecurityConfig.java

@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {

private static final String[] PUBLIC_MATCHERS = {
            "/css/**",
            "/js/**",
            "/image/**",
            "/book/**",
            "/user/**"
    };

@Override
    protected void configure(HttpSecurity http) throws Exception{
        http
                .cors().and()
                .csrf().disable()
                .httpBasic()
                .and()
                .authorizeRequests()
                .antMatchers(PUBLIC_MATCHERS)
                .permitAll()
                .anyRequest()
                .authenticated();
    }
 @Bean
    CorsConfigurationSource corsConfigurationSource() {
        CorsConfiguration configuration = new CorsConfiguration();
        configuration.setAllowedOrigins(Arrays.asList("*"));
        configuration.setAllowedMethods(Arrays.asList("GET","POST","DELETE","PUT","OPTIONS"));
        UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
        source.registerCorsConfiguration("/**", configuration);
        return source;
    }

    @Autowired
    public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
        auth.userDetailsService(userSecurityService).passwordEncoder(passwordEncoder());
    }

LoginController.java

@RestController
public class LoginController {

    @Autowired
    private UserService userService;

    @RequestMapping("/token")
    public Map<String, String> token(HttpSession session, HttpServletRequest request) {
        String remoteHost = request.getRemoteHost();
        int portNumber = request.getRemotePort();
        String remoteAddr = request.getRemoteAddr();

        System.out.println(remoteHost + ":" + portNumber);
        System.out.println(remoteAddr);


        return Collections.singletonMap("token", session.getId());
    }
}

5 回答

  • 1

    我被困这个问题2天,并在 controller 中添加 @CrossOrigin("*") 解决了我的问题 .

    注意:你可以把 origin address 代替 *

  • 0

    使用

    @CrossOrigin("http://your-foreign-site/")
    @RequestMapping("/token")
    

    代替 .

  • 0

    在控制器内部使用.properties文件中的值

    @Value(“$ ”)私有字符串网站;

    使用@crossOrigin(网站)

  • 1

    <mvc:cors>
        <mvc:mapping path="/**" />
    </mvc:cors>
    

    web.xml 以允许来自所有主机的连接

    原产地:https://spring.io/blog/2015/06/08/cors-support-in-spring-framework

  • 3

    试试这个配置 . 它应该适合你 .

    @Bean
    CorsConfigurationSource corsConfigurationSource() {
            CorsConfiguration configuration = new CorsConfiguration();
            configuration.setAllowedOrigins(Arrays.asList("*"));
            configuration.setAllowedMethods(Arrays.asList("GET", "POST", "OPTIONS", "DELETE", "PUT", "PATCH"));
            configuration.setAllowedHeaders(Arrays.asList("X-Requested-With", "Origin", "Content-Type", "Accept", "Authorization"));
            configuration.setAllowCredentials(true);
            UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
            source.registerCorsConfiguration("/**", configuration);
            return source;
        }
    

    由于您使用的是spring security / authentication . 您应该使用setAllowCredentials(true) .

相关问题