简体   繁体   中英

AuthenticationProvider not authenticating

I am making custom token authentication in java spring boot, but it doesn't work. Please help.

This is my SecurityConfigurerAdapter :

@Configuration
@EnableWebSecurity
@EnableGlobalMethodSecurity(securedEnabled = true,prePostEnabled=true)
public class MyWebSecurityConfigurerAdapter extends WebSecurityConfigurerAdapter {

    @Autowired
    private BokiAuthenticationProvider bokiAuthenticationProvider;

    @Autowired
    private MyCredentialsFilter myCredentialsFilter;

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

        // request handling
        http.authorizeRequests()
            .antMatchers(HttpMethod.GET, "/users").hasRole("USER")
            .antMatchers(HttpMethod.GET, "/users/*").hasRole("USER")
            .antMatchers(HttpMethod.POST, "/users").permitAll()
            .antMatchers(HttpMethod.PATCH, "/users/*").hasRole("USER")
            .antMatchers(HttpMethod.DELETE, "/users/*").hasRole("USER")
            .antMatchers(HttpMethod.POST, "/login").permitAll()
            ;

        // disable csrf
        http.csrf().disable();

        // app session is stateless
        http.sessionManagement()
            .sessionCreationPolicy(SessionCreationPolicy.STATELESS);        

        http.addFilterBefore(myCredentialsFilter, UsernamePasswordAuthenticationFilter.class);
    }

    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.eraseCredentials(false)
            .authenticationProvider(bokiAuthenticationProvider);
    }
}

This is my filter. The request comes into the filter first. The token string is in the request header. I make a UsernamePasswordAuthenticationToken object out of it :

@Component
public class CredentialsFilter extends OncePerRequestFilter{

    @Autowired
    private MyCriptoService myCriptoService;

    public CredentialsFilter(){
        super();
    }

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain chain)
            throws ServletException, IOException {

        if(request.getRequestURI().contains("login")){
            chain.doFilter(request, response);
        }else{
            String token = request.getHeader("MyTokenHeader");
            String username = myCriptoService.getUsernameFromToken(token);
            if (username!=null && SecurityContextHolder.getContext().getAuthentication()==null){
                UsernamePasswordAuthenticationToken 
                authentication = new UsernamePasswordAuthenticationToken(
                                        username, 
                                        myCriptoService.getPasswordFromToken(token), 
                                        myCriptoService.getAuthoritiesFromToken(token));

                SecurityContextHolder.getContext().setAuthentication(authentication);
                chain.doFilter(request, response);
            }
        }
    }

}

And this is my AuthenticationProvider :

@Component
public class BokiAuthenticationProvider implements AuthenticationProvider {

    @Autowired
    private MyUserRepository myUserRepository;

    @Autowired
    private MyCriptoService myCryptoService;

    @Override
    public Authentication authenticate(Authentication auth) throws AuthenticationException {
        String username = auth.getName();

        if(username!=null && !"".equals(username)){
            MyUserJPA jpa = myUserRepository.findByUsername(username);

            if(jpa!=null){
                String password = auth.getCredentials().toString();
                if(myCryptoService.checkPasswords(password, jpa.getPassword())){

                    @SuppressWarnings("unchecked")
                    List<SimpleGrantedAuthority> authorities = (List<SimpleGrantedAuthority>) auth.getAuthorities();

                    return new UsernamePasswordAuthenticationToken(
                            jpa.getUsername(),
                            null,
                            authorities);
                }
                throw new MyBadCredentialsException("Passwords is missing or invalid.");
            }
            throw new MyBadCredentialsException("There is no user with username = "+username);
        }

        throw new MyBadCredentialsException("You did not provide a username.");
    }

    @Override
    public boolean supports(Class<?> authentication) {
        return authentication.equals(UsernamePasswordAuthenticationToken.class);
    }
}

I did debugging. The filter fires and does the .doFilter(request,response), but the AuthenticationProvider doesn't even start.

What am i doing wrong ?

It turns out that authentication provider was authenticating, but there was a problem with the database. I recreated the database, and now it works.

Also, it is impossible for debugging to enter the authenticate-method in the authentication provider once the program is running. That was why my debug was failing.

The source of my confusion was also that my fiddler was not displaying me the JSON from the GET request, but that was an issue with the Fiddler which i solved.

Now I have tested it in more detail now, and everything is working.

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