简体   繁体   中英

Spring boot security principal user getting changed to newly logged in user details

Am using spring boot 2.2.4 with spring security. And the problem am facing is every time am logging in with a new user the principal username is getting reset to the newly logged in user's details, Why. However as I have observed the session ID remains correct. I don't understand this behavior. Any idea?

@EnableWebSecurity
public class IctSecurityConfiguration extends WebSecurityConfigurerAdapter {

    @Autowired
    PasswordEncoder passwordEncoder;

    @Autowired
    private UserDetailsService userDetailsService;


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


    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.authorizeRequests()
                //URLs matching for access rights
                .antMatchers("/").permitAll()
                .antMatchers("/signup").permitAll()
                .antMatchers("/signin").permitAll()
                .antMatchers("/ict/**/**").permitAll()
                .antMatchers("/user/queue/reply").hasAnyAuthority(RolesConst.APP_USER)
                .antMatchers("/find").hasAnyAuthority(RolesConst.APP_USER)
                //.anyRequest().authenticated()
                .and()
                //form login
                .csrf().disable().formLogin()
                .loginPage("/login")
                .failureUrl("/login?error=true")
                .defaultSuccessUrl("/dashboard")
                .and()
                //logout
                .logout()
                .logoutRequestMatcher(new AntPathRequestMatcher("/logout"))
                .logoutSuccessUrl("/login").and()
                .exceptionHandling()
                .accessDeniedPage("/access-denied");
    }

    @Bean
    public PasswordEncoder passwordEncoder() {
        return new BCryptPasswordEncoder();
        //return NoOpPasswordEncoder.getInstance();
    }

}

UserDetails service

@Service
public class IctUserDetailsService implements UserDetailsService {

    @Autowired
    private UserRepository userRepository;

    @Override 
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException { 
        //return new IctUserDetails(username);
        Optional<UserEntity> user = userRepository.findByUsername(username);
        user.orElseThrow(() -> new UsernameNotFoundException("Not found: " + username));
        //UserController.groupname(username);
        return user.map(IctUserDetails::new).get();
    }

}

UserDetails class

   public class IctUserDetails implements UserDetails {

    private static final long serialVersionUID = 1L;

    public static String username;
    private String password;

    private List<? extends GrantedAuthority> authorities;


    public IctUserDetails() {
    }

    public IctUserDetails(UserEntity userEntity) {
        this.username = userEntity.getUsername();


        this.password = userEntity.getPassword();
        List<SimpleGrantedAuthority> authoriteis = getRoleAuthoritiesFromUserEntity(userEntity);
        this.authorities = authoriteis;
    }

    @Override
    public Collection<? extends GrantedAuthority> getAuthorities() {
        return authorities;
    }

    @Override
    public String getPassword() {
        return password;
    }

    @Override
    public String getUsername() {
        return this.username;
    }

    @Override
    public boolean isAccountNonExpired() {
        return true;
    }

    @Override
    public boolean isAccountNonLocked() {
        return true;
    }

    @Override
    public boolean isCredentialsNonExpired() {
        return true;
    }

    @Override
    public boolean isEnabled() {
        return true;
    }

    /**
     * Get list of role authorities from current user entity
     * @param userRoleEntities
     * @return
     */
    @Transactional
    private List<SimpleGrantedAuthority> getRoleAuthoritiesFromUserEntity(UserEntity userEntity) {
        Collection<UserRoleEntity> userRoleEntities = userEntity.getUserRoleEntities();
        List<SimpleGrantedAuthority> authoriteis = userRoleEntities
                .stream()
                .map(ur -> ur.getRole().getRoleName())
                .map(SimpleGrantedAuthority::new)
                .collect(Collectors.toList());
        return authoriteis;
    }

}

So, this was the problem. I had declared username in my UserDetails class as static public static String username; .

I have changed this to private String username; and all is good now. Thanks.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM