在 Spring 引导中使用 OAuth2 保护 Spring REST 服务的问题

Issue in securing Spring REST service With OAuth2 in Spring Boot

我一直在尝试通过在我的应用程序中实施 OAuth2 来保护我的 spring 休息网络服务。我一直在关注 this tutorial 以实现它。

我已经用类似的方式实现了它,但是由于某种原因,当我用邮递员点击 /oauth/token URL 时,它没有 return 我令牌。

这是我的主要文件代码:

1.AuthorizacionServerConfiguration.java

@Configuration
@EnableAuthorizationServer
public class AuthorizacionServerConfiguration extends AuthorizationServerConfigurerAdapter {
@Autowired
@Qualifier("authenticationManagerBean")
private AuthenticationManager authenticationManager;

@Autowired
private TokenStore tokenStore;

public void configure(ClientDetailsServiceConfigurer clients) throws Exception {
    clients.inMemory()
    .withClient("User")
    .authorizedGrantTypes(new String[] { "password" }).authorities(new String[] { "ROLE_CLIENT", "ROLE_TRUSTED_CLIENT", "USER" }).accessTokenValiditySeconds(120)
    .scopes(new String[] { "read" }).autoApprove(true)
    .secret(passwordEncoder().encode("12345"));
}

public PasswordEncoder passwordEncoder() {
    return (PasswordEncoder)new BCryptPasswordEncoder();
}

public void configure(AuthorizationServerEndpointsConfigurer endpoints) throws Exception {
    endpoints
    .authenticationManager(this.authenticationManager)
    .tokenStore(this.tokenStore);
}

@Bean
public TokenStore tokenStore() {
    return (TokenStore)new InMemoryTokenStore();
}
}

2.ResourceServerConfiguration.java

@EnableResourceServer
@RestController
public class ResourceServerConfiguration extends ResourceServerConfigurerAdapter {
    @SuppressWarnings("rawtypes")
    public void configure(HttpSecurity http) throws Exception {
    ((ExpressionUrlAuthorizationConfigurer.AuthorizedUrl)http.authorizeRequests()
            .antMatchers(new String[] { "/api/v1/**","/oauth/token", "/oauth/authorize **" 
    })).permitAll();
  }
}

3.WebSecurityConfiguration.java

@EnableWebSecurity
class WebSecurityConfiguration extends WebSecurityConfigurerAdapter {

@Bean
@Override
public UserDetailsService userDetailsService() {
    UserDetails user = User.builder().username("user1").password(passwordEncoder().encode("pass1")).roles(new String[] { "USER" }).build();
    return (UserDetailsService)new InMemoryUserDetailsManager(new UserDetails[] { user });
}

@Bean
public PasswordEncoder passwordEncoder() {
    return (PasswordEncoder)new BCryptPasswordEncoder();
}

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

当我试图用邮递员打它的时候。我收到未经授权的请求消息,而不是 OAuth 令牌。请看以下截图:

我已将此 line-for-line 与您所拥有的复制到一个新项目中,一切都按预期工作,与您在这里所拥有的完全一样。我的建议是检查您的依赖项。我让它与 spring boot、spring-boot-starter-oauth2-client、spring-boot-starter-oauth2-resource-server、spring-boot-starter-security 和 spring-boot-starter 一起使用-web 全部在版本 2.3.5.RELEASE.