Я успешно создаю веб-сервис, используя фреймворк spring-boot. Теперь я хочу защитить свой веб-сервис с помощью OAuth2 (используя весну) и задать несколько вопросов относительно этого:Spring Security OAuth2 InvalidGrantException
Согласно моим исследованиям, весна предоставляет какой-то шаблон по умолчанию для запроса токена доступа (baseURL/oauth/token
). Я проверил URL-адрес с помощью почтового менеджера, и был возвращен действительный токен доступа (с использованием типа гранта client_credentials), но не токен обновления. Однако этот метод не работает с grant_type=password
и приводит следующий ответ ошибки:
{"error":"invalid_grant","error_description":"Bad credentials"}
Мои журналы весной приложений InvalidGrantException
.
Завиток Я использовал для тестирования grant_type=password
является следующее:
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
.
Как я могу получить весну, чтобы вернуть оба accessToken и refreshToken используя grant_type=password
?
В моей конфигурации есть что-то неправильное?
Моя весна приложение (конфигурация) выглядит следующим образом:
@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/**")
}
}
}