WordPress user Authentication

After researching and looking up the WordPress Codex, this is the code that I have used to authenticate..

I hope this helpful to all friends .it’s working fine for me 🙂

 $creds = array(
    'user_login'    => $username,
    'user_password' => $userpassword,
    'remember'      => true
 );
 
 if(!empty($username) && !empty($userpassword)) {
    
    if(!username_exists($username)) {

        $userdata = array(
            'user_login'  =>  $username,
            'user_email'  =>  $useremail, 
            'user_pass'   =>  $userpassword, 
            'role'        =>  'customer' 
        );

        $user_id = wp_insert_user( $userdata ) ; 
        
        $user = wp_signon( $creds, false );
        wp_set_current_user($user->ID,$username); 
        wp_set_auth_cookie($user->ID, true, false );  

        wp_redirect(site_url()); 
        
 
    }