2017-11-01 1 views
0

Ich bin neu in eckigen und Feder-Sicherheit.Ich habe Probleme mit CORS beim Versuch, von eckigen Login-Formularseite mit Standard-Authentifizierung an den Rest Endpunkt anmelden. Mein Angular-Code wird unter http://localhost:4200 ausgeführt und der Endpunkt wird auf http://localhost:8181 festgelegt. Mein eckiges Login-Formular versucht, eine Anfrage an http://localhost:8181/token zu stellen, die ich in meinem Login-Controller angegeben habe. Obwohl ich Cors-Konfiguration in Server-Seite hinzugefügt habe, erhalte ich diesen Fehler: -Feder CORS und eckig funktioniert nicht: HTTP-Statuscode 403 Fehler

Fehler beim Laden http://localhost:8181/token: Antwort auf Preflight-Anfrage nicht übergeben Kontrolle der Zugriffskontrolle: Nein 'Access-Control-Allow-Origin' Header ist vorhanden auf der angeforderten Ressource. Origin 'http://localhost:4200' ist daher nicht erlaubt. Der Antwortcode HTTP-Status 403. hatte

(Winkel-) 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); 
    } 

}

(Feder) 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()); 
    } 
} 
+0

CORS scheint deaktiviert zu werden (https://spring.io/understanding/CORS) – Zooly

+0

Ich habe die CORS-Konfiguration in der SecurityConfig-Klasse hinzugefügt, wie oben im Codeblock –

+0

gezeigt. Das Problem liegt bei Ihrem Authentifizierungsmechanismus, irgendwie ist es nicht in der Lage, Benutzer zu authentifizieren. So gibt es 403 Status –

Antwort

0

Versuchen Sie diese Konfiguration. Es sollte für Sie gut funktionieren.

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

Da Sie Federsicherheit/Authentifizierung verwenden. Sie sollten setAllowCredentials (true) verwenden.

+0

Danke. Es funktioniert wie erwartet :) –

0

Verwendung

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

statt.

+1

Aber ich möchte Cors-Konfiguration auf globaler Ebene hinzufügen. Nicht im Controller. –

0

in Ihrem Controller den Wert von einer .properties verwenden

@Value ("$ {cors.site.enable}") private String-Site-Datei;

Verwenden Sie @crossOrigin (Standort)