首页 > 解决方案 > 在 Spring Boot 中使用 OAuth2 保护 Spring REST 服务的问题

问题描述

我一直在尝试通过在我的应用程序中实现 OAuth2 来保护我的 spring rest webs 服务。我一直在关注本教程来实现它。

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

这是我的主要文件代码:

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 令牌。请看以下截图: 在此处输入图像描述

在此处输入图像描述

标签: springspring-bootoauth-2.0spring-rest

解决方案


我已经将这一行与您所拥有的内容逐行复制到一个新项目中,并且一切都按预期工作,与您在这里所拥有的完全相同。我的建议是检查您的依赖关系。我在 2.3 版中使用 spring-boot、spring-boot-starter-oauth2-client、spring-boot-starter-oauth2-resource-server、spring-boot-starter-security 和 spring-boot-starter-web .5.释放。


推荐阅读