Multiple authentification strategies in spring boot security












-1















In order to use a custom authentification in spring security you got to implement the UserDetailsService interface and override the loadUserByUsername method, such as the example below



public class UserServiceImpl implements UserDetailsService{

@Autowired
private UserDao userDao;

@Override
public UserDetails loadUserByUsername(String useremail)
throws UsernameNotFoundException {
Users user = userDao.findByUserEmail(useremail);
if(user == null){
throw new UsernameNotFoundException("UserName or Password Invalid.");
}
return new org.springframework.security.core.userdetails.User(user.getUsername(), user.getPassword(), user.getEnabled(), true, true, true, getGrantedAuthorities(userDao.getUserRole(user.getUsersId())));
}


and its working fine for the whole website.



what i want to do now is to expose a restful webservice from the same host and all the requests for that WS will be through the /api/** with a different type of authentification (e.g : using tokens)
is it possible to do it? and if so, is there any idea how to do it ? any useful resources ?










share|improve this question





























    -1















    In order to use a custom authentification in spring security you got to implement the UserDetailsService interface and override the loadUserByUsername method, such as the example below



    public class UserServiceImpl implements UserDetailsService{

    @Autowired
    private UserDao userDao;

    @Override
    public UserDetails loadUserByUsername(String useremail)
    throws UsernameNotFoundException {
    Users user = userDao.findByUserEmail(useremail);
    if(user == null){
    throw new UsernameNotFoundException("UserName or Password Invalid.");
    }
    return new org.springframework.security.core.userdetails.User(user.getUsername(), user.getPassword(), user.getEnabled(), true, true, true, getGrantedAuthorities(userDao.getUserRole(user.getUsersId())));
    }


    and its working fine for the whole website.



    what i want to do now is to expose a restful webservice from the same host and all the requests for that WS will be through the /api/** with a different type of authentification (e.g : using tokens)
    is it possible to do it? and if so, is there any idea how to do it ? any useful resources ?










    share|improve this question



























      -1












      -1








      -1








      In order to use a custom authentification in spring security you got to implement the UserDetailsService interface and override the loadUserByUsername method, such as the example below



      public class UserServiceImpl implements UserDetailsService{

      @Autowired
      private UserDao userDao;

      @Override
      public UserDetails loadUserByUsername(String useremail)
      throws UsernameNotFoundException {
      Users user = userDao.findByUserEmail(useremail);
      if(user == null){
      throw new UsernameNotFoundException("UserName or Password Invalid.");
      }
      return new org.springframework.security.core.userdetails.User(user.getUsername(), user.getPassword(), user.getEnabled(), true, true, true, getGrantedAuthorities(userDao.getUserRole(user.getUsersId())));
      }


      and its working fine for the whole website.



      what i want to do now is to expose a restful webservice from the same host and all the requests for that WS will be through the /api/** with a different type of authentification (e.g : using tokens)
      is it possible to do it? and if so, is there any idea how to do it ? any useful resources ?










      share|improve this question
















      In order to use a custom authentification in spring security you got to implement the UserDetailsService interface and override the loadUserByUsername method, such as the example below



      public class UserServiceImpl implements UserDetailsService{

      @Autowired
      private UserDao userDao;

      @Override
      public UserDetails loadUserByUsername(String useremail)
      throws UsernameNotFoundException {
      Users user = userDao.findByUserEmail(useremail);
      if(user == null){
      throw new UsernameNotFoundException("UserName or Password Invalid.");
      }
      return new org.springframework.security.core.userdetails.User(user.getUsername(), user.getPassword(), user.getEnabled(), true, true, true, getGrantedAuthorities(userDao.getUserRole(user.getUsersId())));
      }


      and its working fine for the whole website.



      what i want to do now is to expose a restful webservice from the same host and all the requests for that WS will be through the /api/** with a different type of authentification (e.g : using tokens)
      is it possible to do it? and if so, is there any idea how to do it ? any useful resources ?







      java spring authentication spring-security token






      share|improve this question















      share|improve this question













      share|improve this question




      share|improve this question








      edited Nov 21 '18 at 10:00







      octopus

















      asked Nov 21 '18 at 9:48









      octopusoctopus

      2817




      2817
























          1 Answer
          1






          active

          oldest

          votes


















          0














          You can start by making security configuration class as follows



          @Configuration
          public class SecurityConfiguration extends WebSecurityConfigurerAdapter {

          private final TokenAuthenticationFilter tokenAuthenticationFilter;

          ...

          public SecurityConfiguration(TokenAuthenticationFilter tokenAuthenticationFilter) {
          this.corsFilter = corsFilter;
          }

          @Bean
          public PasswordEncoder passwordEncoder() {
          return new BCryptPasswordEncoder();
          }

          @Override
          public void configure(WebSecurity web) throws Exception {
          web.ignoring()
          .antMatchers(HttpMethod.OPTIONS, "/**");
          }

          @Override
          protected void configure(HttpSecurity http) throws Exception {
          http
          .csrf().disable()
          .and()
          .addFilterBefore(tokenAuthenticationFilter, TokenAuthenticationFilter.class)
          .exceptionHandling()
          .authenticationEntryPoint(problemSupport)
          .accessDeniedHandler(problemSupport)
          .and()
          .logout()
          .logoutUrl("/api/logout")
          .logoutSuccessHandler(You log out success handler goes here)
          .permitAll()
          .and()
          .authorizeRequests()
          .antMatchers("/api/**").authenticated();

          }


          }



          And your TokenAuthenticationFilter class will do the token authenticity for every request.



          @Configuration
          public class SecurityConfiguration extends WebSecurityConfigurerAdapter {

          private final TokenAuthenticationFilter tokenAuthenticationFilter;

          ...

          public SecurityConfiguration(TokenAuthenticationFilter tokenAuthenticationFilter) {
          this.corsFilter = corsFilter;
          }

          @Bean
          public PasswordEncoder passwordEncoder() {
          return new BCryptPasswordEncoder();
          }

          @Override
          public void configure(WebSecurity web) throws Exception {
          web.ignoring()
          .antMatchers(HttpMethod.OPTIONS, "/**");
          }

          @Override
          protected void configure(HttpSecurity http) throws Exception {
          http
          .csrf().disable()
          .and()
          .addFilterBefore(tokenAuthenticationFilter, TokenAuthenticationFilter.class)
          .exceptionHandling()
          .authenticationEntryPoint(problemSupport)
          .accessDeniedHandler(problemSupport)
          .and()
          .logout()
          .logoutUrl("/api/logout")
          .logoutSuccessHandler(You log out success handler goes here)
          .permitAll()
          .and()
          .authorizeRequests()
          .antMatchers("/api/**").authenticated();

          }
          }





          share|improve this answer


























          • I see what you want to say, but this will not solve the problem , in this case all the request will go through the TokenAuthenticationFilter. But what i want is to apply this token authentification just for a url pattern /api/** , and apply another authentification (email,password) for the other requests

            – octopus
            Nov 22 '18 at 8:45











          • So in that case this answer might solve your problem stackoverflow.com/a/46239996/4801359

            – Shashank Rajput
            Nov 22 '18 at 9:36











          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%2f53409262%2fmultiple-authentification-strategies-in-spring-boot-security%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









          0














          You can start by making security configuration class as follows



          @Configuration
          public class SecurityConfiguration extends WebSecurityConfigurerAdapter {

          private final TokenAuthenticationFilter tokenAuthenticationFilter;

          ...

          public SecurityConfiguration(TokenAuthenticationFilter tokenAuthenticationFilter) {
          this.corsFilter = corsFilter;
          }

          @Bean
          public PasswordEncoder passwordEncoder() {
          return new BCryptPasswordEncoder();
          }

          @Override
          public void configure(WebSecurity web) throws Exception {
          web.ignoring()
          .antMatchers(HttpMethod.OPTIONS, "/**");
          }

          @Override
          protected void configure(HttpSecurity http) throws Exception {
          http
          .csrf().disable()
          .and()
          .addFilterBefore(tokenAuthenticationFilter, TokenAuthenticationFilter.class)
          .exceptionHandling()
          .authenticationEntryPoint(problemSupport)
          .accessDeniedHandler(problemSupport)
          .and()
          .logout()
          .logoutUrl("/api/logout")
          .logoutSuccessHandler(You log out success handler goes here)
          .permitAll()
          .and()
          .authorizeRequests()
          .antMatchers("/api/**").authenticated();

          }


          }



          And your TokenAuthenticationFilter class will do the token authenticity for every request.



          @Configuration
          public class SecurityConfiguration extends WebSecurityConfigurerAdapter {

          private final TokenAuthenticationFilter tokenAuthenticationFilter;

          ...

          public SecurityConfiguration(TokenAuthenticationFilter tokenAuthenticationFilter) {
          this.corsFilter = corsFilter;
          }

          @Bean
          public PasswordEncoder passwordEncoder() {
          return new BCryptPasswordEncoder();
          }

          @Override
          public void configure(WebSecurity web) throws Exception {
          web.ignoring()
          .antMatchers(HttpMethod.OPTIONS, "/**");
          }

          @Override
          protected void configure(HttpSecurity http) throws Exception {
          http
          .csrf().disable()
          .and()
          .addFilterBefore(tokenAuthenticationFilter, TokenAuthenticationFilter.class)
          .exceptionHandling()
          .authenticationEntryPoint(problemSupport)
          .accessDeniedHandler(problemSupport)
          .and()
          .logout()
          .logoutUrl("/api/logout")
          .logoutSuccessHandler(You log out success handler goes here)
          .permitAll()
          .and()
          .authorizeRequests()
          .antMatchers("/api/**").authenticated();

          }
          }





          share|improve this answer


























          • I see what you want to say, but this will not solve the problem , in this case all the request will go through the TokenAuthenticationFilter. But what i want is to apply this token authentification just for a url pattern /api/** , and apply another authentification (email,password) for the other requests

            – octopus
            Nov 22 '18 at 8:45











          • So in that case this answer might solve your problem stackoverflow.com/a/46239996/4801359

            – Shashank Rajput
            Nov 22 '18 at 9:36
















          0














          You can start by making security configuration class as follows



          @Configuration
          public class SecurityConfiguration extends WebSecurityConfigurerAdapter {

          private final TokenAuthenticationFilter tokenAuthenticationFilter;

          ...

          public SecurityConfiguration(TokenAuthenticationFilter tokenAuthenticationFilter) {
          this.corsFilter = corsFilter;
          }

          @Bean
          public PasswordEncoder passwordEncoder() {
          return new BCryptPasswordEncoder();
          }

          @Override
          public void configure(WebSecurity web) throws Exception {
          web.ignoring()
          .antMatchers(HttpMethod.OPTIONS, "/**");
          }

          @Override
          protected void configure(HttpSecurity http) throws Exception {
          http
          .csrf().disable()
          .and()
          .addFilterBefore(tokenAuthenticationFilter, TokenAuthenticationFilter.class)
          .exceptionHandling()
          .authenticationEntryPoint(problemSupport)
          .accessDeniedHandler(problemSupport)
          .and()
          .logout()
          .logoutUrl("/api/logout")
          .logoutSuccessHandler(You log out success handler goes here)
          .permitAll()
          .and()
          .authorizeRequests()
          .antMatchers("/api/**").authenticated();

          }


          }



          And your TokenAuthenticationFilter class will do the token authenticity for every request.



          @Configuration
          public class SecurityConfiguration extends WebSecurityConfigurerAdapter {

          private final TokenAuthenticationFilter tokenAuthenticationFilter;

          ...

          public SecurityConfiguration(TokenAuthenticationFilter tokenAuthenticationFilter) {
          this.corsFilter = corsFilter;
          }

          @Bean
          public PasswordEncoder passwordEncoder() {
          return new BCryptPasswordEncoder();
          }

          @Override
          public void configure(WebSecurity web) throws Exception {
          web.ignoring()
          .antMatchers(HttpMethod.OPTIONS, "/**");
          }

          @Override
          protected void configure(HttpSecurity http) throws Exception {
          http
          .csrf().disable()
          .and()
          .addFilterBefore(tokenAuthenticationFilter, TokenAuthenticationFilter.class)
          .exceptionHandling()
          .authenticationEntryPoint(problemSupport)
          .accessDeniedHandler(problemSupport)
          .and()
          .logout()
          .logoutUrl("/api/logout")
          .logoutSuccessHandler(You log out success handler goes here)
          .permitAll()
          .and()
          .authorizeRequests()
          .antMatchers("/api/**").authenticated();

          }
          }





          share|improve this answer


























          • I see what you want to say, but this will not solve the problem , in this case all the request will go through the TokenAuthenticationFilter. But what i want is to apply this token authentification just for a url pattern /api/** , and apply another authentification (email,password) for the other requests

            – octopus
            Nov 22 '18 at 8:45











          • So in that case this answer might solve your problem stackoverflow.com/a/46239996/4801359

            – Shashank Rajput
            Nov 22 '18 at 9:36














          0












          0








          0







          You can start by making security configuration class as follows



          @Configuration
          public class SecurityConfiguration extends WebSecurityConfigurerAdapter {

          private final TokenAuthenticationFilter tokenAuthenticationFilter;

          ...

          public SecurityConfiguration(TokenAuthenticationFilter tokenAuthenticationFilter) {
          this.corsFilter = corsFilter;
          }

          @Bean
          public PasswordEncoder passwordEncoder() {
          return new BCryptPasswordEncoder();
          }

          @Override
          public void configure(WebSecurity web) throws Exception {
          web.ignoring()
          .antMatchers(HttpMethod.OPTIONS, "/**");
          }

          @Override
          protected void configure(HttpSecurity http) throws Exception {
          http
          .csrf().disable()
          .and()
          .addFilterBefore(tokenAuthenticationFilter, TokenAuthenticationFilter.class)
          .exceptionHandling()
          .authenticationEntryPoint(problemSupport)
          .accessDeniedHandler(problemSupport)
          .and()
          .logout()
          .logoutUrl("/api/logout")
          .logoutSuccessHandler(You log out success handler goes here)
          .permitAll()
          .and()
          .authorizeRequests()
          .antMatchers("/api/**").authenticated();

          }


          }



          And your TokenAuthenticationFilter class will do the token authenticity for every request.



          @Configuration
          public class SecurityConfiguration extends WebSecurityConfigurerAdapter {

          private final TokenAuthenticationFilter tokenAuthenticationFilter;

          ...

          public SecurityConfiguration(TokenAuthenticationFilter tokenAuthenticationFilter) {
          this.corsFilter = corsFilter;
          }

          @Bean
          public PasswordEncoder passwordEncoder() {
          return new BCryptPasswordEncoder();
          }

          @Override
          public void configure(WebSecurity web) throws Exception {
          web.ignoring()
          .antMatchers(HttpMethod.OPTIONS, "/**");
          }

          @Override
          protected void configure(HttpSecurity http) throws Exception {
          http
          .csrf().disable()
          .and()
          .addFilterBefore(tokenAuthenticationFilter, TokenAuthenticationFilter.class)
          .exceptionHandling()
          .authenticationEntryPoint(problemSupport)
          .accessDeniedHandler(problemSupport)
          .and()
          .logout()
          .logoutUrl("/api/logout")
          .logoutSuccessHandler(You log out success handler goes here)
          .permitAll()
          .and()
          .authorizeRequests()
          .antMatchers("/api/**").authenticated();

          }
          }





          share|improve this answer















          You can start by making security configuration class as follows



          @Configuration
          public class SecurityConfiguration extends WebSecurityConfigurerAdapter {

          private final TokenAuthenticationFilter tokenAuthenticationFilter;

          ...

          public SecurityConfiguration(TokenAuthenticationFilter tokenAuthenticationFilter) {
          this.corsFilter = corsFilter;
          }

          @Bean
          public PasswordEncoder passwordEncoder() {
          return new BCryptPasswordEncoder();
          }

          @Override
          public void configure(WebSecurity web) throws Exception {
          web.ignoring()
          .antMatchers(HttpMethod.OPTIONS, "/**");
          }

          @Override
          protected void configure(HttpSecurity http) throws Exception {
          http
          .csrf().disable()
          .and()
          .addFilterBefore(tokenAuthenticationFilter, TokenAuthenticationFilter.class)
          .exceptionHandling()
          .authenticationEntryPoint(problemSupport)
          .accessDeniedHandler(problemSupport)
          .and()
          .logout()
          .logoutUrl("/api/logout")
          .logoutSuccessHandler(You log out success handler goes here)
          .permitAll()
          .and()
          .authorizeRequests()
          .antMatchers("/api/**").authenticated();

          }


          }



          And your TokenAuthenticationFilter class will do the token authenticity for every request.



          @Configuration
          public class SecurityConfiguration extends WebSecurityConfigurerAdapter {

          private final TokenAuthenticationFilter tokenAuthenticationFilter;

          ...

          public SecurityConfiguration(TokenAuthenticationFilter tokenAuthenticationFilter) {
          this.corsFilter = corsFilter;
          }

          @Bean
          public PasswordEncoder passwordEncoder() {
          return new BCryptPasswordEncoder();
          }

          @Override
          public void configure(WebSecurity web) throws Exception {
          web.ignoring()
          .antMatchers(HttpMethod.OPTIONS, "/**");
          }

          @Override
          protected void configure(HttpSecurity http) throws Exception {
          http
          .csrf().disable()
          .and()
          .addFilterBefore(tokenAuthenticationFilter, TokenAuthenticationFilter.class)
          .exceptionHandling()
          .authenticationEntryPoint(problemSupport)
          .accessDeniedHandler(problemSupport)
          .and()
          .logout()
          .logoutUrl("/api/logout")
          .logoutSuccessHandler(You log out success handler goes here)
          .permitAll()
          .and()
          .authorizeRequests()
          .antMatchers("/api/**").authenticated();

          }
          }






          share|improve this answer














          share|improve this answer



          share|improve this answer








          edited Nov 22 '18 at 8:03

























          answered Nov 22 '18 at 6:20









          Shashank RajputShashank Rajput

          1125




          1125













          • I see what you want to say, but this will not solve the problem , in this case all the request will go through the TokenAuthenticationFilter. But what i want is to apply this token authentification just for a url pattern /api/** , and apply another authentification (email,password) for the other requests

            – octopus
            Nov 22 '18 at 8:45











          • So in that case this answer might solve your problem stackoverflow.com/a/46239996/4801359

            – Shashank Rajput
            Nov 22 '18 at 9:36



















          • I see what you want to say, but this will not solve the problem , in this case all the request will go through the TokenAuthenticationFilter. But what i want is to apply this token authentification just for a url pattern /api/** , and apply another authentification (email,password) for the other requests

            – octopus
            Nov 22 '18 at 8:45











          • So in that case this answer might solve your problem stackoverflow.com/a/46239996/4801359

            – Shashank Rajput
            Nov 22 '18 at 9:36

















          I see what you want to say, but this will not solve the problem , in this case all the request will go through the TokenAuthenticationFilter. But what i want is to apply this token authentification just for a url pattern /api/** , and apply another authentification (email,password) for the other requests

          – octopus
          Nov 22 '18 at 8:45





          I see what you want to say, but this will not solve the problem , in this case all the request will go through the TokenAuthenticationFilter. But what i want is to apply this token authentification just for a url pattern /api/** , and apply another authentification (email,password) for the other requests

          – octopus
          Nov 22 '18 at 8:45













          So in that case this answer might solve your problem stackoverflow.com/a/46239996/4801359

          – Shashank Rajput
          Nov 22 '18 at 9:36





          So in that case this answer might solve your problem stackoverflow.com/a/46239996/4801359

          – Shashank Rajput
          Nov 22 '18 at 9:36




















          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%2f53409262%2fmultiple-authentification-strategies-in-spring-boot-security%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

          MongoDB - Not Authorized To Execute Command

          How to fix TextFormField cause rebuild widget in Flutter

          Npm cannot find a required file even through it is in the searched directory