1

Je développe une application avec printemps comme backend et angular2 comme frontend, Le côté Backend est sécurisé (avec sécurité de printemps), et j'ai le formulaire de connexion par défaut lorsque je l'exécute. Je souhaite me connecter du côté client au serveur, mais lorsque j'essaie de transmettre les informations d'identification, j'ai ces erreurs dans la console du navigateur.Comment passer les informations d'identification de frontend Angular2 au back-end de printemps (Basic Authentification avec Spring Security)

Voici les ERREURS: enter image description here

enter image description here

Je déployer mon application angular2 sur serveur wildfly (même port que la partie back-end).

La classe de configuration

@Configuration 
    @EnableWebSecurity 
    @ComponentScan(basePackages = { "tn.com.kmf.springdemo.config" }) 
    public class WebSecurityConfig extends WebSecurityConfigurerAdapter { 


     @Autowired 
     private RESTAuthenticationFailureHandler authenticationFailureHandler; 
     @Autowired 
     private RESTAuthenticationSuccessHandler authenticationSuccessHandler; 

     @Autowired 
     public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception { 
      auth.inMemoryAuthentication().withUser("admin").password("admin").roles("ADMIN", "USER").and().withUser("user") 
        .password("user").roles("USER"); 
     } 

     @Override 
     protected void configure(HttpSecurity http) throws Exception { 

      http 
    .csrf().disable() 
    .addFilterBefore(new CORSFilter(), ChannelProcessingFilter.class) 
    .authorizeRequests() 
    .antMatchers("/etudiant/list").hasRole("ADMIN") 
     .anyRequest().authenticated() 
     .and() 
    .formLogin() 
     .loginProcessingUrl("/login") 
     .usernameParameter("username") 
     .passwordParameter("password") 
     .successHandler(authenticationSuccessHandler) 
     .failureHandler(authenticationFailureHandler) 
    .permitAll() 
    .and() 
    .httpBasic(); 
     } 

    } 

Le CorsFilter:

public class CORSFilter implements Filter{ 


     @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", "*"); 
      response.setHeader("Access-Control-Allow-Methods", "POST, GET, OPTIONS, DELETE"); 
      response.setHeader("Access-Control-Max-Age", "3600"); 
      response.setHeader("Access-Control-Allow-Headers", "x-requested-with, authorization"); 

      if ("OPTIONS".equalsIgnoreCase(request.getMethod())) { 
       response.setStatus(HttpServletResponse.SC_OK); 
      } else { 
       chain.doFilter(req, res); 
     } 
    } 

     @Override 
     public void init(FilterConfig filterConfig) {} 

     @Override 
     public void destroy() { } 
} 

Le filtre de sécurité dans web.xml:

<filter> 
    <filter-name>springSecurityFilterChain</filter-name> 
     <filter-class> 
     org.springframework.web.filter.DelegatingFilterProxy 
     </filter-class> 
    </filter> 
    <filter-mapping> 
    <filter-name>springSecurityFilterChain</filter-name> 
    <url-pattern>/*</url-pattern> 
    </filter-mapping> 

Le formulaire de connexion du côté angular2:

<div class="login jumbotron center-block"> 
 
    <h1>Login</h1> 
 
    <form role="form" (submit)="login(username.value, password.value)"> 
 
    <div class="form-group"> 
 
    <label for="username">Username</label> 
 
    <input type="text" #username class="form-control" id="username" placeholder="Username"> 
 
    </div> 
 
    <div class="form-group"> 
 
    <label for="password">Password</label> 
 
    <input type="password" #password class="form-control" id="password" placeholder="Password"> 
 
    </div> 
 
    <button type="submit" class="btn btn-default">Submit</button> 
 
</form> 
 
</div>

Le code de service: (login.service.ts)

import { Injectable } from '@angular/core'; 

import { Http, Response, Headers } from '@angular/http'; 
import { Observable } from 'rxjs/Rx'; 

import 'rxjs/add/operator/map'; 
import 'rxjs/add/operator/catch'; 

@Injectable() 
export class LoginService { 

    isAuthenticated = false; 

    constructor(private http: Http) { 

    } 

    login(username: string, password: string) { 
    const headers = new Headers(); 
    const creds = 'username=' + username + '&password=' + password; 
    // headers.append('Content-Type', 'application/json'); 
    headers.append('Authorization', 'Basic ' + 
     btoa(username+':'+password)); 
    headers.append('Content-Type', 'application/x-www-form-urlencoded'); 
    return new Promise((resolve) => { 
     this.http.post('http://localhost:8080/StudentManager/login', creds, { headers: headers }).subscribe((data) => { 
     console.log(creds); 
     if (data.json().success) { 
      // window.localStorage.setItem('auth_key', data.json().token); 
      // this.userId = data.json().userId; 
      this.isAuthenticated = true; 
     } 
     resolve(this.isAuthenticated); 
     }); 
    }); 
    } 
} 
+1

Si vous souhaitez utiliser le formulaire de connexion, vous devez envoyer un nom d'utilisateur et un mot de passe avec le type de contenu 'application/x-www-form-urlencoded' et non comme JSON. – dur

+0

Je l'ai changé en ** application/x-www-form-urlencoded ** mais j'ai toujours les mêmes erreurs – SuperGirl

+1

Non, je viens d'envoyer des informations d'identification sans JSON.stringify – SuperGirl

Répondre

0

Lorsque vous déclarez cela:

.and().formLogin() 

Le point de connexion par défaut doit être: "yourAppContextPath/login? User = myUser & password = myPassword";

et quand vous déclarez:

.and().httpBasic(); 

signifie que vous souhaitez utiliser ressort « d'accès de base d'authentification »

le login après que vous devez chaque fois envoyer un en-tête avec la valeur « de base: »

var authenticate = function(credentials, callback) { 
     var headers = credentials ? { 
      authorization : "Basic " 
        + btoa(credentials.username + ":" 
          + credentials.password) 
     } : {}; 
     $http.get('user', { 
      headers : headers 
     }).then(function(response) { 
      if (response.data.name) { 
       $rootScope.authenticated = true; 
      } else { 
       $rootScope.authenticated = false; 
      } 
      callback && callback($rootScope.authenticated); 
     }, function() { 
      $rootScope.authenticated = false; 
      callback && callback(false); 
     }); 
    } 

il y a l'échantillon complet peut-être vous aider: https://github.com/spring-guides/tut-spring-security-and-angular-js/blob/master/single/src/main/resources/static/js/hello.js

vous utilisez aussi CORS! Vous devez donc ajouter un jeton _cors dans votre page de connexion.

+1

ça ne marche pas :(j'ai toujours la même erreur :( – SuperGirl