【发布时间】:2016-04-11 12:34:09
【问题描述】:
我已经使用spring-boot 框架成功创建了一个网络服务。现在我想用 OAuth2(使用 spring)来保护我的网络服务,并且对此有几个问题:
根据我的研究,spring 提供了某种默认 URL 来请求访问令牌 (baseURL/oauth/token)。我已经使用邮递员测试了 URL,并返回了有效的访问令牌(使用 client_credentials 授权类型),但没有刷新令牌。但是此方法不适用于grant_type=password,并导致以下错误响应:
{"error":"invalid_grant","error_description":"Bad credentials"}
我的spring应用日志InvalidGrantException。
我用来测试grant_type=password的curl如下:
curl -v -X POST -H "Content-Type: application/json" -H "Authorization: Basic base64encodedclientidandsecret" 'http://localhost:8888/oauth/token?grant_type=password&username=user&password=1234'
我没有使用邮递员进行测试,因为它不支持grant_type=password。
如何让 spring 使用 grant_type=password 同时返回 accessToken 和 refreshToken?
我的配置有什么问题吗?
我的spring应用(配置)如下:
@Configuration
@ComponentScan
@EnableAutoConfiguration(exclude = { MongoAutoConfiguration.class, MongoDataAutoConfiguration.class })
@SpringBootApplication
public class CsWebServerApplication {
public static final String RESOURCE_ID = "myresource";
public static final String CLIENT_ID = "myapplication";
public static final String CLIENT_SECRET = "application_secret";
public static void main(String[] args) {
SpringApplication.run(MyWebServerApplication.class, args);
}
@Configuration
@EnableAuthorizationServer
protected static class OAuth2Config extends AuthorizationServerConfigurerAdapter {
@Inject
private AuthenticationManager authenticationManager;
@Override
public void configure(AuthorizationServerEndpointsConfigurer endpoints) throws Exception {
endpoints.authenticationManager(authenticationManager);
}
@Override
public void configure(ClientDetailsServiceConfigurer clients) throws Exception {
clients.inMemory().withClient(CLIENT_ID)
.authorizedGrantTypes("client_credentials", "password", "refresh_token")
.authorities("ROLE_CLIENT", "ROLE_TRUSTED_CLIENT")
.scopes("read", "write", "trust")
.secret(CLIENT_SECRET);
}
@Override
public void configure(AuthorizationServerSecurityConfigurer oauthServer) throws Exception {
super.configure(oauthServer);
}
}
@Configuration
@EnableResourceServer
protected static class ResourceConfig extends ResourceServerConfigurerAdapter {
@Override
public void configure(HttpSecurity http) throws Exception {
http.requestMatchers().antMatchers("/*", "/admin/beans").and().authorizeRequests().anyRequest()
.access("#oauth2.hasScope('read')");
}
@Override
public void configure(ResourceServerSecurityConfigurer resources) throws Exception {
resources.resourceId(RESOURCE_ID);
}
}
@Configuration
@EnableWebSecurity
protected static class WebConfigurer extends WebSecurityConfigurerAdapter {
@Override
protected void configure(HttpSecurity http) throws Exception {
super.configure(http);
}
@Override
public void configure(WebSecurity webSecurity) throws Exception {
webSecurity.ignoring()
// All of Spring Security will ignore the requests
.antMatchers("/accessibleservices/**")
}
}
}
【问题讨论】:
标签: java spring spring-boot spring-security-oauth2