简体   繁体   中英

Spring Security - UserDetailsService implementation class is not invoked when logging in from angular 4 client

I am securing my spring application with spring security. I have implemented UserDetailService for authenticating user. When logging in from Angular 4, UserDetailService is not invoked and user is not found.

The reason I found is I have not used formLogin() in SecurityConfig.java. For that I have added httpBasic() but its not working. Is there any configurations missing ?

SecurityConfig.java

@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {

    @Autowired
    private LoginUserDetailService loginUserDetailService;

    @Autowired
    private BCryptPasswordEncoder bCryptPasswordEncoder;

    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {

        auth.userDetailsService(loginUserDetailService).passwordEncoder(bCryptPasswordEncoder);
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {

        http.cors().and()
        .authorizeRequests()
        .antMatchers("/login","/logout", "/home").permitAll()
        .anyRequest().fullyAuthenticated().and()
        .logout()
        .permitAll()
        .logoutRequestMatcher(new AntPathRequestMatcher("/logout", "POST"))
        .and()
        .httpBasic().and()
        .csrf().disable();
    }

    @Override
    public void configure(WebSecurity web) throws Exception {

        web.ignoring().antMatchers("/resources/**", "/static/**", "/css/**", "/js/**", "/images/**");

    }

}

Controller

@RequestMapping("/login")
    public Principal user(Principal principal) {
        logger.info("user logged " + principal);
        return principal;
    }

LoginUserDetailService

@Service("loginUserDetailService")
public class LoginUserDetailService implements UserDetailsService {

    @Autowired
    UserRepository userRepository;

    @Override
    @Transactional
    public UserDetails loadUserByUsername(String email) throws UsernameNotFoundException {
        System.out.println("Login User Detail Service");
        System.out.println("email: "+email);
        UserEntity user = userRepository.findByEmail(email);
        if (user != null) {
            System.out.println("User found ");
        }
        else {
            System.out.println("User not found");
        }
        Set<GrantedAuthority> authorities = getUserAuthority(user.getRoles());
        System.out.println("Authorities of user : " + email);
        authorities.forEach(a -> System.out.println(a));

        return buildUserForAuthentication(user, authorities);
    }

    private Set<GrantedAuthority> getUserAuthority(Set<RoleEntity> userRoles) {
        System.out.println("Roles: ");
        for(RoleEntity role : userRoles) {
            System.out.println(role);
        }
        Set<GrantedAuthority> authorities = new HashSet<GrantedAuthority>();
        for (RoleEntity role : userRoles) {
            authorities.add(new SimpleGrantedAuthority(role.getRole()));
            role.getPermissions().stream().map(p -> new SimpleGrantedAuthority(p.getPermission()))
                    .forEach(authorities::add);
        }
        System.out.println("Authorities :");
        for(GrantedAuthority authority : authorities)
        {
            System.out.println(authority);
        }

        return authorities;
    }

    private UserDetails buildUserForAuthentication(UserEntity user, Set<GrantedAuthority> authorities) {
        return new org.springframework.security.core.userdetails.User(user.getEmail(), user.getPassword(),
                user.getActive(), true, true, true, authorities);
    }
}

Log

2018-10-24 12:45:26.532  INFO 9660 --- [nio-8080-exec-2] c.m.c.AuthenticationController           : user logged null

它通过在 http GET 方法的请求标头中传递用户凭据而不是从 angular 客户端将凭据作为 http POST 方法的主体传递来解决。

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