java - 找不到 UsernamePasswordAuthenticationToken 的 AuthenticationProvider - Spring-boot + Oauth2 : Restful API

标签 java spring hibernate spring-boot oauth-2.0

我正在尝试使用 Spring-boot 和使用 hibernate 的 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();
}
}

最佳答案

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

@Autowired
CustomAuthenticationProvider customAuthenticationProvider;

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

关于java - 找不到 UsernamePasswordAuthenticationToken 的 AuthenticationProvider - Spring-boot + Oauth2 : Restful API,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34573168/

相关文章:

java私有(private)访问修饰符可以在类之外访问吗?

java - 使用 Matcher.find() 时出现 IndexOutOfBoundsException

java - ArrayOutOfBounds 异常合并排序

java - 删除android中链表的链表

java - Spring MVC 区域设置更改不起作用

java - 添加两个变量后出现 BeanCreationException

java - Spring 正常关闭 - 请求方法不支持

java - Spring 数据休息 : Limit sending values on Update method

C3P0ConnectionProvider.getConnection() 中的 java.lang.NullPointerException

java - JPA 实体图和分页