Skip to content

UsernamePasswordAuthenticationToken cannot be cast to JWTToken #1

@dnjiao

Description

@dnjiao

Hi, I followed your code to implement JWT based authentication. However I got the following error for the line "JWTToken jwtToken = (JWTToken) authentication" in JWTAuthenticationProvider:

java.lang.ClassCastException: org.springframework.security.authentication.UsernamePasswordAuthenticationToken cannot be cast to org.mdacc.rists.ristore.ws.security.jwt.JWTToken

My detailed code can be found here

JWTAuthenticationFilter is added my web security config in Spring Boot:

@Configuration
@EnableWebSecurity
@PropertySource(value = { "classpath:/config/application.properties" })
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
   @Autowired
    private RestAuthenticationSuccessHandler authenticationSuccessHandler;
    @Autowired
    private RestAuthenticationEntryPoint restAuthenticationEntryPoint;

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

            .httpBasic()
            .and()
            .addFilterBefore(new CORSFilter(), ChannelProcessingFilter.class)
            .addFilterAfter(new JWTAuthenticationFilter(authenticationManagerBean()),
                    AnonymousAuthenticationFilter.class)
            .csrf().disable()
            .sessionManagement().sessionCreationPolicy(
                    SessionCreationPolicy.STATELESS)
            .and()
            .exceptionHandling()
            .authenticationEntryPoint(restAuthenticationEntryPoint)
            .and()
            .authorizeRequests()
                .antMatchers("/login").permitAll()
                .antMatchers("/ristore/**").authenticated()
                .anyRequest().authenticated()
                .and()

            .formLogin()
                .successHandler(authenticationSuccessHandler)
                .failureHandler(new SimpleUrlAuthenticationFailureHandler());
    }

    @Configuration
    protected static class AuthenticationConfiguration extends
            GlobalAuthenticationConfigurerAdapter {

        @Override
        public void init(AuthenticationManagerBuilder auth) throws Exception { 
            //omitting LDAP config   
            auth.authenticationProvider(new JWTAuthenticationProvider());
        }
    }
}

I got this error when I submit the login form created with AngularJS. Post request with user credentials to "http://localhost:8080/login" ends up with 505 (Internal Server Error). Why am I getting this error?

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions