How to auto login after successful registration in spring boot?












0















Yes, I know this question is already asked. But regard to this question I have a different problem as well. authenticationManager object of AuthenticationManager in SecurityServiceImpl class which is not authenticating the details which caused me to stuck at this point.



I have tried to give message after each step by which I can track the particular code whether they are working or not and I found in SecurityServiceImpl class that it does not work after this code



authenticationManager.authenticate(usernamePasswordAuthenticationToken);


I don't know this is just my understanding. Help me out of this problem and please provide me if you have better code snippet to solve this particular problem.



SecurityConfiguration



package com.demo.practice.configuration;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;

@Configuration
@EnableWebSecurity
public class SecurityConfiguration extends WebSecurityConfigurerAdapter {
Logger logger = LoggerFactory.getLogger(SecurityConfiguration.class);

@Autowired
private UserDetailsService userDetailsService;

protected void configure(HttpSecurity http) throws Exception {
http.authorizeRequests()
.antMatchers("/","/register","/login").permitAll()
.antMatchers("/student/**").hasAuthority("STUDENT")
.antMatchers("/admin/**").hasAuthority("ADMIN")
.anyRequest().authenticated()
.and()
.formLogin().loginPage("/login")
.defaultSuccessUrl("/dashboard");
http.csrf().disable();
}



@Autowired
public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
auth.userDetailsService(userDetailsService).passwordEncoder(bCryptPasswordEncoder());
}

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

@Bean
public BCryptPasswordEncoder bCryptPasswordEncoder() {
return new BCryptPasswordEncoder();
}
}


UserServiceImpl



package com.demo.practice.service;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;

import com.demo.practice.model.Credentials;
import com.demo.practice.model.Role;
import com.demo.practice.model.User;
import com.demo.practice.repository.UserRepository;

@Service
public class UserServiceImpl implements UserServiceInterface {

@Autowired
private BCryptPasswordEncoder encoder;
@Autowired
UserRepository userRepo;

@Override
public void saveUser(User user,Credentials credential) {
user.setCredential(credential);
user.getCredential().setUsername(user.getEmail());
user.getCredential().setRoles(Role.STUDENT);
user.getCredential().setPassword(encoder.encode(user.getCredential().getPassword()));
userRepo.save(user);
}

@Override
public User findUserByEmail(String name) {
User user=userRepo.findUserByEmail(name);
return user;
}

}


UserDetailsServiceImpl



package com.demo.practice.service;

import java.util.ArrayList;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.demo.practice.model.Credentials;
import com.demo.practice.repository.CredentialRepository;

@Service
public class UserDetailsServiceImpl implements UserDetailsService {

@Autowired
CredentialRepository credRepo;

@Override
@Transactional(readOnly = true)
public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
Credentials credential =credRepo.findByUsername(username);
List<GrantedAuthority> grantedAuthorities = new ArrayList<GrantedAuthority>();
grantedAuthorities.add(new SimpleGrantedAuthority(credential.getRoles().toString()));
return new org.springframework.security.core.userdetails.User(credential.getUsername(), credential.getPassword(), grantedAuthorities);
}

}


SecurityServiceImpl



package com.demo.practice.service;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.stereotype.Service;

@Service
public class SecurityServiceImpl implements SecurityServiceInterface {

@Autowired
private AuthenticationManager authenticationManager;

@Autowired
private UserDetailsService userDetailsService;

private static final Logger logger = LoggerFactory.getLogger(SecurityServiceImpl.class);

@Override
public String findLoggedInUsername() {
Object userDetails = SecurityContextHolder.getContext().getAuthentication().getDetails();
if (userDetails instanceof UserDetails) {
return ((UserDetails)userDetails).getUsername();
}

return null;
}

@Override
public void autologin(String username, String password) {
System.out.println("in autologin "+username);
UserDetails userDetails = userDetailsService.loadUserByUsername(username);
System.out.println("in autologin at userdetails"+userDetails);
logger.info("after userdetails "+userDetails);
UsernamePasswordAuthenticationToken usernamePasswordAuthenticationToken = new UsernamePasswordAuthenticationToken(userDetails.getUsername(), userDetails.getPassword(),userDetails.getAuthorities());
logger.info("in autologin after usernamepasswordauthentication! ", usernamePasswordAuthenticationToken);
authenticationManager.authenticate(usernamePasswordAuthenticationToken);
logger.info("after authentication manager ", usernamePasswordAuthenticationToken);
if (usernamePasswordAuthenticationToken.isAuthenticated()) {
SecurityContextHolder.getContext().setAuthentication(usernamePasswordAuthenticationToken);
logger.debug(String.format("Auto login %s successfully!", username));
}
else System.out.println("auto login failed");
}


}









share|improve this question





























    0















    Yes, I know this question is already asked. But regard to this question I have a different problem as well. authenticationManager object of AuthenticationManager in SecurityServiceImpl class which is not authenticating the details which caused me to stuck at this point.



    I have tried to give message after each step by which I can track the particular code whether they are working or not and I found in SecurityServiceImpl class that it does not work after this code



    authenticationManager.authenticate(usernamePasswordAuthenticationToken);


    I don't know this is just my understanding. Help me out of this problem and please provide me if you have better code snippet to solve this particular problem.



    SecurityConfiguration



    package com.demo.practice.configuration;

    import org.slf4j.Logger;
    import org.slf4j.LoggerFactory;
    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.context.annotation.Bean;
    import org.springframework.context.annotation.Configuration;
    import org.springframework.security.authentication.AuthenticationManager;
    import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
    import org.springframework.security.config.annotation.web.builders.HttpSecurity;
    import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
    import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
    import org.springframework.security.core.userdetails.UserDetailsService;
    import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;

    @Configuration
    @EnableWebSecurity
    public class SecurityConfiguration extends WebSecurityConfigurerAdapter {
    Logger logger = LoggerFactory.getLogger(SecurityConfiguration.class);

    @Autowired
    private UserDetailsService userDetailsService;

    protected void configure(HttpSecurity http) throws Exception {
    http.authorizeRequests()
    .antMatchers("/","/register","/login").permitAll()
    .antMatchers("/student/**").hasAuthority("STUDENT")
    .antMatchers("/admin/**").hasAuthority("ADMIN")
    .anyRequest().authenticated()
    .and()
    .formLogin().loginPage("/login")
    .defaultSuccessUrl("/dashboard");
    http.csrf().disable();
    }



    @Autowired
    public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
    auth.userDetailsService(userDetailsService).passwordEncoder(bCryptPasswordEncoder());
    }

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

    @Bean
    public BCryptPasswordEncoder bCryptPasswordEncoder() {
    return new BCryptPasswordEncoder();
    }
    }


    UserServiceImpl



    package com.demo.practice.service;

    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
    import org.springframework.stereotype.Service;

    import com.demo.practice.model.Credentials;
    import com.demo.practice.model.Role;
    import com.demo.practice.model.User;
    import com.demo.practice.repository.UserRepository;

    @Service
    public class UserServiceImpl implements UserServiceInterface {

    @Autowired
    private BCryptPasswordEncoder encoder;
    @Autowired
    UserRepository userRepo;

    @Override
    public void saveUser(User user,Credentials credential) {
    user.setCredential(credential);
    user.getCredential().setUsername(user.getEmail());
    user.getCredential().setRoles(Role.STUDENT);
    user.getCredential().setPassword(encoder.encode(user.getCredential().getPassword()));
    userRepo.save(user);
    }

    @Override
    public User findUserByEmail(String name) {
    User user=userRepo.findUserByEmail(name);
    return user;
    }

    }


    UserDetailsServiceImpl



    package com.demo.practice.service;

    import java.util.ArrayList;
    import java.util.List;

    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.security.core.GrantedAuthority;
    import org.springframework.security.core.authority.SimpleGrantedAuthority;
    import org.springframework.security.core.userdetails.UserDetails;
    import org.springframework.security.core.userdetails.UserDetailsService;
    import org.springframework.security.core.userdetails.UsernameNotFoundException;
    import org.springframework.stereotype.Service;
    import org.springframework.transaction.annotation.Transactional;

    import com.demo.practice.model.Credentials;
    import com.demo.practice.repository.CredentialRepository;

    @Service
    public class UserDetailsServiceImpl implements UserDetailsService {

    @Autowired
    CredentialRepository credRepo;

    @Override
    @Transactional(readOnly = true)
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
    Credentials credential =credRepo.findByUsername(username);
    List<GrantedAuthority> grantedAuthorities = new ArrayList<GrantedAuthority>();
    grantedAuthorities.add(new SimpleGrantedAuthority(credential.getRoles().toString()));
    return new org.springframework.security.core.userdetails.User(credential.getUsername(), credential.getPassword(), grantedAuthorities);
    }

    }


    SecurityServiceImpl



    package com.demo.practice.service;

    import org.slf4j.Logger;
    import org.slf4j.LoggerFactory;
    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.security.authentication.AuthenticationManager;
    import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
    import org.springframework.security.core.context.SecurityContextHolder;
    import org.springframework.security.core.userdetails.UserDetails;
    import org.springframework.security.core.userdetails.UserDetailsService;
    import org.springframework.stereotype.Service;

    @Service
    public class SecurityServiceImpl implements SecurityServiceInterface {

    @Autowired
    private AuthenticationManager authenticationManager;

    @Autowired
    private UserDetailsService userDetailsService;

    private static final Logger logger = LoggerFactory.getLogger(SecurityServiceImpl.class);

    @Override
    public String findLoggedInUsername() {
    Object userDetails = SecurityContextHolder.getContext().getAuthentication().getDetails();
    if (userDetails instanceof UserDetails) {
    return ((UserDetails)userDetails).getUsername();
    }

    return null;
    }

    @Override
    public void autologin(String username, String password) {
    System.out.println("in autologin "+username);
    UserDetails userDetails = userDetailsService.loadUserByUsername(username);
    System.out.println("in autologin at userdetails"+userDetails);
    logger.info("after userdetails "+userDetails);
    UsernamePasswordAuthenticationToken usernamePasswordAuthenticationToken = new UsernamePasswordAuthenticationToken(userDetails.getUsername(), userDetails.getPassword(),userDetails.getAuthorities());
    logger.info("in autologin after usernamepasswordauthentication! ", usernamePasswordAuthenticationToken);
    authenticationManager.authenticate(usernamePasswordAuthenticationToken);
    logger.info("after authentication manager ", usernamePasswordAuthenticationToken);
    if (usernamePasswordAuthenticationToken.isAuthenticated()) {
    SecurityContextHolder.getContext().setAuthentication(usernamePasswordAuthenticationToken);
    logger.debug(String.format("Auto login %s successfully!", username));
    }
    else System.out.println("auto login failed");
    }


    }









    share|improve this question



























      0












      0








      0








      Yes, I know this question is already asked. But regard to this question I have a different problem as well. authenticationManager object of AuthenticationManager in SecurityServiceImpl class which is not authenticating the details which caused me to stuck at this point.



      I have tried to give message after each step by which I can track the particular code whether they are working or not and I found in SecurityServiceImpl class that it does not work after this code



      authenticationManager.authenticate(usernamePasswordAuthenticationToken);


      I don't know this is just my understanding. Help me out of this problem and please provide me if you have better code snippet to solve this particular problem.



      SecurityConfiguration



      package com.demo.practice.configuration;

      import org.slf4j.Logger;
      import org.slf4j.LoggerFactory;
      import org.springframework.beans.factory.annotation.Autowired;
      import org.springframework.context.annotation.Bean;
      import org.springframework.context.annotation.Configuration;
      import org.springframework.security.authentication.AuthenticationManager;
      import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
      import org.springframework.security.config.annotation.web.builders.HttpSecurity;
      import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
      import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
      import org.springframework.security.core.userdetails.UserDetailsService;
      import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;

      @Configuration
      @EnableWebSecurity
      public class SecurityConfiguration extends WebSecurityConfigurerAdapter {
      Logger logger = LoggerFactory.getLogger(SecurityConfiguration.class);

      @Autowired
      private UserDetailsService userDetailsService;

      protected void configure(HttpSecurity http) throws Exception {
      http.authorizeRequests()
      .antMatchers("/","/register","/login").permitAll()
      .antMatchers("/student/**").hasAuthority("STUDENT")
      .antMatchers("/admin/**").hasAuthority("ADMIN")
      .anyRequest().authenticated()
      .and()
      .formLogin().loginPage("/login")
      .defaultSuccessUrl("/dashboard");
      http.csrf().disable();
      }



      @Autowired
      public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
      auth.userDetailsService(userDetailsService).passwordEncoder(bCryptPasswordEncoder());
      }

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

      @Bean
      public BCryptPasswordEncoder bCryptPasswordEncoder() {
      return new BCryptPasswordEncoder();
      }
      }


      UserServiceImpl



      package com.demo.practice.service;

      import org.springframework.beans.factory.annotation.Autowired;
      import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
      import org.springframework.stereotype.Service;

      import com.demo.practice.model.Credentials;
      import com.demo.practice.model.Role;
      import com.demo.practice.model.User;
      import com.demo.practice.repository.UserRepository;

      @Service
      public class UserServiceImpl implements UserServiceInterface {

      @Autowired
      private BCryptPasswordEncoder encoder;
      @Autowired
      UserRepository userRepo;

      @Override
      public void saveUser(User user,Credentials credential) {
      user.setCredential(credential);
      user.getCredential().setUsername(user.getEmail());
      user.getCredential().setRoles(Role.STUDENT);
      user.getCredential().setPassword(encoder.encode(user.getCredential().getPassword()));
      userRepo.save(user);
      }

      @Override
      public User findUserByEmail(String name) {
      User user=userRepo.findUserByEmail(name);
      return user;
      }

      }


      UserDetailsServiceImpl



      package com.demo.practice.service;

      import java.util.ArrayList;
      import java.util.List;

      import org.springframework.beans.factory.annotation.Autowired;
      import org.springframework.security.core.GrantedAuthority;
      import org.springframework.security.core.authority.SimpleGrantedAuthority;
      import org.springframework.security.core.userdetails.UserDetails;
      import org.springframework.security.core.userdetails.UserDetailsService;
      import org.springframework.security.core.userdetails.UsernameNotFoundException;
      import org.springframework.stereotype.Service;
      import org.springframework.transaction.annotation.Transactional;

      import com.demo.practice.model.Credentials;
      import com.demo.practice.repository.CredentialRepository;

      @Service
      public class UserDetailsServiceImpl implements UserDetailsService {

      @Autowired
      CredentialRepository credRepo;

      @Override
      @Transactional(readOnly = true)
      public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
      Credentials credential =credRepo.findByUsername(username);
      List<GrantedAuthority> grantedAuthorities = new ArrayList<GrantedAuthority>();
      grantedAuthorities.add(new SimpleGrantedAuthority(credential.getRoles().toString()));
      return new org.springframework.security.core.userdetails.User(credential.getUsername(), credential.getPassword(), grantedAuthorities);
      }

      }


      SecurityServiceImpl



      package com.demo.practice.service;

      import org.slf4j.Logger;
      import org.slf4j.LoggerFactory;
      import org.springframework.beans.factory.annotation.Autowired;
      import org.springframework.security.authentication.AuthenticationManager;
      import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
      import org.springframework.security.core.context.SecurityContextHolder;
      import org.springframework.security.core.userdetails.UserDetails;
      import org.springframework.security.core.userdetails.UserDetailsService;
      import org.springframework.stereotype.Service;

      @Service
      public class SecurityServiceImpl implements SecurityServiceInterface {

      @Autowired
      private AuthenticationManager authenticationManager;

      @Autowired
      private UserDetailsService userDetailsService;

      private static final Logger logger = LoggerFactory.getLogger(SecurityServiceImpl.class);

      @Override
      public String findLoggedInUsername() {
      Object userDetails = SecurityContextHolder.getContext().getAuthentication().getDetails();
      if (userDetails instanceof UserDetails) {
      return ((UserDetails)userDetails).getUsername();
      }

      return null;
      }

      @Override
      public void autologin(String username, String password) {
      System.out.println("in autologin "+username);
      UserDetails userDetails = userDetailsService.loadUserByUsername(username);
      System.out.println("in autologin at userdetails"+userDetails);
      logger.info("after userdetails "+userDetails);
      UsernamePasswordAuthenticationToken usernamePasswordAuthenticationToken = new UsernamePasswordAuthenticationToken(userDetails.getUsername(), userDetails.getPassword(),userDetails.getAuthorities());
      logger.info("in autologin after usernamepasswordauthentication! ", usernamePasswordAuthenticationToken);
      authenticationManager.authenticate(usernamePasswordAuthenticationToken);
      logger.info("after authentication manager ", usernamePasswordAuthenticationToken);
      if (usernamePasswordAuthenticationToken.isAuthenticated()) {
      SecurityContextHolder.getContext().setAuthentication(usernamePasswordAuthenticationToken);
      logger.debug(String.format("Auto login %s successfully!", username));
      }
      else System.out.println("auto login failed");
      }


      }









      share|improve this question
















      Yes, I know this question is already asked. But regard to this question I have a different problem as well. authenticationManager object of AuthenticationManager in SecurityServiceImpl class which is not authenticating the details which caused me to stuck at this point.



      I have tried to give message after each step by which I can track the particular code whether they are working or not and I found in SecurityServiceImpl class that it does not work after this code



      authenticationManager.authenticate(usernamePasswordAuthenticationToken);


      I don't know this is just my understanding. Help me out of this problem and please provide me if you have better code snippet to solve this particular problem.



      SecurityConfiguration



      package com.demo.practice.configuration;

      import org.slf4j.Logger;
      import org.slf4j.LoggerFactory;
      import org.springframework.beans.factory.annotation.Autowired;
      import org.springframework.context.annotation.Bean;
      import org.springframework.context.annotation.Configuration;
      import org.springframework.security.authentication.AuthenticationManager;
      import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
      import org.springframework.security.config.annotation.web.builders.HttpSecurity;
      import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
      import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
      import org.springframework.security.core.userdetails.UserDetailsService;
      import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;

      @Configuration
      @EnableWebSecurity
      public class SecurityConfiguration extends WebSecurityConfigurerAdapter {
      Logger logger = LoggerFactory.getLogger(SecurityConfiguration.class);

      @Autowired
      private UserDetailsService userDetailsService;

      protected void configure(HttpSecurity http) throws Exception {
      http.authorizeRequests()
      .antMatchers("/","/register","/login").permitAll()
      .antMatchers("/student/**").hasAuthority("STUDENT")
      .antMatchers("/admin/**").hasAuthority("ADMIN")
      .anyRequest().authenticated()
      .and()
      .formLogin().loginPage("/login")
      .defaultSuccessUrl("/dashboard");
      http.csrf().disable();
      }



      @Autowired
      public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
      auth.userDetailsService(userDetailsService).passwordEncoder(bCryptPasswordEncoder());
      }

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

      @Bean
      public BCryptPasswordEncoder bCryptPasswordEncoder() {
      return new BCryptPasswordEncoder();
      }
      }


      UserServiceImpl



      package com.demo.practice.service;

      import org.springframework.beans.factory.annotation.Autowired;
      import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
      import org.springframework.stereotype.Service;

      import com.demo.practice.model.Credentials;
      import com.demo.practice.model.Role;
      import com.demo.practice.model.User;
      import com.demo.practice.repository.UserRepository;

      @Service
      public class UserServiceImpl implements UserServiceInterface {

      @Autowired
      private BCryptPasswordEncoder encoder;
      @Autowired
      UserRepository userRepo;

      @Override
      public void saveUser(User user,Credentials credential) {
      user.setCredential(credential);
      user.getCredential().setUsername(user.getEmail());
      user.getCredential().setRoles(Role.STUDENT);
      user.getCredential().setPassword(encoder.encode(user.getCredential().getPassword()));
      userRepo.save(user);
      }

      @Override
      public User findUserByEmail(String name) {
      User user=userRepo.findUserByEmail(name);
      return user;
      }

      }


      UserDetailsServiceImpl



      package com.demo.practice.service;

      import java.util.ArrayList;
      import java.util.List;

      import org.springframework.beans.factory.annotation.Autowired;
      import org.springframework.security.core.GrantedAuthority;
      import org.springframework.security.core.authority.SimpleGrantedAuthority;
      import org.springframework.security.core.userdetails.UserDetails;
      import org.springframework.security.core.userdetails.UserDetailsService;
      import org.springframework.security.core.userdetails.UsernameNotFoundException;
      import org.springframework.stereotype.Service;
      import org.springframework.transaction.annotation.Transactional;

      import com.demo.practice.model.Credentials;
      import com.demo.practice.repository.CredentialRepository;

      @Service
      public class UserDetailsServiceImpl implements UserDetailsService {

      @Autowired
      CredentialRepository credRepo;

      @Override
      @Transactional(readOnly = true)
      public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
      Credentials credential =credRepo.findByUsername(username);
      List<GrantedAuthority> grantedAuthorities = new ArrayList<GrantedAuthority>();
      grantedAuthorities.add(new SimpleGrantedAuthority(credential.getRoles().toString()));
      return new org.springframework.security.core.userdetails.User(credential.getUsername(), credential.getPassword(), grantedAuthorities);
      }

      }


      SecurityServiceImpl



      package com.demo.practice.service;

      import org.slf4j.Logger;
      import org.slf4j.LoggerFactory;
      import org.springframework.beans.factory.annotation.Autowired;
      import org.springframework.security.authentication.AuthenticationManager;
      import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
      import org.springframework.security.core.context.SecurityContextHolder;
      import org.springframework.security.core.userdetails.UserDetails;
      import org.springframework.security.core.userdetails.UserDetailsService;
      import org.springframework.stereotype.Service;

      @Service
      public class SecurityServiceImpl implements SecurityServiceInterface {

      @Autowired
      private AuthenticationManager authenticationManager;

      @Autowired
      private UserDetailsService userDetailsService;

      private static final Logger logger = LoggerFactory.getLogger(SecurityServiceImpl.class);

      @Override
      public String findLoggedInUsername() {
      Object userDetails = SecurityContextHolder.getContext().getAuthentication().getDetails();
      if (userDetails instanceof UserDetails) {
      return ((UserDetails)userDetails).getUsername();
      }

      return null;
      }

      @Override
      public void autologin(String username, String password) {
      System.out.println("in autologin "+username);
      UserDetails userDetails = userDetailsService.loadUserByUsername(username);
      System.out.println("in autologin at userdetails"+userDetails);
      logger.info("after userdetails "+userDetails);
      UsernamePasswordAuthenticationToken usernamePasswordAuthenticationToken = new UsernamePasswordAuthenticationToken(userDetails.getUsername(), userDetails.getPassword(),userDetails.getAuthorities());
      logger.info("in autologin after usernamepasswordauthentication! ", usernamePasswordAuthenticationToken);
      authenticationManager.authenticate(usernamePasswordAuthenticationToken);
      logger.info("after authentication manager ", usernamePasswordAuthenticationToken);
      if (usernamePasswordAuthenticationToken.isAuthenticated()) {
      SecurityContextHolder.getContext().setAuthentication(usernamePasswordAuthenticationToken);
      logger.debug(String.format("Auto login %s successfully!", username));
      }
      else System.out.println("auto login failed");
      }


      }






      spring-mvc spring-boot spring-security spring-data-jpa spring-data






      share|improve this question















      share|improve this question













      share|improve this question




      share|improve this question








      edited Nov 14 '18 at 19:01









      James Z

      11.2k71935




      11.2k71935










      asked Nov 14 '18 at 7:45









      SURAJ KUMARSURAJ KUMAR

      226




      226
























          1 Answer
          1






          active

          oldest

          votes


















          0














          you are missing one thing, if you want to have an authentication session based, you need to add WebAuthenticationDetails to the token like:



          UsernamePasswordAuthenticationToken token =
          new UsernamePasswordAuthenticationToken(principalUser, null, List.of(new SimpleGrantedAuthority(principalUser.getRole())));

          token.setDetails(new WebAuthenticationDetails(request));
          SecurityContextHolder.getContext().setAuthentication(token);


          the WebAuthenticationDetails from the doc:
          Records the remote address and will also set the session Id if a session already exists (it won't create one).



          for more info about the login/logout process take a look at:
          https://github.com/pezetem/spring-security-angular-skeleton/blob/master/src/main/java/com/pezetem/blog/code/spring_security_custom_authorizers/security/SecurityController.java



          UPDATE:



          ok, there could be another reason why it is not working for you. Spring Security adds default prefix to the roles. It is equal to ROLE_. It means that when you have an endpoint configured for .hasAuthority("STUDENT") role must be equal to ROLE_STUDENT, take a look at the line where you create a user, you assign role with Role.STUDENT and the enum value should be ROLE_STUDENT not STUDENT






          share|improve this answer


























          • thanks for your response..but it didn't help me

            – SURAJ KUMAR
            Nov 15 '18 at 17:31











          • place, take a look at the updated answer, there might be an issue with role prefix, you are missing for Role.STUDENT

            – pezetem
            Nov 15 '18 at 18:51











          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%2f53295260%2fhow-to-auto-login-after-successful-registration-in-spring-boot%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 are missing one thing, if you want to have an authentication session based, you need to add WebAuthenticationDetails to the token like:



          UsernamePasswordAuthenticationToken token =
          new UsernamePasswordAuthenticationToken(principalUser, null, List.of(new SimpleGrantedAuthority(principalUser.getRole())));

          token.setDetails(new WebAuthenticationDetails(request));
          SecurityContextHolder.getContext().setAuthentication(token);


          the WebAuthenticationDetails from the doc:
          Records the remote address and will also set the session Id if a session already exists (it won't create one).



          for more info about the login/logout process take a look at:
          https://github.com/pezetem/spring-security-angular-skeleton/blob/master/src/main/java/com/pezetem/blog/code/spring_security_custom_authorizers/security/SecurityController.java



          UPDATE:



          ok, there could be another reason why it is not working for you. Spring Security adds default prefix to the roles. It is equal to ROLE_. It means that when you have an endpoint configured for .hasAuthority("STUDENT") role must be equal to ROLE_STUDENT, take a look at the line where you create a user, you assign role with Role.STUDENT and the enum value should be ROLE_STUDENT not STUDENT






          share|improve this answer


























          • thanks for your response..but it didn't help me

            – SURAJ KUMAR
            Nov 15 '18 at 17:31











          • place, take a look at the updated answer, there might be an issue with role prefix, you are missing for Role.STUDENT

            – pezetem
            Nov 15 '18 at 18:51
















          0














          you are missing one thing, if you want to have an authentication session based, you need to add WebAuthenticationDetails to the token like:



          UsernamePasswordAuthenticationToken token =
          new UsernamePasswordAuthenticationToken(principalUser, null, List.of(new SimpleGrantedAuthority(principalUser.getRole())));

          token.setDetails(new WebAuthenticationDetails(request));
          SecurityContextHolder.getContext().setAuthentication(token);


          the WebAuthenticationDetails from the doc:
          Records the remote address and will also set the session Id if a session already exists (it won't create one).



          for more info about the login/logout process take a look at:
          https://github.com/pezetem/spring-security-angular-skeleton/blob/master/src/main/java/com/pezetem/blog/code/spring_security_custom_authorizers/security/SecurityController.java



          UPDATE:



          ok, there could be another reason why it is not working for you. Spring Security adds default prefix to the roles. It is equal to ROLE_. It means that when you have an endpoint configured for .hasAuthority("STUDENT") role must be equal to ROLE_STUDENT, take a look at the line where you create a user, you assign role with Role.STUDENT and the enum value should be ROLE_STUDENT not STUDENT






          share|improve this answer


























          • thanks for your response..but it didn't help me

            – SURAJ KUMAR
            Nov 15 '18 at 17:31











          • place, take a look at the updated answer, there might be an issue with role prefix, you are missing for Role.STUDENT

            – pezetem
            Nov 15 '18 at 18:51














          0












          0








          0







          you are missing one thing, if you want to have an authentication session based, you need to add WebAuthenticationDetails to the token like:



          UsernamePasswordAuthenticationToken token =
          new UsernamePasswordAuthenticationToken(principalUser, null, List.of(new SimpleGrantedAuthority(principalUser.getRole())));

          token.setDetails(new WebAuthenticationDetails(request));
          SecurityContextHolder.getContext().setAuthentication(token);


          the WebAuthenticationDetails from the doc:
          Records the remote address and will also set the session Id if a session already exists (it won't create one).



          for more info about the login/logout process take a look at:
          https://github.com/pezetem/spring-security-angular-skeleton/blob/master/src/main/java/com/pezetem/blog/code/spring_security_custom_authorizers/security/SecurityController.java



          UPDATE:



          ok, there could be another reason why it is not working for you. Spring Security adds default prefix to the roles. It is equal to ROLE_. It means that when you have an endpoint configured for .hasAuthority("STUDENT") role must be equal to ROLE_STUDENT, take a look at the line where you create a user, you assign role with Role.STUDENT and the enum value should be ROLE_STUDENT not STUDENT






          share|improve this answer















          you are missing one thing, if you want to have an authentication session based, you need to add WebAuthenticationDetails to the token like:



          UsernamePasswordAuthenticationToken token =
          new UsernamePasswordAuthenticationToken(principalUser, null, List.of(new SimpleGrantedAuthority(principalUser.getRole())));

          token.setDetails(new WebAuthenticationDetails(request));
          SecurityContextHolder.getContext().setAuthentication(token);


          the WebAuthenticationDetails from the doc:
          Records the remote address and will also set the session Id if a session already exists (it won't create one).



          for more info about the login/logout process take a look at:
          https://github.com/pezetem/spring-security-angular-skeleton/blob/master/src/main/java/com/pezetem/blog/code/spring_security_custom_authorizers/security/SecurityController.java



          UPDATE:



          ok, there could be another reason why it is not working for you. Spring Security adds default prefix to the roles. It is equal to ROLE_. It means that when you have an endpoint configured for .hasAuthority("STUDENT") role must be equal to ROLE_STUDENT, take a look at the line where you create a user, you assign role with Role.STUDENT and the enum value should be ROLE_STUDENT not STUDENT







          share|improve this answer














          share|improve this answer



          share|improve this answer








          edited Nov 15 '18 at 18:50

























          answered Nov 14 '18 at 22:48









          pezetempezetem

          1,6011126




          1,6011126













          • thanks for your response..but it didn't help me

            – SURAJ KUMAR
            Nov 15 '18 at 17:31











          • place, take a look at the updated answer, there might be an issue with role prefix, you are missing for Role.STUDENT

            – pezetem
            Nov 15 '18 at 18:51



















          • thanks for your response..but it didn't help me

            – SURAJ KUMAR
            Nov 15 '18 at 17:31











          • place, take a look at the updated answer, there might be an issue with role prefix, you are missing for Role.STUDENT

            – pezetem
            Nov 15 '18 at 18:51

















          thanks for your response..but it didn't help me

          – SURAJ KUMAR
          Nov 15 '18 at 17:31





          thanks for your response..but it didn't help me

          – SURAJ KUMAR
          Nov 15 '18 at 17:31













          place, take a look at the updated answer, there might be an issue with role prefix, you are missing for Role.STUDENT

          – pezetem
          Nov 15 '18 at 18:51





          place, take a look at the updated answer, there might be an issue with role prefix, you are missing for Role.STUDENT

          – pezetem
          Nov 15 '18 at 18:51




















          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%2f53295260%2fhow-to-auto-login-after-successful-registration-in-spring-boot%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

          Florida Star v. B. J. F.

          Error while running script in elastic search , gateway timeout

          Adding quotations to stringified JSON object values