Jonathan Ato Markin
Jonathan Ato Markin

Reputation: 61

Spring Security JDBC Authentication with Custom Username and Password Queries

I am new to Spring Security and trying to implement it in my application. The database has already been established and has a different schema from the default. The passwords have been hashed with an Oracle DB hashing scheme.

Here lies my problem. I want to be able to pass custom queries to fetch the username and also has the incoming password before comparing it to what is in the database. how do I go about that?

Upvotes: 0

Views: 543

Answers (1)

Vallabh Vaidya
Vallabh Vaidya

Reputation: 330

You can customize the authentication logic by implementing custom UserDetailsService and overriding its loadUserByUsername() method.

public interface MembersService extends UserDetailsService {}

@Service
public class MembersServiceImpl implements MemberService{
    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {

        //custom logic to authenticate  
        throw new UsernameNotFoundException("User '" + username + "' not found");
    }

}

Set this custom user details service in security configuration

@Configuration
public class WebSecurityConfiguration extends WebSecurityConfigurerAdapter {

    private MembersService memberService;

    public WebSecurityConfiguration(MembersService memberService) {
        this.memberService = memberService;
    }

@Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.userDetailsService(this.memberService).passwordEncoder(encoder());
    }

}

Upvotes: 1

Related Questions