简体   繁体   中英

custom login with JPA and spring security

I have been trying to authenticate my service by spring security. For that I am using filter as

This is the Security configuration I have been Using: In this configuration I am filtering all requests and permitting all , by authentication. For Authentication I have login page. In the login form I have use 'username' for email and 'password' for password for the attribute names respectively.

public class LoginAuthenticate  extends WebSecurityConfigurerAdapter{

    @Autowired
    @Qualifier("userDetailsService")
    MyUserDetailService userDetailsService;     

   @Autowired
   @Override
   public void configure(AuthenticationManagerBuilder auth) throws Exception {
       auth.userDetailsService(userDetailsService).passwordEncoder(passwordEncoder());
       System.out.println("reaching");
   }        

    @Override
    protected void configure(HttpSecurity http) throws Exception{
        http.authorizeRequests()
        .antMatchers("/resources/**").permitAll() 
        .anyRequest().authenticated()
      .and()
      .formLogin()
          .loginPage("/login")
          .usernameParameter("username")
          .passwordParameter("password")
          .defaultSuccessUrl("/success")
          .failureUrl("/")
          .permitAll()
          .and()
      .logout()
          .permitAll().and().csrf().disable();
    }
    @Bean
    public PasswordEncoder passwordEncoder(){
        PasswordEncoder encoder = new BCryptPasswordEncoder();
        return encoder;
    }

This is my program structure

程序结构

And for implementing UserDEtailService I did the following

This is my UserDetailsService which I overrided, I have autowired the repository to get the email address and password from the database[ using email as username] and then created a userdetails user object with the username and password and returned that object. When the use inputs the username and password in login page then I should be able to authenticate using the details with the details pulled from the database like the email and password of the user should match the email and password retrieved from the db.But the problem is I couldnt fire the authenticate method in spring security configuration:

@Service("userDetailsService")
public class MyUserDetailService implements UserDetailsService{
@Autowired  
 IUsers userrepo;

        @Override
        public UserDetails loadUserByUsername(String username)
                throws UsernameNotFoundException {
            User user = userrepo.finduserByUserName(username);
            if (user == null) {
                return null;
            }
            List<GrantedAuthority> auth = AuthorityUtils
                    .commaSeparatedStringToAuthorityList("ROLE_USER");
            if (username.equals("admin")) {
                auth = AuthorityUtils
                        .commaSeparatedStringToAuthorityList("ROLE_ADMIN");
            }
            String password = user.getLoginPassword();
            String Email = user.getEmailAddress();
            System.out.println(password+ " "+ Email);
            return new org.springframework.security.core.userdetails.User(Email,password,auth);
}
}

But My authentication function is not evaluating the user!

Can someone help me what is going wrong here. There are no errors to debug. I consoled out if reaching authentication function , but not reaching. I tried every possible thing on internet on this custom login with JPA but my effort didn't turn up anything to be fruitful.

In class LoginAuthenticate:
remove @Autowired before void configure(AuthenticationManagerBuilder auth) ,
add annotation for this class

@Configuration    
@EnableWebSecurity


In class MyUserDetailService.loadUserByUsername:
change

if (user == null) {
      return null;
}

to

if (user == null) {
      throw new UsernameNotFoundException ("User not found");
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM