如何获取 Spring Boot 和 OAuth2 示例以使用默认凭据以外的密码授予凭据
2022-09-02 22:09:41
我正在遵循Dave Syer的基本Spring Boot OAuth2示例:https://github.com/dsyer/sparklr-boot/blob/master/src/main/java/demo/Application.java
@Configuration
@ComponentScan
@EnableAutoConfiguration
@RestController
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
@RequestMapping("/")
public String home() {
return "Hello World";
}
@Configuration
@EnableResourceServer
protected static class ResourceServer extends ResourceServerConfigurerAdapter {
@Override
public void configure(HttpSecurity http) throws Exception {
// @formatter:off
http
// Just for laughs, apply OAuth protection to only 2 resources
.requestMatchers().antMatchers("/","/admin/beans").and()
.authorizeRequests()
.anyRequest().access("#oauth2.hasScope('read')");
// @formatter:on
}
@Override
public void configure(ResourceServerSecurityConfigurer resources) throws Exception {
resources.resourceId("sparklr");
}
}
@Configuration
@EnableAuthorizationServer
protected static class OAuth2Config extends AuthorizationServerConfigurerAdapter {
@Autowired
private AuthenticationManager authenticationManager;
@Override
public void configure(AuthorizationServerEndpointsConfigurer endpoints) throws Exception {
endpoints.authenticationManager(authenticationManager);
}
@Override
public void configure(ClientDetailsServiceConfigurer clients) throws Exception {
// @formatter:off
clients.inMemory()
.withClient("my-trusted-client")
.authorizedGrantTypes("password", "authorization_code", "refresh_token", "implicit")
.authorities("ROLE_CLIENT", "ROLE_TRUSTED_CLIENT")
.scopes("read", "write", "trust")
.resourceIds("sparklr")
.accessTokenValiditySeconds(60)
.and()
.withClient("my-client-with-registered-redirect")
.authorizedGrantTypes("authorization_code")
.authorities("ROLE_CLIENT")
.scopes("read", "trust")
.resourceIds("sparklr")
.redirectUris("http://anywhere?key=value")
.and()
.withClient("my-client-with-secret")
.authorizedGrantTypes("client_credentials", "password")
.authorities("ROLE_CLIENT")
.scopes("read")
.resourceIds("sparklr")
.secret("secret");
// @formatter:on
}
}
}
该示例适用于这两种类型的授权,但密码授予使用 Spring Boot 默认安全用户(在启动期间回显“使用默认安全密码:927ca0a0-634a-4671-bd1c-1323a866618a”的用户)。
我的问题是,你如何覆盖默认的用户帐户,并实际依赖于WebSecurityConfig?我添加了一个这样的部分:
@Configuration
@EnableWebSecurity
@EnableGlobalMethodSecurity(prePostEnabled = true)
protected static class WebSecurityConfig extends WebSecurityConfigurerAdapter {
@Override
protected void configure(AuthenticationManagerBuilder authManagerBuilder)
throws Exception {
authManagerBuilder.inMemoryAuthentication().withUser("user")
.password("password").roles("USER");
}
}
但它似乎并没有覆盖默认的Spring用户/密码,即使文档建议它应该覆盖。
我错过了什么才能让它工作?