Я получаю «Неверный токен» при доступе к службе ресурсов с помощью токена.
Вот код OAuth2Configuration.java
@Configuration
@EnableAuthorizationServer
public class OAuth2Configuration extends AuthorizationServerConfigurerAdapter {
@Autowired
private DataSource dataSource;
@Autowired
private PasswordEncoder passwordEncoder;
@Autowired
@Qualifier("customUserDetailService")
private UserDetailsService userDetailsService;
@Autowired
private ClientDetailsService clientDetailsService;
@Autowired
@Qualifier("authenticationManagerBean")
private AuthenticationManager authenticationManager;
@Bean("tokenStore")
public TokenStore getTokenStore() {
return new JdbcTokenStore(dataSource);
}
@Override
public void configure(ClientDetailsServiceConfigurer clients) throws Exception {
clients.jdbc(dataSource).passwordEncoder(passwordEncoder);
}
@Override
public void configure(AuthorizationServerSecurityConfigurer oauthServer) throws Exception {
oauthServer.tokenKeyAccess("permitAll()").checkTokenAccess("isAuthenticated()");
}
@Override
public void configure(AuthorizationServerEndpointsConfigurer endpoints) throws Exception {
endpoints
.tokenStore(getTokenStore())
.authenticationManager(authenticationManager)
.userDetailsService(userDetailsService);
}
}
Вот WebSecurityConfiguration.java
@Configuration
public class WebSecurityConfiguration extends WebSecurityConfigurerAdapter {
@Autowired
@Qualifier("customUserDetailService")
private UserDetailsService userDetailsService;
@Bean
public PasswordEncoder passwordEncoder() {
return PasswordEncoderFactories.createDelegatingPasswordEncoder();
}
@Bean
@Override
public AuthenticationManager authenticationManagerBean() throws Exception {
return super.authenticationManagerBean();
}
@Override
protected void configure(HttpSecurity http) throws Exception {
http.csrf().disable()
.authorizeRequests()
.anyRequest().authenticated();
}
@Override
public void configure(AuthenticationManagerBuilder auth) throws Exception {
auth.userDetailsService(userDetailsService).passwordEncoder(passwordEncoder());
}
}
Ниже упоминается файл application.yml
.
server:
port: 9999
info:
app:
name: token-service
description: token-service
version: 1.0.0
endpoints:
routes:
sensitive: false
spring:
datasource:
url: jdbc:mysql://localhost:3306/authDBTest?useSSL=false
username: root
password: root123
driver-class-name: com.mysql.jdbc.Driver
initialization-mode: never
platform: mysql
jpa:
properties:
hibernate:
dialect: org.hibernate.dialect.MySQL5Dialect
hibernate:
naming:
physical-strategy: org.hibernate.boot.model.naming.PhysicalNamingStrategyStandardImpl
check-user-scopes: false
logging:
level:
org:
hibernate:
type: trace
security:
basic:
enabled: false
ignored: /css/**,/js/**,/favicon.ico,/webjars/**
oauth2:
resource:
id: auth-service
token-info-uri: http://localhost:9999/oauth/check_token
client:
access-token-uri: http://localhost:9999/oauth/token
eureka:
client:
registerWithEureka: true
fetchRegistry: true
serviceUrl:
defaultZone: ${vcap.services.discovery-service.credentials.uri:http://localhost:8761}/eureka/
instance:
preferIpAddress: true
Сервер ресурсов - это отдельная служба, а здесь ResourceServerConfig.java
@Configuration
@EnableResourceServer
public class ResourceServerConfig extends ResourceServerConfigurerAdapter {
private static final String RESOURCE_ID = "auth-service";
@Override
public void configure(ResourceServerSecurityConfigurer resources) {
resources.resourceId(RESOURCE_ID).stateless(false);
}
}
Ниже упоминается контроллер ресурсов .
@CrossOrigin(origins = "*", allowedHeaders = "*")
@RestController
@RequestMapping("/")
public class ResourceController {
@GetMapping(value = "/user", produces = MediaType.APPLICATION_JSON_VALUE)
public String getName(){
return "user";
}
}
Ниже упоминается application.yml
, который я использовал в службе ресурсов.
server:
port: 9099
spring:
application:
name: resource-service
security:
basic:
enabled: false
oauth2:
resource:
id: auth-service
service-id: ${PREFIX:}resource
eureka:
client:
registerWithEureka: true
fetchRegistry: true
serviceUrl:
defaultZone: ${vcap.services.discovery-service.credentials.uri:http://localhost:8761}/eureka/
instance:
preferIpAddress: true
Вот ответ службы авторизации.
{
"access_token": "access_token",
"token_type": "bearer",
"refresh_token": "refresh_token",
"expires_in": 3599,
"scope": "READ WRITE"
}
После Я пользуюсь этим токеном доступа для http://localhost:9099/user
, и каждый раз появляется ошибка ниже.
{
"error": "invalid_token",
"error_description": "Invalid access token: access_token"
}
Пожалуйста, помогите мне решить эту проблему. Любая помощь или обходные пути действительно приветствуются.