AuthenticationProvider无法进行身份验证

时间:2018-05-29 20:14:57

标签: java spring spring-boot authentication

我在java spring boot中进行自定义令牌身份验证,但它不起作用。请帮忙。

这是我的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);
    }
}

这是我的过滤器。请求首先进入过滤器。令牌字符串位于请求标头中。我从中创建了一个UsernamePasswordAuthenticationToken对象:

@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);
            }
        }
    }

}

这是我的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);
    }
}

我做了调试。过滤器触发并执行.doFilter(请求,响应),但AuthenticationProvider甚至没有启动。

我做错了什么?

1 个答案:

答案 0 :(得分:0)

事实证明,身份验证提供程序正在进行身份验证,但数据库存在问题。我重新创建了数据库,现在它可以工作。

此外,一旦程序运行,调试就无法在身份验证提供程序中输入authenticate-method。这就是我的调试失败的原因。

我困惑的原因还在于我的小提琴手没有向我展示GET请求中的JSON,但这是我解决的Fiddler的一个问题。

现在我已经对它进行了更详细的测试,一切正常。