![](/img/trans.png)
[英]Spring boot 2 + Oauth2 - Securing the Rest Calls in Microservices
[英]Issue in securing Spring REST service With OAuth2 in Spring Boot
我一直在尝试通过在我的应用程序中实现 OAuth2 来保护我的 spring 休息网络服务。 我一直在关注本教程来实现它。
我已经类似地实现了它,但是由于某种原因,当我用邮递员点击 /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.释放。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.