oauth / check_token не возвращает новую обновленную информацию токена - PullRequest
0 голосов
/ 28 февраля 2020

Я реализую функцию Spring Oauth2 для моего проекта. Все работает нормально, за исключением того, что новая измененная информация о существующем токене не обновляется, поскольку я пытаюсь обновить значения в связанных таблицах в базе данных mysql. Вот схема моих таблиц и некоторые примеры данных

create table oauth_client_details (
  client_id VARCHAR(256) PRIMARY KEY,
  resource_ids VARCHAR(256),
  client_secret VARCHAR(256),
  scope VARCHAR(256),
  authorized_grant_types VARCHAR(256),
  web_server_redirect_uri VARCHAR(256),
  authorities VARCHAR(256),
  access_token_validity INTEGER,
  refresh_token_validity INTEGER,
  additional_information VARCHAR(4096),
  autoapprove VARCHAR(256)
);
create table if not exists oauth_access_token (
  token_id VARCHAR(255),
  token LONG VARBINARY,
  authentication_id VARCHAR(255) PRIMARY KEY,
  user_name VARCHAR(255),
  client_id VARCHAR(255),
  authentication LONG VARBINARY,
  refresh_token VARCHAR(255)
);

create table if not exists oauth_refresh_token (
  token_id VARCHAR(255),
  token LONG VARBINARY,
  authentication LONG VARBINARY
);


CREATE TABLE `users` (
    `username` VARCHAR(50) NOT NULL,
    `password` VARCHAR(50) NOT NULL,
    `enabled` TINYINT(1) NOT NULL,
    PRIMARY KEY (`username`)
) ;

CREATE TABLE authorities (
  username VARCHAR(50) NOT NULL,
  authority VARCHAR(50) NOT NULL,
  FOREIGN KEY (username) REFERENCES users(username)
);

CREATE UNIQUE INDEX ix_auth_username
  on authorities (username,authority);

INSERT INTO users (username, password, enabled)
  values ('user1',
    'password1',
    1);

INSERT INTO users (username, password, enabled)
  values ('user2',
    'password2',
    1);
INSERT INTO users (username, password, enabled)
  values ('user3',
    'password3',
    1);

INSERT INTO authorities (username, authority)
  values ('user1', 'ROLE_USER');


INSERT INTO authorities (username, authority)
  values ('user2', 'ROLE_USER');


INSERT INTO authorities (username, authority)
  values ('user3', 'ROLE_USER');

INSERT INTO oauth_client_details
(client_id, resource_ids, client_secret, scope, authorized_grant_types, web_server_redirect_uri, authorities, access_token_validity, refresh_token_validity, additional_information, autoapprove)
VALUES
  ('read-only-client', 'todo-services', NULL, 'read,write', 'implicit', 'http://localhost', NULL, 7200, 0, NULL, 'false');

INSERT INTO oauth_client_details
(client_id, resource_ids, client_secret, scope, authorized_grant_types, web_server_redirect_uri, authorities, access_token_validity, refresh_token_validity, additional_information, autoapprove)
VALUES
  ('curl-client', 'todo-services', 'client-secret', 'read,write', 'password,client_credentials', '', 'role_admin', 7200, 0, NULL, 'false');

INSERT INTO oauth_client_details
(client_id, client_secret)
VALUES
  ('resource-server', 'resource-server');

Мой сервер авторизации

@Configuration
@EnableAuthorizationServer
public class SecurityOAuth2Configuration extends AuthorizationServerConfigurerAdapter {

    @Autowired
    private AuthenticationManager authenticationManager;

    @Autowired
    DataSource dataSource;


    @Bean
    public JdbcClientDetailsService clientDetailsService() {
        return new JdbcClientDetailsService(dataSource);
    }

    @Bean
    public TokenStore tokenStore() {
        return new JdbcTokenStore(dataSource);
    }


    @Override
    public void configure(AuthorizationServerSecurityConfigurer oauthServer) throws Exception {
        oauthServer.tokenKeyAccess("permitAll()")
                   .checkTokenAccess("isAuthenticated()")
                   .allowFormAuthenticationForClients(); ;
    }

    @Override
    public void configure(ClientDetailsServiceConfigurer clients) throws Exception {
        clients.jdbc(dataSource);
    }

    @Override
    public void configure(AuthorizationServerEndpointsConfigurer endpoints) throws Exception {
        endpoints.authenticationManager(authenticationManager);
        endpoints.setClientDetailsService(clientDetailsService());
        endpoints      .tokenStore(tokenStore());

    }

    @Primary
    @Bean
    public RemoteTokenServices tokenService() {
        RemoteTokenServices tokenService = new RemoteTokenServices();       tokenService.setCheckTokenEndpointUrl(
                "http://localhost:8080/oauth/check_token");
        tokenService.setClientId("curl-client");
        tokenService.setClientSecret("client-secret");
        tokenService.setCheckTokenEndpointUrl("http://localhost:8080/oauth/check_token");
        return tokenService;
    }
}

Код моего сервера ресурсов:

@Configuration
@EnableResourceServer
public class SecurityConfiguration extends ResourceServerConfigurerAdapter {

    @Autowired
    private DataSource dataSource;


    @Autowired
    private AuthenticationEntryPoint authEntryPoint;

    @Override
    public void configure(HttpSecurity http) throws Exception {
        http
                .antMatcher("/**")
                .authorizeRequests()
                .antMatchers("/")
                .permitAll()
                .antMatchers("/user")
                .hasRole("USER")
                .anyRequest()
                .authenticated()
                .and().httpBasic()
                .authenticationEntryPoint(authEntryPoint);
    }

    @Autowired    
    public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
        auth.jdbcAuthentication().dataSource(dataSource);
    }

    @Override
    public void configure(ResourceServerSecurityConfigurer resources) throws Exception {

        resources.resourceId("todo-services");
    }
}

application.properties

spring.datasource.url=jdbc:mysql://localhost/demo_database
spring.datasource.username=root
spring.datasource.password=root
spring.datasource.driver-class-name=com.mysql.jdbc.Driver
debug=true

Функции создания токенов работают нормально http://localhost: 8080 / oauth / token возвращает

{
    "access_token": "4356c521-c59c-4ac8-9f30-c62915782d11",
    "token_type": "bearer",
    "expires_in": 7128,
    "scope": "read write"
}

localhost: 8080 / oauth / check_token? Token = 4356c521-c59 c -4ac8-9f30-c62915782d11 возвращает

{
    "aud": [
        "todo-services"
    ],
    "exp": 1582882181,
    "user_name": "user2",
    "authorities": [
        "ROLE_USER"
    ],
    "client_id": "curl-client",
    "scope": [
        "read",
        "write"
    ]
}

Однако, когда я меняю полномочия в таблице полномочий на «ROLE_ADMIN» пользователя 2 в рабочей среде mysql и go на URL localhost: 8080 / oauth / check_token? token = 4356c521-c59 c -4ac8-9f30-c62915782d11, значение полномочий не обновляется

{
    "aud": [
        "todo-services"
    ],
    "exp": 1582882181,
    "user_name": "user2",
    "authorities": [
        "ROLE_USER"
    ],
    "client_id": "curl-client",
    "scope": [
        "read",
        "write"
    ]
}

, если я удаляю этот токен из таблицы oauth_access_token, то каким-то образом получил правильный ответ, как я тестирую в почтальоне

{
    "error": "invalid_token",
    "error_description": "Token was not recognised"
}

Есть ли что-то, что я пропускаю?

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...