Spring boot security REST basic authentication from database












3















I have a problem where when I use basic authentication with inMemoryAuthentication as in the following snippet, it works perfectly.



@Configuration
public class SecurityConfig extends WebSecurityConfigurerAdapter {

@Autowired
DataSource dataSource;

@Autowired
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
auth.inMemoryAuthentication()
.withUser("user1").password("secret1").roles("USER")
.and()
.withUser("admin").password("123456").roles("ADMIN");
}

@Override
protected void configure(HttpSecurity http) throws Exception {
http.httpBasic().and().authorizeRequests().antMatchers("/**").hasRole("ADMIN").and()
.csrf().disable().headers().frameOptions().disable();
}

}


but when I try to use get database to get userdata that will be used for authentication it doesn't work and just sends back a 403 response.



@Configuration
public class SecurityConfig extends WebSecurityConfigurerAdapter {

@Autowired
DataSource dataSource;//MySQL db via JPA

@Autowired
protected void configureGlobal(AuthenticationManagerBuilder auth) throws Exception{
auth.jdbcAuthentication().dataSource(dataSource).usersByUsernameQuery("select username, password, 1 as enabled from user where username=?")
.authoritiesByUsernameQuery("select username, role from user where username=?");
}

@Override
protected void configure(HttpSecurity http) throws Exception {
http.httpBasic().and().authorizeRequests().antMatchers("/**").hasRole("ADMIN").and()
.csrf().disable().headers().frameOptions().disable();

}

}


now, this is the case only with a Spring-Boot REST application, I've tried the same method in a Spring MVC application and a /login page and it worked with both inMemoryAuthentication and jdbcAuthentication.










share|improve this question























  • It seems that authentication processes is performed but without successful, in that case, could you provide the code of how is the rest service consumed?

    – Daniel C.
    Sep 9 '17 at 1:11











  • it's consumed via classes annotated with @RestController, if that's what you mean. the same methodology is used in other projects -without security- and it just works

    – Sherbi7y
    Sep 9 '17 at 15:06













  • Sorry I didn't explain myself correctly. I mean, if the access to the rest service is through web browser or using a custom client code or other tool like curl?

    – Daniel C.
    Sep 9 '17 at 15:55











  • I use PostMan and chrome to do the testing, in PM I just sent the authentication data with the request. in chrome I type down the URL, wait for the login pop-up, and fill in the authentication data.

    – Sherbi7y
    Sep 9 '17 at 16:49
















3















I have a problem where when I use basic authentication with inMemoryAuthentication as in the following snippet, it works perfectly.



@Configuration
public class SecurityConfig extends WebSecurityConfigurerAdapter {

@Autowired
DataSource dataSource;

@Autowired
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
auth.inMemoryAuthentication()
.withUser("user1").password("secret1").roles("USER")
.and()
.withUser("admin").password("123456").roles("ADMIN");
}

@Override
protected void configure(HttpSecurity http) throws Exception {
http.httpBasic().and().authorizeRequests().antMatchers("/**").hasRole("ADMIN").and()
.csrf().disable().headers().frameOptions().disable();
}

}


but when I try to use get database to get userdata that will be used for authentication it doesn't work and just sends back a 403 response.



@Configuration
public class SecurityConfig extends WebSecurityConfigurerAdapter {

@Autowired
DataSource dataSource;//MySQL db via JPA

@Autowired
protected void configureGlobal(AuthenticationManagerBuilder auth) throws Exception{
auth.jdbcAuthentication().dataSource(dataSource).usersByUsernameQuery("select username, password, 1 as enabled from user where username=?")
.authoritiesByUsernameQuery("select username, role from user where username=?");
}

@Override
protected void configure(HttpSecurity http) throws Exception {
http.httpBasic().and().authorizeRequests().antMatchers("/**").hasRole("ADMIN").and()
.csrf().disable().headers().frameOptions().disable();

}

}


now, this is the case only with a Spring-Boot REST application, I've tried the same method in a Spring MVC application and a /login page and it worked with both inMemoryAuthentication and jdbcAuthentication.










share|improve this question























  • It seems that authentication processes is performed but without successful, in that case, could you provide the code of how is the rest service consumed?

    – Daniel C.
    Sep 9 '17 at 1:11











  • it's consumed via classes annotated with @RestController, if that's what you mean. the same methodology is used in other projects -without security- and it just works

    – Sherbi7y
    Sep 9 '17 at 15:06













  • Sorry I didn't explain myself correctly. I mean, if the access to the rest service is through web browser or using a custom client code or other tool like curl?

    – Daniel C.
    Sep 9 '17 at 15:55











  • I use PostMan and chrome to do the testing, in PM I just sent the authentication data with the request. in chrome I type down the URL, wait for the login pop-up, and fill in the authentication data.

    – Sherbi7y
    Sep 9 '17 at 16:49














3












3








3


1






I have a problem where when I use basic authentication with inMemoryAuthentication as in the following snippet, it works perfectly.



@Configuration
public class SecurityConfig extends WebSecurityConfigurerAdapter {

@Autowired
DataSource dataSource;

@Autowired
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
auth.inMemoryAuthentication()
.withUser("user1").password("secret1").roles("USER")
.and()
.withUser("admin").password("123456").roles("ADMIN");
}

@Override
protected void configure(HttpSecurity http) throws Exception {
http.httpBasic().and().authorizeRequests().antMatchers("/**").hasRole("ADMIN").and()
.csrf().disable().headers().frameOptions().disable();
}

}


but when I try to use get database to get userdata that will be used for authentication it doesn't work and just sends back a 403 response.



@Configuration
public class SecurityConfig extends WebSecurityConfigurerAdapter {

@Autowired
DataSource dataSource;//MySQL db via JPA

@Autowired
protected void configureGlobal(AuthenticationManagerBuilder auth) throws Exception{
auth.jdbcAuthentication().dataSource(dataSource).usersByUsernameQuery("select username, password, 1 as enabled from user where username=?")
.authoritiesByUsernameQuery("select username, role from user where username=?");
}

@Override
protected void configure(HttpSecurity http) throws Exception {
http.httpBasic().and().authorizeRequests().antMatchers("/**").hasRole("ADMIN").and()
.csrf().disable().headers().frameOptions().disable();

}

}


now, this is the case only with a Spring-Boot REST application, I've tried the same method in a Spring MVC application and a /login page and it worked with both inMemoryAuthentication and jdbcAuthentication.










share|improve this question














I have a problem where when I use basic authentication with inMemoryAuthentication as in the following snippet, it works perfectly.



@Configuration
public class SecurityConfig extends WebSecurityConfigurerAdapter {

@Autowired
DataSource dataSource;

@Autowired
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
auth.inMemoryAuthentication()
.withUser("user1").password("secret1").roles("USER")
.and()
.withUser("admin").password("123456").roles("ADMIN");
}

@Override
protected void configure(HttpSecurity http) throws Exception {
http.httpBasic().and().authorizeRequests().antMatchers("/**").hasRole("ADMIN").and()
.csrf().disable().headers().frameOptions().disable();
}

}


but when I try to use get database to get userdata that will be used for authentication it doesn't work and just sends back a 403 response.



@Configuration
public class SecurityConfig extends WebSecurityConfigurerAdapter {

@Autowired
DataSource dataSource;//MySQL db via JPA

@Autowired
protected void configureGlobal(AuthenticationManagerBuilder auth) throws Exception{
auth.jdbcAuthentication().dataSource(dataSource).usersByUsernameQuery("select username, password, 1 as enabled from user where username=?")
.authoritiesByUsernameQuery("select username, role from user where username=?");
}

@Override
protected void configure(HttpSecurity http) throws Exception {
http.httpBasic().and().authorizeRequests().antMatchers("/**").hasRole("ADMIN").and()
.csrf().disable().headers().frameOptions().disable();

}

}


now, this is the case only with a Spring-Boot REST application, I've tried the same method in a Spring MVC application and a /login page and it worked with both inMemoryAuthentication and jdbcAuthentication.







java spring spring-boot spring-security spring-rest






share|improve this question













share|improve this question











share|improve this question




share|improve this question










asked Sep 8 '17 at 20:24









Sherbi7ySherbi7y

335




335













  • It seems that authentication processes is performed but without successful, in that case, could you provide the code of how is the rest service consumed?

    – Daniel C.
    Sep 9 '17 at 1:11











  • it's consumed via classes annotated with @RestController, if that's what you mean. the same methodology is used in other projects -without security- and it just works

    – Sherbi7y
    Sep 9 '17 at 15:06













  • Sorry I didn't explain myself correctly. I mean, if the access to the rest service is through web browser or using a custom client code or other tool like curl?

    – Daniel C.
    Sep 9 '17 at 15:55











  • I use PostMan and chrome to do the testing, in PM I just sent the authentication data with the request. in chrome I type down the URL, wait for the login pop-up, and fill in the authentication data.

    – Sherbi7y
    Sep 9 '17 at 16:49



















  • It seems that authentication processes is performed but without successful, in that case, could you provide the code of how is the rest service consumed?

    – Daniel C.
    Sep 9 '17 at 1:11











  • it's consumed via classes annotated with @RestController, if that's what you mean. the same methodology is used in other projects -without security- and it just works

    – Sherbi7y
    Sep 9 '17 at 15:06













  • Sorry I didn't explain myself correctly. I mean, if the access to the rest service is through web browser or using a custom client code or other tool like curl?

    – Daniel C.
    Sep 9 '17 at 15:55











  • I use PostMan and chrome to do the testing, in PM I just sent the authentication data with the request. in chrome I type down the URL, wait for the login pop-up, and fill in the authentication data.

    – Sherbi7y
    Sep 9 '17 at 16:49

















It seems that authentication processes is performed but without successful, in that case, could you provide the code of how is the rest service consumed?

– Daniel C.
Sep 9 '17 at 1:11





It seems that authentication processes is performed but without successful, in that case, could you provide the code of how is the rest service consumed?

– Daniel C.
Sep 9 '17 at 1:11













it's consumed via classes annotated with @RestController, if that's what you mean. the same methodology is used in other projects -without security- and it just works

– Sherbi7y
Sep 9 '17 at 15:06







it's consumed via classes annotated with @RestController, if that's what you mean. the same methodology is used in other projects -without security- and it just works

– Sherbi7y
Sep 9 '17 at 15:06















Sorry I didn't explain myself correctly. I mean, if the access to the rest service is through web browser or using a custom client code or other tool like curl?

– Daniel C.
Sep 9 '17 at 15:55





Sorry I didn't explain myself correctly. I mean, if the access to the rest service is through web browser or using a custom client code or other tool like curl?

– Daniel C.
Sep 9 '17 at 15:55













I use PostMan and chrome to do the testing, in PM I just sent the authentication data with the request. in chrome I type down the URL, wait for the login pop-up, and fill in the authentication data.

– Sherbi7y
Sep 9 '17 at 16:49





I use PostMan and chrome to do the testing, in PM I just sent the authentication data with the request. in chrome I type down the URL, wait for the login pop-up, and fill in the authentication data.

– Sherbi7y
Sep 9 '17 at 16:49












1 Answer
1






active

oldest

votes


















1














I had the same problem, in my case the following solution worked perfectly



Create a class that implements AuthenticationProvider interface:



@Component
public class CustomAuthenticationProvider implements AuthenticationProvider {

@Autowired
private UserService userService;

@Override
public Authentication authenticate(Authentication authentication) throws AuthenticationException {

String email = authentication.getName();
String password = authentication.getCredentials().toString();

User user = userService.findUserByEmail(email);

List<GrantedAuthority> authorities = new ArrayList<>();
authorities.add(new SimpleGrantedAuthority(user.getRole().getDescription())); // description is a string

return new UsernamePasswordAuthenticationToken(email, password, authorities);
}

@Override
public boolean supports(Class<?> authentication) {
return authentication.equals(UsernamePasswordAuthenticationToken.class);
}
}


here to authenticate the user, you use your user service to retrieve the user by email (username) from database and create a token using his email, password with his granted authorities (for example: USER, ADMIN)



then in your SecurityConfig class use the the bean you have just created as follows:



@Configuration
@EnableGlobalMethodSecurity(securedEnabled = true)
public class SecurityConfig extends WebSecurityConfigurerAdapter {

@Autowired
private CustomAuthenticationProvider authProvider;

@Autowired
public void configAuthentication(AuthenticationManagerBuilder auth) throws Exception {
auth.authenticationProvider(authProvider);
}

@Override
protected void configure(HttpSecurity http) throws Exception {
http.httpBasic().and().authorizeRequests().antMatchers("/**").hasRole("ADMIN").and()
.csrf().disable().headers().frameOptions().disable();
}
}





share|improve this answer

























    Your Answer






    StackExchange.ifUsing("editor", function () {
    StackExchange.using("externalEditor", function () {
    StackExchange.using("snippets", function () {
    StackExchange.snippets.init();
    });
    });
    }, "code-snippets");

    StackExchange.ready(function() {
    var channelOptions = {
    tags: "".split(" "),
    id: "1"
    };
    initTagRenderer("".split(" "), "".split(" "), channelOptions);

    StackExchange.using("externalEditor", function() {
    // Have to fire editor after snippets, if snippets enabled
    if (StackExchange.settings.snippets.snippetsEnabled) {
    StackExchange.using("snippets", function() {
    createEditor();
    });
    }
    else {
    createEditor();
    }
    });

    function createEditor() {
    StackExchange.prepareEditor({
    heartbeatType: 'answer',
    autoActivateHeartbeat: false,
    convertImagesToLinks: true,
    noModals: true,
    showLowRepImageUploadWarning: true,
    reputationToPostImages: 10,
    bindNavPrevention: true,
    postfix: "",
    imageUploader: {
    brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
    contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
    allowUrls: true
    },
    onDemand: true,
    discardSelector: ".discard-answer"
    ,immediatelyShowMarkdownHelp:true
    });


    }
    });














    draft saved

    draft discarded


















    StackExchange.ready(
    function () {
    StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f46124028%2fspring-boot-security-rest-basic-authentication-from-database%23new-answer', 'question_page');
    }
    );

    Post as a guest















    Required, but never shown

























    1 Answer
    1






    active

    oldest

    votes








    1 Answer
    1






    active

    oldest

    votes









    active

    oldest

    votes






    active

    oldest

    votes









    1














    I had the same problem, in my case the following solution worked perfectly



    Create a class that implements AuthenticationProvider interface:



    @Component
    public class CustomAuthenticationProvider implements AuthenticationProvider {

    @Autowired
    private UserService userService;

    @Override
    public Authentication authenticate(Authentication authentication) throws AuthenticationException {

    String email = authentication.getName();
    String password = authentication.getCredentials().toString();

    User user = userService.findUserByEmail(email);

    List<GrantedAuthority> authorities = new ArrayList<>();
    authorities.add(new SimpleGrantedAuthority(user.getRole().getDescription())); // description is a string

    return new UsernamePasswordAuthenticationToken(email, password, authorities);
    }

    @Override
    public boolean supports(Class<?> authentication) {
    return authentication.equals(UsernamePasswordAuthenticationToken.class);
    }
    }


    here to authenticate the user, you use your user service to retrieve the user by email (username) from database and create a token using his email, password with his granted authorities (for example: USER, ADMIN)



    then in your SecurityConfig class use the the bean you have just created as follows:



    @Configuration
    @EnableGlobalMethodSecurity(securedEnabled = true)
    public class SecurityConfig extends WebSecurityConfigurerAdapter {

    @Autowired
    private CustomAuthenticationProvider authProvider;

    @Autowired
    public void configAuthentication(AuthenticationManagerBuilder auth) throws Exception {
    auth.authenticationProvider(authProvider);
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {
    http.httpBasic().and().authorizeRequests().antMatchers("/**").hasRole("ADMIN").and()
    .csrf().disable().headers().frameOptions().disable();
    }
    }





    share|improve this answer






























      1














      I had the same problem, in my case the following solution worked perfectly



      Create a class that implements AuthenticationProvider interface:



      @Component
      public class CustomAuthenticationProvider implements AuthenticationProvider {

      @Autowired
      private UserService userService;

      @Override
      public Authentication authenticate(Authentication authentication) throws AuthenticationException {

      String email = authentication.getName();
      String password = authentication.getCredentials().toString();

      User user = userService.findUserByEmail(email);

      List<GrantedAuthority> authorities = new ArrayList<>();
      authorities.add(new SimpleGrantedAuthority(user.getRole().getDescription())); // description is a string

      return new UsernamePasswordAuthenticationToken(email, password, authorities);
      }

      @Override
      public boolean supports(Class<?> authentication) {
      return authentication.equals(UsernamePasswordAuthenticationToken.class);
      }
      }


      here to authenticate the user, you use your user service to retrieve the user by email (username) from database and create a token using his email, password with his granted authorities (for example: USER, ADMIN)



      then in your SecurityConfig class use the the bean you have just created as follows:



      @Configuration
      @EnableGlobalMethodSecurity(securedEnabled = true)
      public class SecurityConfig extends WebSecurityConfigurerAdapter {

      @Autowired
      private CustomAuthenticationProvider authProvider;

      @Autowired
      public void configAuthentication(AuthenticationManagerBuilder auth) throws Exception {
      auth.authenticationProvider(authProvider);
      }

      @Override
      protected void configure(HttpSecurity http) throws Exception {
      http.httpBasic().and().authorizeRequests().antMatchers("/**").hasRole("ADMIN").and()
      .csrf().disable().headers().frameOptions().disable();
      }
      }





      share|improve this answer




























        1












        1








        1







        I had the same problem, in my case the following solution worked perfectly



        Create a class that implements AuthenticationProvider interface:



        @Component
        public class CustomAuthenticationProvider implements AuthenticationProvider {

        @Autowired
        private UserService userService;

        @Override
        public Authentication authenticate(Authentication authentication) throws AuthenticationException {

        String email = authentication.getName();
        String password = authentication.getCredentials().toString();

        User user = userService.findUserByEmail(email);

        List<GrantedAuthority> authorities = new ArrayList<>();
        authorities.add(new SimpleGrantedAuthority(user.getRole().getDescription())); // description is a string

        return new UsernamePasswordAuthenticationToken(email, password, authorities);
        }

        @Override
        public boolean supports(Class<?> authentication) {
        return authentication.equals(UsernamePasswordAuthenticationToken.class);
        }
        }


        here to authenticate the user, you use your user service to retrieve the user by email (username) from database and create a token using his email, password with his granted authorities (for example: USER, ADMIN)



        then in your SecurityConfig class use the the bean you have just created as follows:



        @Configuration
        @EnableGlobalMethodSecurity(securedEnabled = true)
        public class SecurityConfig extends WebSecurityConfigurerAdapter {

        @Autowired
        private CustomAuthenticationProvider authProvider;

        @Autowired
        public void configAuthentication(AuthenticationManagerBuilder auth) throws Exception {
        auth.authenticationProvider(authProvider);
        }

        @Override
        protected void configure(HttpSecurity http) throws Exception {
        http.httpBasic().and().authorizeRequests().antMatchers("/**").hasRole("ADMIN").and()
        .csrf().disable().headers().frameOptions().disable();
        }
        }





        share|improve this answer















        I had the same problem, in my case the following solution worked perfectly



        Create a class that implements AuthenticationProvider interface:



        @Component
        public class CustomAuthenticationProvider implements AuthenticationProvider {

        @Autowired
        private UserService userService;

        @Override
        public Authentication authenticate(Authentication authentication) throws AuthenticationException {

        String email = authentication.getName();
        String password = authentication.getCredentials().toString();

        User user = userService.findUserByEmail(email);

        List<GrantedAuthority> authorities = new ArrayList<>();
        authorities.add(new SimpleGrantedAuthority(user.getRole().getDescription())); // description is a string

        return new UsernamePasswordAuthenticationToken(email, password, authorities);
        }

        @Override
        public boolean supports(Class<?> authentication) {
        return authentication.equals(UsernamePasswordAuthenticationToken.class);
        }
        }


        here to authenticate the user, you use your user service to retrieve the user by email (username) from database and create a token using his email, password with his granted authorities (for example: USER, ADMIN)



        then in your SecurityConfig class use the the bean you have just created as follows:



        @Configuration
        @EnableGlobalMethodSecurity(securedEnabled = true)
        public class SecurityConfig extends WebSecurityConfigurerAdapter {

        @Autowired
        private CustomAuthenticationProvider authProvider;

        @Autowired
        public void configAuthentication(AuthenticationManagerBuilder auth) throws Exception {
        auth.authenticationProvider(authProvider);
        }

        @Override
        protected void configure(HttpSecurity http) throws Exception {
        http.httpBasic().and().authorizeRequests().antMatchers("/**").hasRole("ADMIN").and()
        .csrf().disable().headers().frameOptions().disable();
        }
        }






        share|improve this answer














        share|improve this answer



        share|improve this answer








        edited Nov 25 '18 at 2:15

























        answered Nov 25 '18 at 0:41









        Mis94Mis94

        1,07011021




        1,07011021






























            draft saved

            draft discarded




















































            Thanks for contributing an answer to Stack Overflow!


            • Please be sure to answer the question. Provide details and share your research!

            But avoid



            • Asking for help, clarification, or responding to other answers.

            • Making statements based on opinion; back them up with references or personal experience.


            To learn more, see our tips on writing great answers.




            draft saved


            draft discarded














            StackExchange.ready(
            function () {
            StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f46124028%2fspring-boot-security-rest-basic-authentication-from-database%23new-answer', 'question_page');
            }
            );

            Post as a guest















            Required, but never shown





















































            Required, but never shown














            Required, but never shown












            Required, but never shown







            Required, but never shown

































            Required, but never shown














            Required, but never shown












            Required, but never shown







            Required, but never shown







            Popular posts from this blog

            A CLEAN and SIMPLE way to add appendices to Table of Contents and bookmarks

            Calculate evaluation metrics using cross_val_predict sklearn

            Insert data from modal to MySQL (multiple modal on website)