Я следовал инструкциям в этой главе учебника Spring Security:Использование Spring Security с JDBC бэкэндом
я построил приложение, которое работает отлично:
Затем я хотел реализовать бэкэнд JDBC, как описано в этом примере:
Я изменил первоначальный проект, как показано в примере приложения на GitHub:
Теперь кажется, что сервер ресурсов не в состоянии проверить маркеры больше на /uaa/user
конечной точке:
Выполненные команды:
Бревна от сервера OAuth2 авторизации
2016-02-28 12:35:08.762 INFO 1029 --- [nio-9999-exec-3] o.s.s.o.p.token.store.JdbcTokenStore : Failed to find access token for token 41b1504d-b985-40e0-80a8-94c09992aafe
2016-02-28 12:37:58.604 INFO 1029 --- [nio-9999-exec-7] o.s.s.o.p.token.store.JdbcTokenStore : Failed to find access token for token 41b1504d-b985-40e0-80a8-94c09992aafe
2016-02-28 12:44:06.845 INFO 1029 --- [nio-9999-exec-6] o.s.s.o.p.token.store.JdbcTokenStore : Failed to find access token for token 41b1504d-b985-40e0-80a8-94c09992aafe
Бревна из ресурсов сервера
2016-02-28 12:37:42.149 INFO 1186 --- [0.1-8181-exec-3] o.s.b.a.s.o.r.UserInfoTokenServices : Getting user info from: http://localhost:9999/uaa/user
2016-02-28 12:37:42.228 INFO 1186 --- [0.1-8181-exec-3] o.s.b.a.s.o.r.UserInfoTokenServices : Could not fetch user details: class org.springframework.security.oauth2.client.resource.UserRedirectRequiredException, A redirect is required to get the users approval
2016-02-28 12:37:58.600 INFO 1186 --- [0.1-8181-exec-5] o.s.b.a.s.o.r.UserInfoTokenServices : Getting user info from: http://localhost:9999/uaa/user
2016-02-28 12:37:58.623 INFO 1186 --- [0.1-8181-exec-5] o.s.b.a.s.o.r.UserInfoTokenServices : Could not fetch user details: class java.lang.IllegalArgumentException, URI is not absolute
2016-02-28 12:44:06.839 INFO 1186 --- [0.1-8181-exec-7] o.s.b.a.s.o.r.UserInfoTokenServices : Getting user info from: http://localhost:9999/uaa/user
2016-02-28 12:44:06.848 INFO 1186 --- [0.1-8181-exec-7] o.s.b.a.s.o.r.UserInfoTokenServices : Could not fetch user details: class org.springframework.security.oauth2.common.exceptions.InvalidRequestException, Possible CSRF detected - state parameter was present but no state could be found
Вот важные классы:
OAuth2 Авторизация сервера: SaAuthApplication. класс
@SpringBootApplication
@Configuration
@RestController
@EnableDiscoveryClient
@EnableResourceServer
@EnableAutoConfiguration
@EnableAuthorizationServer
public class SaAuthApplication {
@Autowired
private DataSource dataSource;
@RequestMapping("/user")
public Principal user(Principal user) {
return user;
}
public static void main(String[] args) {
SpringApplication.run(SaAuthApplication.class, args);
}
@Configuration
@EnableResourceServer
protected static class ResourceServer extends ResourceServerConfigurerAdapter {
@Autowired
private TokenStore tokenStore;
@Override
public void configure(ResourceServerSecurityConfigurer resources)
throws Exception {
resources.tokenStore(tokenStore);
}
@Override
public void configure(HttpSecurity http) throws Exception {
http.authorizeRequests().anyRequest().authenticated();
}
}
@Configuration
@EnableAuthorizationServer
protected static class OAuth2Config extends AuthorizationServerConfigurerAdapter {
@Autowired
private AuthenticationManager auth;
@Autowired
private DataSource dataSource;
private BCryptPasswordEncoder passwordEncoder = new BCryptPasswordEncoder();
@Bean
public JdbcTokenStore tokenStore() {
return new JdbcTokenStore(dataSource);
}
@Bean
protected AuthorizationCodeServices authorizationCodeServices() {
return new JdbcAuthorizationCodeServices(dataSource);
}
@Override
public void configure(AuthorizationServerSecurityConfigurer security)
throws Exception {
security.passwordEncoder(passwordEncoder);
}
@Override
public void configure(AuthorizationServerEndpointsConfigurer endpoints)
throws Exception {
endpoints.authorizationCodeServices(authorizationCodeServices())
.authenticationManager(auth).tokenStore(tokenStore())
.approvalStoreDisabled();
}
@Override
public void configure(ClientDetailsServiceConfigurer clients) throws Exception {
// @formatter:off
clients.jdbc(dataSource)
.passwordEncoder(passwordEncoder)
.withClient("my-trusted-client")
.authorizedGrantTypes("password", "authorization_code",
"refresh_token", "implicit")
.authorities("ROLE_CLIENT", "ROLE_TRUSTED_CLIENT")
.scopes("read", "write", "trust")
.resourceIds("oauth2-resource")
.accessTokenValiditySeconds(60).and()
.withClient("my-client-with-registered-redirect")
.authorizedGrantTypes("authorization_code")
.authorities("ROLE_CLIENT").scopes("read", "trust")
.resourceIds("oauth2-resource")
.redirectUris("http://anywhere?key=value").and()
.withClient("my-client-with-secret")
.authorizedGrantTypes("client_credentials", "password")
.authorities("ROLE_CLIENT").scopes("read")
.resourceIds("oauth2-resource").secret("secret");
// @formatter:on
}
}
@Autowired
public void init(AuthenticationManagerBuilder auth) throws Exception {
// @formatter:off
auth.jdbcAuthentication().dataSource(dataSource).withUser("dave")
.password("secret").roles("USER");
// @formatter:on
}
}
ресурсов сервера: application.yml
security:
oauth2:
resource:
user-info-uri: http://localhost:9999/uaa/user
ресурсов сервера: SaEmployeeApplication.class
@SpringBootApplication
@EnableDiscoveryClient
@EnableResourceServer
public class SaEmployeeApplication {
public static void main(String[] args) {
SpringApplication.run(SaEmployeeApplication.class, args);
}
}
Все отлично работает на сервере OAuth2 авторизации. Я могу разрешать клиентам и возвращать токены. Но сервер , похоже, не может проверить токен на конечной точке /uaa/user
.
почему у вас есть два '@ EnableResourceServer' аннотацию? попробуйте удалить один из класса SaEmployeeApplication – MangEngkus
@MangEngkus, он не работает. Если я попытаюсь получить доступ к Серверу ресурсов после удаления '@ EnableResourceServer', я получаю следующий журнал (после получения нового токена, конечно):' {"timestamp": 1456737185144, "status": 401, "error": "Unauthorized »,« сообщение »:« Для доступа к этому ресурсу требуется полная аутентификация »,« путь »:«/api/сотрудники/сотрудники »} – Marcel