spring - 在 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();
}
}
解决方案
我已经将这一行与您所拥有的内容逐行复制到一个新项目中,并且一切都按预期工作,与您在这里所拥有的完全相同。我的建议是检查您的依赖关系。我在 2.3 版中使用 spring-boot、spring-boot-starter-oauth2-client、spring-boot-starter-oauth2-resource-server、spring-boot-starter-security 和 spring-boot-starter-web .5.释放。
推荐阅读
- c# - 有没有办法在使用聚合()时将 AutoMapper 用于 mongo c# 投影表达式?
- azure - 如何撤消 kubectl 删除节点
- go - 即使两个文件名完全相同,文件未找到错误?
- reactjs - 如何在 React 应用程序刷新或通过 create-react-app 重新加载之前调用某些东西
- spring - 无法使用spring集成从文档中获取xml节点的数量
- javascript - 字符串内的换行符(React Native)
- java - 如何在 Mockito 测试中从 application.properties 加载属性
- python - python为什么要导入低版本的Numpy?
- javascript - 书签不自动填充
- c++ - 读取 .dat 文件并创建一个数组 C++