IdentifiantMot de passe
Loading...
Mot de passe oublié ?Je m'inscris ! (gratuit)
Navigation

Inscrivez-vous gratuitement
pour pouvoir participer, suivre les réponses en temps réel, voter pour les messages, poser vos propres questions et recevoir la newsletter

Spring Boot Java Discussion :

La page de login fait maison n'est pas affichée dan le contexte spring security/angular


Sujet :

Spring Boot Java

  1. #1
    Membre actif
    Profil pro
    Inscrit en
    Septembre 2006
    Messages
    728
    Détails du profil
    Informations personnelles :
    Localisation : France

    Informations forums :
    Inscription : Septembre 2006
    Messages : 728
    Points : 250
    Points
    250
    Par défaut La page de login fait maison n'est pas affichée dan le contexte spring security/angular
    Bonjour,
    je travaille sur une application Spring Boot/Spring Security/angular. J'ai implémenté du coté client une page de login correspondant au composant LoginComponent

    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
     
    @Component({
      selector: 'app-login',
      templateUrl: './login.component.html'
    })
    export class LoginComponent implements OnInit {
    Le routing est défini de la sorte

    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
     
    const routes: Routes = [
      { path: '', component: HomeComponent, canActivate: [AuthGuard] },
      { path: 'login', component: LoginComponent },
     
      // otherwise redirect to home
      { path: '**', redirectTo: '', pathMatch: 'full' }
    ];
    Quand je lance en dev l'url http://localhost:4200/login, tout se passe bien et la page de login est affichée

    j'interface avec un back Spring Boot/Spring Security que je lance avec >java -jar backend-0.1-SNAPSHOT.jar où backend-0.1-SNAPSHOT.jar est le package de l'ensemble coté client/coté serveur. Avant d'implémenter Spring Security, tout se passait bien et j'avais la page de login affichée lorsque je lancais l'url http://localhost:8080/login

    J'ai rajouté Spring Security. La configuration est la suivante:

    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    48
    49
    50
    51
    52
    53
    54
    55
    56
    57
    58
    59
    60
    61
    62
    63
    64
    65
    66
    67
    68
    69
     
    package .............;
     
    import .......
     
    @Configuration
    @EnableWebSecurity
    public class WebSecurityConfig  extends WebSecurityConfigurerAdapter {
     
     
        @Autowired
        private CustomUserDetailsService userDetailsService;
     
        @Autowired
        private UserRepository userRepository;
     
        @Autowired
        private ModelMapper modelMapper;
     
     
        @Override
        protected void configure(AuthenticationManagerBuilder auth)
                throws Exception {
            auth.authenticationProvider(authenticationProvider());
        }
     
        @Bean
        public DaoAuthenticationProvider authenticationProvider() {
            DaoAuthenticationProvider authProvider
                    = new DaoAuthenticationProvider();
            authProvider.setUserDetailsService(userDetailsService);
            authProvider.setPasswordEncoder(bCryptPasswordEncoder());
            return authProvider;
        }
     
        @Bean(name="passwordEncoder")
        public BCryptPasswordEncoder bCryptPasswordEncoder() {
            return new BCryptPasswordEncoder();
        }
     
        @Override
        protected void configure(HttpSecurity http) throws Exception {
            http
                    .httpBasic()
                    .and()
                    .authorizeRequests()
                    .antMatchers("/index.html", "/", "/home", "/login").permitAll()
                    .anyRequest().authenticated().and()
                    .cors().configurationSource(corsConfigurationSource()).and()
                    .formLogin(form -> form
                            .loginPage("/login")
                            .permitAll().defaultSuccessUrl("/")
                            .failureUrl("/login")
                    );
     
        }
     
        @Bean
        CorsConfigurationSource corsConfigurationSource() {
            CorsConfiguration configuration = new CorsConfiguration();
            configuration.setAllowedOrigins(Arrays.asList("http://localhost:4200"));
            configuration.setAllowedMethods(Arrays.asList("*"));
            configuration.setAllowedHeaders(Arrays.asList("*"));
            configuration.setAllowCredentials(true);
            UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
            source.registerCorsConfiguration("/**", configuration);
            return source;
        }
    }
    J'ai rajouté le controller suivant mais je ne sais pas si c'est nécessaire

    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
     
    @CrossOrigin(origins = "http://localhost:4200")
    public class HelloController {
     
     
        @RequestMapping("/login")
        public boolean login() {
            return
                    isAuthenticated();
        }
     
        private boolean isAuthenticated() {
            Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
            if (authentication == null || AnonymousAuthenticationToken.class.
                    isAssignableFrom(authentication.getClass())) {
                return false;
            }
            return authentication.isAuthenticated();
        }
    et quand je lance le jar et met l'adresse http://localhost:8080/login, j'ai une requête GET
    http://localhost:8080/login qui est lancée avec succès et qui renvoie false dans la page, mais ma page de login n'est pas affichée. Les logs sont les suivant :

    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
     
    2021-05-01 09:26:18.869  INFO 964 --- [           main] com.example.commission.Application       : Started Application in 12.654 seconds (JVM running for 13.801)
    2021-05-01 09:26:24.932  INFO 964 --- [nio-8080-exec-1] o.a.c.c.C.[Tomcat].[localhost].[/]       : Initializing Spring DispatcherServlet 'dispatcherServlet'
    2021-05-01 09:26:24.934  INFO 964 --- [nio-8080-exec-1] o.s.web.servlet.DispatcherServlet        : Initializing Servlet 'dispatcherServlet'
    2021-05-01 09:26:24.936  INFO 964 --- [nio-8080-exec-1] o.s.web.servlet.DispatcherServlet        : Completed initialization in 2 ms
    2021-05-01 09:26:24.961 DEBUG 964 --- [nio-8080-exec-1] o.s.security.web.FilterChainProxy        : Securing GET /login
    2021-05-01 09:26:24.969 DEBUG 964 --- [nio-8080-exec-1] s.s.w.c.SecurityContextPersistenceFilter : Set SecurityContextHolder to empty SecurityContext
    2021-05-01 09:26:24.982 DEBUG 964 --- [nio-8080-exec-1] o.s.s.w.a.AnonymousAuthenticationFilter  : Set SecurityContextHolder to anonymous SecurityContext
    2021-05-01 09:26:24.983 DEBUG 964 --- [nio-8080-exec-1] o.s.s.w.session.SessionManagementFilter  : Request requested invalid session id 151FD0D8B3F35F2A7928F29359EF4C03
    2021-05-01 09:26:24.995 DEBUG 964 --- [nio-8080-exec-1] o.s.s.w.a.i.FilterSecurityInterceptor    : Authorized filter invocation [GET /login] with attributes [permitAll]
    2021-05-01 09:26:24.996 DEBUG 964 --- [nio-8080-exec-1] o.s.security.web.FilterChainProxy        : Secured GET /login
    2021-05-01 09:26:25.072 DEBUG 964 --- [nio-8080-exec-1] w.c.HttpSessionSecurityContextRepository : Did not store anonymous SecurityContext
    2021-05-01 09:26:25.082 DEBUG 964 --- [nio-8080-exec-1] w.c.HttpSessionSecurityContextRepository : Did not store anonymous SecurityContext
    2021-05-01 09:26:25.082 DEBUG 964 --- [nio-8080-exec-1] s.s.w.c.SecurityContextPersistenceFilter : Cleared SecurityContextHolder to complete request
    et quand je lance l'url http://localhost:8080, j'obtiens sur mon navigateur l'écran suivant

    Nom : Capture d’écran 2021-05-01 à 10.08.29.png
Affichages : 881
Taille : 76,7 Ko

  2. #2
    Membre actif
    Profil pro
    Inscrit en
    Septembre 2006
    Messages
    728
    Détails du profil
    Informations personnelles :
    Localisation : France

    Informations forums :
    Inscription : Septembre 2006
    Messages : 728
    Points : 250
    Points
    250
    Par défaut
    Bonjour, j'ai résolu l'erreur d'affichage de la popup qui me demande un nom d'utilisateur et un mot de passe par la solution suivante

    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
     
    @Configuration
    @EnableWebSecurity
    public class SecurityConfig extends WebSecurityConfigurerAdapter {
     
        @Override
        protected void configure(HttpSecurity security) throws Exception
        {
         security.httpBasic().disable();
        }
    }

    et ma custom page de login s'affiche avec la nouvelle configuration suivante


    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
     
         @Override
        protected void configure(HttpSecurity http) throws Exception {
            http
                    .authorizeRequests()
                    .antMatchers("/index.html", "/", "/home", "/login", "/**/*.css",  "/*.js", "/*.ico", "/**/*.svg").permitAll()
                    .anyRequest().authenticated().and()
                    .formLogin(t -> t.loginPage("/login").successHandler(new AuthenticationSuccessHandler() {
                                                                                      @Override
                                                                                      public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException, ServletException {
                                                                                                System.out.println("AuthenticationSuccessHandler");
     
                                                                                       }
                                                                        })
                                                                       .failureHandler(new AuthenticationFailureHandler() {
                                                                                      @Override
                                                                                      public void onAuthenticationFailure(HttpServletRequest request, HttpServletResponse response, AuthenticationException exception) throws IOException, ServletException {
                                                                                                System.out.println("AuthenticationFailureHandler");
     
                                    													}
                        												})
                            					   .defaultSuccessUrl("/home")
                            					   .failureUrl("/login?error=true").permitAll());
    }
    le problème est qu'avec des bons identifiant/Mot de passe, je ne suis pas redirigé vers l'url "/home" et que le successHandler n'est pas déclanché

    Voici les logs:

    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    48
    49
    50
    51
    52
    53
    54
    55
    56
    57
    58
    59
    60
    61
    62
    63
    64
    65
    66
    67
    68
    69
    70
    71
    72
    73
    74
    75
    76
    77
    78
    79
    80
    81
    82
    83
    84
    85
    86
    87
    88
    89
    90
    91
    92
    93
    94
    95
    96
    97
    98
    99
    100
    101
    102
    103
    104
    105
    106
    107
    108
    109
    110
    111
    112
    113
    114
    115
     
    ************************************************************
     
    Request received for GET '/user':
     
    org.apache.catalina.connector.RequestFacade@7e52d448
     
    servletPath:/user
    pathInfo:null
    headers: 
    host: localhost:8080
    user-agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10.15; rv:88.0) Gecko/20100101 Firefox/88.0
    accept: application/json, text/plain, */*
    accept-language: fr,fr-FR;q=0.8,en-US;q=0.5,en;q=0.3
    accept-encoding: gzip, deflate
    authorization: Basic ZW1haWxAYWRtaW4uZnI6QEFkbWluMQ==
    x-requested-with: XMLHttpRequest
    connection: keep-alive
    referer: http://localhost:8080/login
    cookie: JSESSIONID=46AD2AA8E8BFDFC30CCDBC4B9270FAB4
     
     
    Security filter chain: [
      WebAsyncManagerIntegrationFilter
      SecurityContextPersistenceFilter
      HeaderWriterFilter
      CsrfFilter
      LogoutFilter
      UsernamePasswordAuthenticationFilter
      RequestCacheAwareFilter
      SecurityContextHolderAwareRequestFilter
      AnonymousAuthenticationFilter
      SessionManagementFilter
      ExceptionTranslationFilter
      FilterSecurityInterceptor
    ]
     
     
    ************************************************************
     
     
    2021-05-02 21:18:21.804 DEBUG 3655 --- [nio-8080-exec-6] o.s.security.web.FilterChainProxy        : Securing GET /user
    2021-05-02 21:18:21.804 DEBUG 3655 --- [nio-8080-exec-6] s.s.w.c.SecurityContextPersistenceFilter : Set SecurityContextHolder to empty SecurityContext
    2021-05-02 21:18:21.804 DEBUG 3655 --- [nio-8080-exec-6] o.s.s.w.a.AnonymousAuthenticationFilter  : Set SecurityContextHolder to anonymous SecurityContext
    2021-05-02 21:18:21.804 DEBUG 3655 --- [nio-8080-exec-6] o.s.s.w.session.SessionManagementFilter  : Request requested invalid session id 46AD2AA8E8BFDFC30CCDBC4B9270FAB4
    2021-05-02 21:18:21.805 DEBUG 3655 --- [nio-8080-exec-6] o.s.s.w.a.i.FilterSecurityInterceptor    : Failed to authorize filter invocation [GET /user] with attributes [authenticated]
    2021-05-02 21:18:21.806 DEBUG 3655 --- [nio-8080-exec-6] o.s.s.web.DefaultRedirectStrategy        : Redirecting to http://localhost:8080/login
    2021-05-02 21:18:21.807 DEBUG 3655 --- [nio-8080-exec-6] w.c.HttpSessionSecurityContextRepository : Did not store empty SecurityContext
    2021-05-02 21:18:21.807 DEBUG 3655 --- [nio-8080-exec-6] w.c.HttpSessionSecurityContextRepository : Did not store empty SecurityContext
    2021-05-02 21:18:21.807 DEBUG 3655 --- [nio-8080-exec-6] s.s.w.c.SecurityContextPersistenceFilter : Cleared SecurityContextHolder to complete request
    2021-05-02 21:18:21.900  INFO 3655 --- [nio-8080-exec-7] Spring Security Debugger                 : 
     
    ************************************************************
     
    Request received for GET '/login':
     
    org.apache.catalina.connector.RequestFacade@7e52d448
     
    servletPath:/login
    pathInfo:null
    headers: 
    host: localhost:8080
    user-agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10.15; rv:88.0) Gecko/20100101 Firefox/88.0
    accept: application/json, text/plain, */*
    accept-language: fr,fr-FR;q=0.8,en-US;q=0.5,en;q=0.3
    accept-encoding: gzip, deflate
    authorization: Basic ZW1haWxAYWRtaW4uZnI6QEFkbWluMQ==
    x-requested-with: XMLHttpRequest
    referer: http://localhost:8080/login
    connection: keep-alive
    cookie: JSESSIONID=46AD2AA8E8BFDFC30CCDBC4B9270FAB4
     
     
    Security filter chain: [
      WebAsyncManagerIntegrationFilter
      SecurityContextPersistenceFilter
      HeaderWriterFilter
      CsrfFilter
      LogoutFilter
      UsernamePasswordAuthenticationFilter
      RequestCacheAwareFilter
      SecurityContextHolderAwareRequestFilter
      AnonymousAuthenticationFilter
      SessionManagementFilter
      ExceptionTranslationFilter
      FilterSecurityInterceptor
    ]
     
     
    ************************************************************
     
     
    2021-05-02 21:18:21.903 DEBUG 3655 --- [nio-8080-exec-7] o.s.security.web.FilterChainProxy        : Securing GET /login
    2021-05-02 21:18:21.903 DEBUG 3655 --- [nio-8080-exec-7] s.s.w.c.SecurityContextPersistenceFilter : Set SecurityContextHolder to empty SecurityContext
    2021-05-02 21:18:21.903 DEBUG 3655 --- [nio-8080-exec-7] o.s.s.w.a.AnonymousAuthenticationFilter  : Set SecurityContextHolder to anonymous SecurityContext
    2021-05-02 21:18:21.903 DEBUG 3655 --- [nio-8080-exec-7] o.s.s.w.session.SessionManagementFilter  : Request requested invalid session id 46AD2AA8E8BFDFC30CCDBC4B9270FAB4
    2021-05-02 21:18:21.908 DEBUG 3655 --- [nio-8080-exec-7] o.s.s.w.a.i.FilterSecurityInterceptor    : Authorized filter invocation [GET /login] with attributes [permitAll]
    2021-05-02 21:18:21.908 DEBUG 3655 --- [nio-8080-exec-7] o.s.security.web.FilterChainProxy        : Secured GET /login
    2021-05-02 21:18:21.909 DEBUG 3655 --- [nio-8080-exec-7] o.s.web.servlet.DispatcherServlet        : GET "/login", parameters={}
    2021-05-02 21:18:21.911 DEBUG 3655 --- [nio-8080-exec-7] s.w.s.m.m.a.RequestMappingHandlerMapping : Mapped to com.example.commission.controllers.HelloController#redirect()
    2021-05-02 21:18:21.912 DEBUG 3655 --- [nio-8080-exec-7] o.s.w.s.v.ContentNegotiatingViewResolver : Selected '*/* ' given [application/json, text/plain, */*]
    2021-05-02 21:18:21.912 DEBUG 3655 --- [nio-8080-exec-7] o.s.w.servlet.view.InternalResourceView  : View name 'forward:', model {}
    2021-05-02 21:18:21.913 DEBUG 3655 --- [nio-8080-exec-7] o.s.w.servlet.view.InternalResourceView  : Forwarding to [/]
    2021-05-02 21:18:21.915 DEBUG 3655 --- [nio-8080-exec-7] o.s.web.servlet.DispatcherServlet        : "FORWARD" dispatch for GET "/", parameters={}
    2021-05-02 21:18:21.916 DEBUG 3655 --- [nio-8080-exec-7] o.s.w.s.v.ContentNegotiatingViewResolver : Selected '*/*' given [application/json, text/plain, */*]
    2021-05-02 21:18:21.924 DEBUG 3655 --- [nio-8080-exec-7] o.s.w.servlet.view.InternalResourceView  : View name 'forward:', model {}
    2021-05-02 21:18:21.925 DEBUG 3655 --- [nio-8080-exec-7] o.s.w.servlet.view.InternalResourceView  : Forwarding to [index.html]
    2021-05-02 21:18:21.926 DEBUG 3655 --- [nio-8080-exec-7] o.s.web.servlet.DispatcherServlet        : "FORWARD" dispatch for GET "/index.html", parameters={}
    2021-05-02 21:18:21.927 DEBUG 3655 --- [nio-8080-exec-7] o.s.w.s.handler.SimpleUrlHandlerMapping  : Mapped to ResourceHttpRequestHandler [class path resource [META-INF/resources/], class path resource [resources/], class path resource [static/], class path resource [public/], ServletContext resource [/]]
    2021-05-02 21:18:21.932 DEBUG 3655 --- [nio-8080-exec-7] w.c.HttpSessionSecurityContextRepository : Did not store anonymous SecurityContext
    2021-05-02 21:18:21.933 DEBUG 3655 --- [nio-8080-exec-7] o.s.web.servlet.DispatcherServlet        : Exiting from "FORWARD" dispatch, status 200
    2021-05-02 21:18:21.933 DEBUG 3655 --- [nio-8080-exec-7] o.s.web.servlet.DispatcherServlet        : Exiting from "FORWARD" dispatch, status 200
    2021-05-02 21:18:21.933 DEBUG 3655 --- [nio-8080-exec-7] o.s.web.servlet.DispatcherServlet        : Completed 200 OK
    2021-05-02 21:18:21.933 DEBUG 3655 --- [nio-8080-exec-7] w.c.HttpSessionSecurityContextRepository : Did not store anonymous SecurityContext
    2021-05-02 21:18:21.949 DEBUG 3655 --- [nio-8080-exec-7] s.s.w.c.SecurityContextPersistenceFilter : Cleared SecurityContextHolder to complete request

  3. #3
    Membre actif
    Profil pro
    Inscrit en
    Septembre 2006
    Messages
    728
    Détails du profil
    Informations personnelles :
    Localisation : France

    Informations forums :
    Inscription : Septembre 2006
    Messages : 728
    Points : 250
    Points
    250
    Par défaut
    Bonjour,
    excusez moi du retard de ma réponse, j'ai été très occupé ces derniers temps. J'ai finalement réussi à implémenter la sécurité.
    Voici la configuration de spring security

    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
     
    @Configuration
    @EnableWebSecurity(debug = true)
    public class WebSecurityConfig  extends WebSecurityConfigurerAdapter {
     
     
        private final ObjectMapper objectMapper = new ObjectMapper();
     
        @Autowired
        private CustomUserDetailsService userDetailsService;
     
     
     
        @Autowired
        @Qualifier("passwordEncoder")
        public BCryptPasswordEncoder bCryptPasswordEncoder;
     
     
        @Override
        protected void configure(AuthenticationManagerBuilder auth)
                throws Exception {
            auth.authenticationProvider(authenticationProvider());
        }
     
        @Bean
        public DaoAuthenticationProvider authenticationProvider() {
            DaoAuthenticationProvider authProvider
                    = new DaoAuthenticationProvider();
            authProvider.setUserDetailsService(userDetailsService);
            authProvider.setPasswordEncoder(bCryptPasswordEncoder);
            return authProvider;
        }
     
     
     
        @Override
        protected void configure(HttpSecurity http) throws Exception {
            http
                    .authorizeRequests()
                    .antMatchers("/index.html", "/", "/home", "/login", "/**/*.css",  "/*.js", "/*.ico", "/**/*.svg").permitAll()
                    .anyRequest().authenticated().and()
                    .formLogin(t -> t.loginPage("/login")
                    .defaultSuccessUrl("/")
                    .failureUrl("/login?error=true").permitAll()).httpBasic();
     
        }
    }
    Voici mon UserDetailsService
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
     
    @Service
    public class CustomUserDetailsService implements UserDetailsService {
     
        @Autowired
        private UserRepository userRepository;
     
        @Override
        public UserDetails loadUserByUsername(String username) {
            User user = userRepository.findByUsername(username);
            // checking if user exists and converting into UserDetails
            //...
            if (user == null) {
                throw new UsernameNotFoundException("User not found with login: " + username);
            }
     
            return new org.springframework.security.core.userdetails.User(
                    user.getUsername(), user.getPassword(), user.isEnabled(), user.isAccountNonExpired(), user.isCredentialsNonExpired(),
                    user.isAccountNonLocked(), getRolesAuthorities(user.getRoles()));
        }
     
        private Collection<? extends GrantedAuthority> getRolesAuthorities(
                Collection<Authority> roles) {
            List<GrantedAuthority> authorities = new ArrayList<GrantedAuthority>();
            for (Authority role :roles) {
                authorities.add(new SimpleGrantedAuthority(role.getAuthorityKey().getAuthority()));
            }
     
            return authorities;
        }
    }
    Voici mon controller de Login
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
     
    @CrossOrigin(origins = "http://localhost:4200")
    @RequestMapping("/api")
    public class LoginController {
     
        Logger logger = LoggerFactory.getLogger(LoginController.class);
     
     
        @GetMapping("/login")
        @ResponseBody
        public Principal user(Principal user) {
            Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
            if (!(authentication instanceof AnonymousAuthenticationToken)) {
                String currentUserName = authentication.getName();
                return user;
            }
            return null;
        }
        }
    Voici ma définition de routes angular
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
     
    const routes: Routes = [
      { path: '', component: HomeComponent, canActivate: [AuthGuard] },
      { path: 'login', component: LoginComponent },
      { path: '**', redirectTo: '' }
    ];
     
    @NgModule({
      imports: [RouterModule.forRoot(routes,
          { enableTracing: false })],
      exports: [RouterModule]
    })
    export class AppRoutingModule { }
    Et voici la méthode appelé quand je clique sur le bouton LOGIN de ma page de login
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
     
      authenticate(credentials, callback) {
            const headers = new HttpHeaders(credentials ? {
                authorization : 'Basic ' + btoa(credentials.username + ':' + credentials.password)
            } : {});
     
            this.http.get('api/login', {headers: headers}).subscribe(response => {
                if (response['name']) {
                    this.authenticated = true;
                } else {
                    this.authenticated = false;
                }
                return callback && callback();
            });
     
        }

+ Répondre à la discussion
Cette discussion est résolue.

Discussions similaires

  1. Réponses: 5
    Dernier message: 20/12/2015, 22h27
  2. [Débutant] Méthode n'est pas valide dans le contexte donné
    Par Blodsvept dans le forum C#
    Réponses: 9
    Dernier message: 23/06/2015, 09h48
  3. Réponses: 1
    Dernier message: 19/04/2014, 18h54
  4. iReport Wizard n'est pas affiché dans fichier>..
    Par yacine.dev dans le forum Jasper
    Réponses: 1
    Dernier message: 02/03/2010, 19h46
  5. la police wingdings n'est pas affichée dans FF ni safari ?
    Par Ekimasu dans le forum Balisage (X)HTML et validation W3C
    Réponses: 2
    Dernier message: 08/01/2009, 11h31

Partager

Partager
  • Envoyer la discussion sur Viadeo
  • Envoyer la discussion sur Twitter
  • Envoyer la discussion sur Google
  • Envoyer la discussion sur Facebook
  • Envoyer la discussion sur Digg
  • Envoyer la discussion sur Delicious
  • Envoyer la discussion sur MySpace
  • Envoyer la discussion sur Yahoo