【问题标题】:No AuthenticationProvider found for UsernamePasswordAuthenticationToken - Spring-boot + Oauth2: Restful API找不到 UsernamePasswordAuthenticationToken 的 AuthenticationProvider - Spring-boot + Oauth2:Restful API
【发布时间】:2016-04-07 00:06:05
【问题描述】:

我正在尝试使用休眠构建一个带有 Spring-boot 和 oauth2 的 Restful API。

我已经制作了一个 CustomAuthenticationProvider 来对数据库中的用户进行身份验证,但我得到了服务器的以下响应

注意: json 响应。

error": "unauthorized",
"error_description": "No AuthenticationProvider found for org.springframework.security.authentication.UsernamePasswordAuthenticationToken"
}

这是我的 CustomAuthenticationProvider:

@Component
public class CustomAuthenticationProvider implements AuthenticationProvider {
    public CustomAuthenticationProvider() {
        super();
    }
    @Autowired
    private UsuarioDAO user;

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

    Usuarios us = null;
    try {
        us = user.userAuthentication(username, password);
    } catch (Exception ex) {
    }
    if (us != null) {
        final List<GrantedAuthority> grantedAuths = new ArrayList<>();
        grantedAuths.add(new SimpleGrantedAuthority("ROLE_ADMIN"));
        final UserDetails principal = new User(username, password, grantedAuths);
        final Authentication authentication = new UsernamePasswordAuthenticationToken(principal, password, grantedAuths);
        us = null;
        return authentication;
    } else {
        throw new BadCredentialsException("Bad Credentials");
    }
}

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

}

这是我的 WebSecurityConfiguration:

@Configuration
@EnableWebSecurity
public class WebSecurityConfiguration extends WebSecurityConfigurerAdapter {

@Override
@Bean
public AuthenticationManager authenticationManagerBean() throws Exception {
    return super.authenticationManagerBean();
}
}

【问题讨论】:

    标签: java spring hibernate spring-boot oauth2


    【解决方案1】:

    您必须配置 Spring Security 以使用您的自定义身份验证提供程序。 将以下代码添加到您的 WebSecurityConfiguration 类:

    @Autowired
    CustomAuthenticationProvider customAuthenticationProvider;
    
    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.authenticationProvider(customAuthenticationProvider);
    }
    

    【讨论】:

      猜你喜欢
      • 2011-12-31
      • 2018-12-13
      • 2016-05-13
      • 1970-01-01
      • 2020-11-05
      • 1970-01-01
      • 2013-01-27
      • 2016-08-03
      • 1970-01-01
      相关资源
      最近更新 更多