Search code examples
angularspring-bootauthenticationspring-securityrestful-authentication

how can i add a rest angular custom login page to spring app using DaoAuthenticationProvider


i am making an full-stack web application using angular , spring boot and database in witch i there is a login form for admin and users i defined the roles for both. based on a tutorial that i found i created the spring boot login configuration and it works now i need to link it to my angular app but i am stack i don't know how can i set the angular form instead of the one provided with angular because they are not in the same application and i have been using REST Controllers between them .so is it possible for me to do so if yes how can i. here is the code for the login configuration

@Configuration
@EnableWebSecurity
public class SecurityConfiguration extends WebSecurityConfigurerAdapter {

private UserprincipalDetailSerice userprincipalDetailSerice;
 public SecurityConfiguration(UserprincipalDetailSerice userprincipalDetailSerice){
     this.userprincipalDetailSerice=userprincipalDetailSerice;
 }

    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.authenticationProvider(authenticationProvider());

    }

@Bean
    DaoAuthenticationProvider authenticationProvider(){
        DaoAuthenticationProvider daoAuthenticationProvider =new DaoAuthenticationProvider();
         daoAuthenticationProvider.setPasswordEncoder(passwordEncoder());
         daoAuthenticationProvider.setUserDetailsService(this.userprincipalDetailSerice);
return daoAuthenticationProvider;
 }
    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http
                .cors()
                .and()
                .authorizeRequests().antMatchers("/allproduits/**").permitAll()
                .antMatchers("/getallusers/personnels").hasAnyRole("ADMIN","ANY")
                .antMatchers("/getallusers/personnelsbyid/{id}").hasAnyRole("ADMIN","ANY")
                .antMatchers("/getallusers/updatepersonnel").hasAnyRole("ADMIN","ANY")
                .antMatchers("/getallusers/deletepersonnel/{id}").hasAnyRole("ADMIN")
                .antMatchers("/getallusers/encode").permitAll()
                .antMatchers("/getallusers/addcpersonnel").hasRole("ADMIN")
                .antMatchers("/getallcadres/**").hasAnyRole("ADMIN","ANY")
                .and()
                .httpBasic()
                .and()

                .csrf().disable();
      //  http.csrf().csrfTokenRepository(this.csrfRepo());

    }

    @Override
    public void configure(WebSecurity web ) throws Exception
    {
        web.ignoring().antMatchers( HttpMethod.OPTIONS, "/**" );
    }




    @Bean
    CorsConfigurationSource corsConfigurationSource() {
        CorsConfiguration configuration = new CorsConfiguration();
        configuration.setAllowedOrigins(Arrays.asList("*"));
        configuration.setAllowedMethods(Arrays.asList("GET", "POST", "PUT", "PATCH", "DELETE", "OPTIONS"));
        configuration.setAllowedHeaders(Arrays.asList("authorization", "content-type", "x-auth-token"));
        configuration.setExposedHeaders(Arrays.asList("x-auth-token"));
        UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
        source.registerCorsConfiguration("/**", configuration);
        return source;
    }

    @Bean
   public PasswordEncoder passwordEncoder() {
        return new BCryptPasswordEncoder();
    }
}

UserDetailsService class:

@Service
public class UserprincipalDetailSerice implements UserDetailsService {

   private personnelReposotry personnelReposotry;
   public UserprincipalDetailSerice(personnelReposotry pR){
this.personnelReposotry=pR;
   }
    @Override
    public UserDetails loadUserByUsername(String s) throws UsernameNotFoundException {
        personnel personnel=this.personnelReposotry.findByMatricule(s);
        UserPrincipal userPrincipal=new UserPrincipal(personnel);
        System.out.println(personnel.getMatricule()+personnel.getPsw()+"role:"+personnel.getRole());
        return userPrincipal;
    }
}

UserDetails class :

public class UserPrincipal implements UserDetails {
    private personnel personnel;
    public UserPrincipal(personnel personnel){
        this.personnel=personnel;
    }
    @Override
    public Collection<? extends GrantedAuthority> getAuthorities() {
        List<GrantedAuthority> authorities= new ArrayList<>();
        this.personnel.getRoleList().forEach(p->{
            GrantedAuthority authority = new SimpleGrantedAuthority("ROLE_" +p)  ;
            authorities.add(authority);

        });


        return authorities;
    }

    @Override
    public String getPassword() {
        return this.personnel.getPsw();
    }

    @Override
    public String getUsername() {
        return this.personnel.getMatricule();
    }

    @Override
    public boolean isAccountNonExpired() {
        return true;
    }

    @Override
    public boolean isAccountNonLocked() {
        return true;
    }

    @Override
    public boolean isCredentialsNonExpired() {
        return true;
    }

    @Override
    public boolean isEnabled() {
        return true;
    }
}

Solution

  • Your current code may work for a standalone application, but not for this situation. You can instead use that code to return a secret JWT(JSON Web Token) when an authentication is successful, that the user can later send with each request, there are plenty of tutorials on the internet.