简体   繁体   English

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

[英]spring CORS and angular not working : HTTP status code 403 error

I am new to angular and spring-security.I am having problem with CORS when trying to log in from angular login-form page using basic authentication to the rest endpoint. 我是角度和弹簧安全的新手。当我尝试使用基本身份验证从角度登录表单页面登录到其余端点时,我遇到CORS问题。 My Angular code is running on http://localhost:4200 and rest end point on http://localhost:8181 . 我的Angular代码在http:// localhost:4200上运行,而rest端点在http:// localhost:8181上运行 My angular login-form tries to make request to http://localhost:8181/token which I have specified in my login controller. 我的angular login-form尝试向我在登录控制器中指定的http:// localhost:8181 / token发出请求。 Even though I have added cors configuration in server side, I get this error :- 即使我在服务器端添加了cors配置,我也会收到此错误: -

Failed to load http://localhost:8181/token : Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. 无法加载http:// localhost:8181 / token :对预检请求的响应未通过访问控制检查:请求的资源上没有“Access-Control-Allow-Origin”标头。 Origin ' http://localhost:4200 ' is therefore not allowed access. 因此不允许来源' http:// localhost:4200 '访问。 The response had HTTP status code 403. 响应具有HTTP状态代码403。

(angular) login.service.ts:- (有角度的)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 (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 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());
    }
}

Try this configuration. 试试这个配置。 It should work fine for you. 它应该适合你。

@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;
    }

Since you are using spring security / authentication. 由于您使用弹簧安全/身份验证。 You should use setAllowCredentials(true). 您应该使用setAllowCredentials(true)。

Use 使用

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

instead. 代替。

I was stuck with this problem for 2 days and by adding @CrossOrigin("*") in controller solved my problem. 我坚持这个问题2天,在controller添加@CrossOrigin("*")解决了我的问题。

note: you can put your origin address instead of * 注意:您可以输入您的origin address而不是*

inside your controller use the value from a .properties file 在控制器内部使用.properties文件中的值

@Value("${cors.site.enable}") private String site; @Value(“$ {cors.site.enable}”)私有字符串站点;

use @crossOrigin(site) 使用@crossOrigin(网站)

Add

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

to your web.xml to allow connections from all hosts 到您的web.xml以允许来自所有主机的连接

Origin: https://spring.io/blog/2015/06/08/cors-support-in-spring-framework 来源: https//spring.io/blog/2015/06/08/cors-support-in-spring-framework

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM