Ошибка WebSecurityConfiguration в Java SpringBoot, не распознает мой пользовательский конструктор - PullRequest
1 голос
/ 24 февраля 2020

Я создаю Java SpringBoot (Back-End), Vuejs (front) application и im в этой части настройки приложения веб-безопасности. В моем пользовательском классе конструктор может выглядеть следующим образом:

package com.miniAmazon;


import org.hibernate.annotations.GenericGenerator;
import org.springframework.security.core.GrantedAuthority;

import javax.persistence.*;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

@Entity
public class User {
    @Id
    @GeneratedValue(strategy = GenerationType.AUTO,generator = "native")
    @GenericGenerator(name="native",strategy="native")
    private Long id;

    @OneToMany(mappedBy = "users",fetch= FetchType.EAGER)
    Set<Product> productsSet= new HashSet<>();

    @OneToMany(mappedBy="users", fetch=FetchType.EAGER)
    Set<Purchase> purchaseSet=new HashSet<>();

    private String userRole;
    private String userName;
    private String userEmail;
    private String userPassword;

    public User(){}
    public User( String userEmail,String userName,String userPassword,String userRole){
       this.userName=userName;
       this.userEmail=userEmail;
       this.userPassword=userPassword;
       this.userRole=userRole;
    }
    public void addPurchase(Purchase purchase){ purchaseSet.add(purchase);}
    public Set<Purchase>getUserPurchaseSet(){
        return purchaseSet;
    }



    ////////////////////////////////////////////setter/////////////////////////////////////////////

    ///////////////////////////////////////////getters////////////////////////////////////////////////

    ///////////////////////////////////////////////////////////////////////////////////////////
    @Override
       xxxxx
    }


}

хранилище пользователя выглядит так:

package com.miniAmazon;

import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.rest.core.annotation.RepositoryRestResource;

@RepositoryRestResource
public interface UserRepository extends JpaRepository<User,String> {
    User findByuserName (String usertName);
}

и код приложения веб-безопасности был определен следующим образом:

package com.miniAmazon;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.authentication.configuration.GlobalAuthenticationConfigurerAdapter;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.factory.PasswordEncoderFactories;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.web.WebAttributes;
import org.springframework.security.web.authentication.logout.HttpStatusReturningLogoutSuccessHandler;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.util.Arrays;
import java.util.Date;

@SpringBootApplication
public class DemoApplication {

    public static void main(String[] args) {
        SpringApplication.run(DemoApplication.class, args);
    }
    @Bean
    public PasswordEncoder passwordEncoder(){
        return PasswordEncoderFactories.createDelegatingPasswordEncoder();
    }
    @Bean
    public CommandLineRunner initData(ProductRepository productRepository, UserRepository userRepository, PurchaseRepository purchaseRepository){
        return(args)->{


            User user1=new User("lolo@gmail.com","lolo gomex",passwordEncoder().encode("24"),"buyer");
            User user2=new User("jhony@gmail.com","Jack Ripper",passwordEncoder().encode("mole"),"buyer");
            User user3=new User("gothic@gmail.com","demo gago",passwordEncoder().encode("adu"),"seller");
            User user4=new User("grau@gmail.com","grau gomex",passwordEncoder().encode("24"),"seller");
            User user5=new User("goiy@gmail.com","divan Ripper",passwordEncoder().encode("mole"),"buyer");
            User user6=new User("gatti@gmail.com","guti gago",passwordEncoder().encode("adu"),"admin");

            userRepository.save(user1);
            userRepository.save(user2);
            userRepository.save(user3);
            userRepository.save(user4);
            userRepository.save(user5);
            userRepository.save(user6);



        };
    }
}
@Configuration
@EnableWebSecurity
class WebSecurityConfiguration extends GlobalAuthenticationConfigurerAdapter {
    @Autowired
    UserRepository userRepository;
    @Override
    public void init(AuthenticationManagerBuilder auth) throws Exception {
        auth.userDetailsService(inputName-> {
            User user =userRepository.findByuserName(inputName);
            if (user != null) {
                return new User(user.getUserName(), user.getUserPassword(),
                        AuthorityUtils.createAuthorityList("USER"));--------------------ERROR
            } else {
                throw new UsernameNotFoundException("Unknown user: " + inputName);
            }
        });
    }
}
@Configuration
@EnableWebSecurity
class WebSecurityConfig extends WebSecurityConfigurerAdapter {
    @Override
    protected void configure(HttpSecurity http) throws Exception {
//      http.cors();///de heroku tambien
        http.authorizeRequests()
                .antMatchers("/mini/all_products").permitAll()
                .antMatchers("mini/all_products/user_dashboard/purchase/{id}").permitAll()
                .antMatchers("/mini/all_product/registering").permitAll()
                .antMatchers("/h2-console/**").permitAll()
                .antMatchers("/rest/**").hasAuthority("ADMIN")
                .antMatchers("/**").hasAuthority("USER")
                .anyRequest().fullyAuthenticated();
        /////Autorizaciones y permisos para los distintos niveles de seguridad que tendria el usuario segun su casificacion
        http.formLogin()
                .usernameParameter("name")
                .passwordParameter("password")
                .loginPage("/api/login");
//
        http.logout().logoutUrl("/api/logout");

        http.csrf().disable();

        http.exceptionHandling().authenticationEntryPoint((req, res, exc) -> res.sendError(HttpServletResponse.SC_UNAUTHORIZED));

        http.formLogin().successHandler((req, res, auth) -> clearAuthenticationAttributes(req));

        http.formLogin().failureHandler((req, res, exc) -> res.sendError(HttpServletResponse.SC_UNAUTHORIZED));

        http.logout().logoutSuccessHandler(new HttpStatusReturningLogoutSuccessHandler());
//        http.headers().frameOptions().disable();
        http.headers().frameOptions().sameOrigin();
    }

    private void clearAuthenticationAttributes(HttpServletRequest request) {
        HttpSession session = request.getSession(false);
        if (session != null) {
            session.removeAttribute(WebAttributes.AUTHENTICATION_EXCEPTION);
        }
    }
}

, но постоянно выдает мне ошибку в первой конфигурации WebSecurityConnant в новом конструкторе нового пользователя, говоря, что когда я наведу на него курсор

Cannot resolve constructor 'User(java.lang.String, java.lang.String, java.util.List<org.springframework.security.core.GrantedAuthority>)'

Любая идея о том, почему это происходит. весь этот код !! И заранее спасибо !!!

Ответы [ 2 ]

1 голос
/ 26 февраля 2020

Вы должны вернуть org.springframework.security.core.userdetails.User вместо com.miniAmazon.User:

        if (user != null) {
            return new org.springframework.security.core.userdetails.User(user.getUserName(), user.getUserPassword(),
                    AuthorityUtils.createAuthorityList("USER"));
        } else {
            throw new UsernameNotFoundException("Unknown user: " + inputName);
        }

, поскольку метод loadUserByUsername из UserDetailsService возвращает экземпляр org.springframework.security.core.userdetails.UserDetails, а org.springframework.security.core.userdetails.User реализует org.springframework.security.core.userdetails.UserDetails.

public interface UserDetailsService {
    UserDetails loadUserByUsername(String username) throws UsernameNotFoundException;
}
0 голосов
/ 26 февраля 2020

Я проверил ваш код. В вашем WebSecurityConfig классе

public void init(AuthenticationManagerBuilder auth) throws Exception {
        auth.userDetailsService(inputName-> {
            User user =userRepository.findByuserName(inputName);
            if (user != null) {
                return new User(user.getUserName(), user.getUserPassword(),
                        AuthorityUtils.createAuthorityList("USER"));--------------------ERROR
            } 
        });
    }

Вы возвращаете объект пользователя следующим образом:

return new User(user.getUserName(), 
                user.getUserPassword(),
                AuthorityUtils.createAuthorityList("USER"));

, что неверно. Потому что вы создали конструктор с другим аргументом:

public User(String userEmail,
            String userName,
            String userPassword,
            String userRole);

Так что передавайте аргументы правильно. Это будет работать.

Вы также можете вернуться так:

return new User(null, user.getUserName(), user.getUserPassword(),
                        AuthorityUtils.createAuthorityList("USER"));
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...