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

时间:2020-11-05 18:47:56

标签: spring spring-boot oauth-2.0 spring-rest

我一直在尝试通过在应用程序中实现OAuth2来保护我的Spring Rest Web服务。我一直在关注this tutorial来实现它。

我已经类似地实现了它,但是由于某种原因,当我用邮递员访问/ 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令牌。请查看以下屏幕截图: enter image description here

enter image description here

1 个答案:

答案 0 :(得分:2)

我已经将这行代码与您拥有的内容复制到了一个新项目中,并且一切都按预期运行,并且与您在此处的内容完全一样。我的建议是检查您的依赖关系。我将其与Spring Boot,spring-boot-starter-oauth2-client,spring-boot-starter-oauth2-resource-server,spring-boot-starter-security和spring-boot-starter-web一起使用,所有版本为2.3 .5。发布。

相关问题