无法通过BasicAuth

时间:2019-01-27 11:17:13

标签: java spring java-ee oauth-2.0 token

我正在尝试使用令牌实现oauth。一切似乎都很好,但是在POST

之后
http://localhost:8080/oauth/token?grant_type=password

已设置BasicAuth admin / admin(我的数据库中的用户具有登录名admin和密码admin)

我得到了具有基本身份验证的窗口,当我写了登录名和密码时,我一次又一次地获得了具有基本身份验证的窗口。

@Configuration
@EnableResourceServer
public class ResourceServerConfig extends ResourceServerConfigurerAdapter {
    @Override
    public void configure(HttpSecurity http) throws Exception {
        http
                .authorizeRequests()
                .antMatchers("/**").authenticated();
    }
}

@Configuration
@EnableAuthorizationServer
public class AuthorizationServerConfig extends AuthorizationServerConfigurerAdapter {

    @Autowired
    private AuthenticationManager authenticationManager;

    @Override
    public void configure(AuthorizationServerSecurityConfigurer security) throws Exception {
        security
                .tokenKeyAccess("permitAll()")
                .checkTokenAccess("isAuthenticated()")
                .allowFormAuthenticationForClients();
    }

    @Override
    public void configure(ClientDetailsServiceConfigurer clients) throws Exception {
        clients.inMemory().withClient("android-client")
                .authorizedGrantTypes("client-credentials", "password","refresh_token")
                .authorities("ROLE_CLIENT", "ROLE_ANDROID_CLIENT")
                .scopes("read", "write", "trust")
                .resourceIds("oauth2-resource")
                .accessTokenValiditySeconds(5000)
                .secret("android-secret").refreshTokenValiditySeconds(50000);
    }

    @Override
    public void configure(AuthorizationServerEndpointsConfigurer endpoints) throws Exception {
        endpoints.authenticationManager(authenticationManager)
                .allowedTokenEndpointRequestMethods(HttpMethod.GET, HttpMethod.POST);
    }
}

@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {

    @Autowired
    private UserRepository userRepository;

    @Bean
    public AuthenticationManager customAuthenticationManager() throws Exception {
        return authenticationManager();
    }

    private PasswordEncoder encoder =
            PasswordEncoderFactories.createDelegatingPasswordEncoder();

    @Autowired
    protected void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
        auth.userDetailsService(username -> {
            Optional<User> user = userRepository.findById(username);
            if (user.isPresent()) {
                return new org.springframework.security.core.userdetails.User(user.get().getUsername(), encoder.encode(user.get().getPassword()),
                        true, true, true, true, AuthorityUtils.createAuthorityList("USER"));
            } else {
                throw new UsernameNotFoundException("Could not find the user '" + username + "'");
            }
        });
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.authorizeRequests().anyRequest().fullyAuthenticated().and().httpBasic().and().csrf().disable();
    }
}

非常重要:
如果我删除ResourceServerConfig.java,则可以通过BasicAuth登录,在写了admin / admin之后,我从localhost:8080获得了JSON,但我希望通过令牌进行访问。

这是我的第一个RESTful API。
有人可以帮我吗?有人知道我在哪里犯错吗?
互联网上互联网上的信息很少。我该如何解决?

1 个答案:

答案 0 :(得分:1)

您需要发送clientId:“ android-client”和密码“ android-secret”作为基本身份验证凭据,而不是需要作为http参数(用户名=管理员密码)发送的用户(admin / admin)凭据= admin),例如“ grant_type”参数

所以您的请求应该是这样

  

http://localhost:8080/oauth/token?grant_type=password &username = admin&password = admin

将您的clientId和密码添加到基本身份验证凭据中