Search code examples
spring-bootspring-securityoauth-2.0spring-jdbc

How to Change jdbc schema users with mytable in OAuth2 spring boot


I have to change the name of default schema users with mytable name.


    @Configuration
    @EnableAuthorizationServer
    public class AuthorizationServerConfig extends AuthorizationServerConfigurerAdapter {
        
        @Autowired
        private AuthenticationManager authenticationManager;
        
        @Autowired
        private PasswordEncoder passwordEncoder;
        
        @Autowired
        private DataSource dataSource;
        
        @Bean
        TokenStore jdbcTokenStore() {
            return new JdbcTokenStore(dataSource);
        }
        
        @Override
        public void configure(AuthorizationServerEndpointsConfigurer endpoints) throws Exception {
            endpoints.tokenStore(jdbcTokenStore());
            endpoints.authenticationManager(authenticationManager);
        }
        
        @Override
        public void configure(ClientDetailsServiceConfigurer clients) throws Exception {
            clients.jdbc(dataSource);
        }
        
        @Override
        public void configure(AuthorizationServerSecurityConfigurer security) throws Exception {
            security.tokenKeyAccess("permitAll()").checkTokenAccess("isAuthenticated()");
        }
        
    }

this is my securityConfig class


@Configuration
@EnableWebSecurity
public class SecurityConfiguration extends WebSecurityConfigurerAdapter {

    @Autowired
    private DataSource dataSource;

    @Override
    @Bean
    public AuthenticationManager authenticationManagerBean() throws Exception {
        return super.authenticationManagerBean();
    }

    @Bean
    public UserDetailsService userDetailsService(DataSource dataSource) {
        JdbcUserDetailsManager jdbcUserDetailsManager = new JdbcUserDetailsManager(dataSource);
        jdbcUserDetailsManager.setUsersByUsernameQuery("select USER_LOGIN_ID,USER_PASSWORD "
                + "from MY_TABLE "
                + "where USER_LOGIN_ID = ?");

        return jdbcUserDetailsManager;
    }

    @Bean
    public PasswordEncoder getPasswordEncoder() {
        return NoOpPasswordEncoder.getInstance();
    }

    @Bean
    GrantedAuthorityDefaults grantedAuthorityDefaults() {
        return new GrantedAuthorityDefaults(""); // Remove the ROLE_ prefix
    }
}

this is my resouceserver


@Configuration
@EnableResourceServer
public class ResourceServerConfiguration extends ResourceServerConfigurerAdapter {

    @Override
    public void configure(HttpSecurity http) throws Exception {
        http
                .authorizeRequests()
                .antMatchers("/").permitAll()
                .antMatchers("/secure").authenticated();
    }

}

and i have create customer table here

which ius here

@Entity
@Table(name = "MY_TABLE")
public class MyTable {

    @Column(name = "USER_LOGIN_ID", nullable = false, unique = true)
    private String userLoginId;
    @Column(name = "USER_PASSWORD", nullable = false)
    private String userPassword;
}

here url which i use.

http://localhost:8081/oauth/token?grant_type=password&username=user&password=user

and it is throwing error

{ "timestamp": 1621689938591, "status": 401, "error": "Unauthorized", "message": "Unauthorized", "path": "/oauth/token" }


Solution

  • To use your own table you have to authenticationmanager to read user from that table like below. It should be able to provide user and authority details. You can create your own configuration class which extends WebSecurityConfigurerAdapter and override configure method like below.

     @Override
        protected void configure(AuthenticationManagerBuilder auth) throws Exception {
            auth.jdbcAuthentication()
                       .dataSource(dataSource)
                       .usersByUsernameQuery("select userid,password,enabled "
                         + "from yourtable"
                         + "where userid = ?")
                       .authoritiesByUsernameQuery("select userid,authority "
                        + "from yourauthoritytable"
                        + "where userid= ?");
        }