Search code examples
javaspringspring-bootspring-securityspring-oauth2

Spring OAuth2 Custom Authentication Manager ClassCastException


i've a big problem and no idea how to solve it... I need to use customAuthenticationManager for third party log-in in my spring boot application, but when i declare custom authenticator i get :

Handling error:

ClassCastException, java.lang.String cannot be cast to com.nexus.demooauth.models.User

If i use default authentication manager (the one that comes with spring boot) everything works fine.

Here is Websecurity.java

@Configuration 
public class WebSecurity extends WebSecurityConfigurerAdapter {

@Bean
public AuthenticationManager customAuthenticationManager() throws Exception {
    return new CustomAuthenticationManager();
}

AuthorizationServerConfig.java

@Configuration
@EnableAuthorizationServer
public class AuthorizationServerConfig extends AuthorizationServerConfigurerAdapter {


@Autowired
UserDetailsService customUserDetailsService;

@Autowired
DataSource dataSource;

@Autowired
private AuthenticationManager authenticationManager;        

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

@Override
public void configure(AuthorizationServerEndpointsConfigurer configurer) throws Exception {
    //configurer.userDetailsService(customUserDetailsService);
    configurer.authenticationManager(authenticationManager);
    configurer.tokenEnhancer(tokenEnhancer());
}

@Bean
public TokenEnhancer tokenEnhancer() {
    return new CustomTokenEnhancer();
}


@Override
public void configure(ClientDetailsServiceConfigurer clients) throws Exception {
    clients.inMemory().withClient("gigy").secret("secret").accessTokenValiditySeconds(8400)
    .scopes("read", "write").authorizedGrantTypes("password", "refresh_token");
}

CustomAuthenticationManager.java

 @Service
    public class CustomAuthenticationManager implements AuthenticationManager{

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

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

    String username = authentication.getName();
    String pw       = authentication.getCredentials().toString();
    logger.info("was here" + username.toString() + " , " + pw.toString());

    return new UsernamePasswordAuthenticationToken(username, pw, authentication.getAuthorities());

}

It actually prints in logger

2018-05-15 17:58:34.453  INFO 7212 --- [nio-8089-exec-1] c.n.d.s.CustomAuthenticationManager      : was heretest , test

When debugging it breaks when returning new UsernamePasswordAuthenticationToken in some obfuscated class.


Solution

  • Actually found the anserw. The problem was in CustomTokenEnhancer that was making this invalid conversion.