Как я могу добавить отдых пользовательские страницы входа в приложение Spring с помощью DaoAuthenticationProvider - PullRequest
0 голосов
/ 31 мая 2019

Я делаю веб-приложение с полным стеком, используя angular, spring boot и базу данных, в которой есть форма входа для администратора и пользователей, я определил роли для обоих. основываясь на учебнике, который я обнаружил, я создал конфигурацию входа в систему с пружинной загрузкой, и теперь она работает. Мне нужно связать ее с моим угловым приложением, но я работаю в стеке. Я не знаю, как установить угловую форму вместо той, которая предоставляется с угловым потому что они не в том же приложении, и я использую контроллеры REST между ними. так что я могу сделать это, если да, как я могу. вот код для конфигурации входа в систему

@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:

@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:

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

1 Ответ

1 голос
/ 31 мая 2019

Ваш текущий код может работать для автономного приложения, но не для этой ситуации.Вместо этого вы можете использовать этот код для возврата секретного JWT (JSON Web Token) при успешной аутентификации, который пользователь может позже отправить с каждым запросом, в Интернете есть множество учебных пособий.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...