Я разработал клиент-серверное приложение с angular java и keycloak все хорошо работает с docker для keycloak ensiute Я поставил свой пользовательский интерфейс под docker все работает хорошо, последний шаг я но мой код java и там я всегда получаю 401 не понимаю. Я попытался вывести свой код и запустить его на linux, так как docker тоже не работает. но только в окне, а в остальных linux проблем нет. вот мой конфиг и код в java.
Это адаптер
@KeycloakConfiguration
@ConditionalOnProperty(name = "keycloak.enabled", havingValue = "true", matchIfMissing = true)
class SecurityConfig extends KeycloakWebSecurityConfigurerAdapter {
@Autowired
private Cors cors;
@Autowired
public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
KeycloakAuthenticationProvider keycloakAuthenticationProvider = keycloakAuthenticationProvider();
keycloakAuthenticationProvider.setGrantedAuthoritiesMapper(new SimpleAuthorityMapper());
auth.authenticationProvider(keycloakAuthenticationProvider);
}
@Bean
public CorsConfigurationSource corsConfigurationSource() {
UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
CorsConfiguration config = new CorsConfiguration();
for (String origin : cors.getAllowedOrigin()) {
config.addAllowedOrigin(origin);
}
for (String method : cors.getAllowedMethods()) {
config.addAllowedMethod(method);
}
for (String header : cors.getAllowedHeaders()) {
config.addAllowedHeader(header);
}
config.setAllowCredentials(true);
config.setMaxAge(cors.getMaxAge());
source.registerCorsConfiguration(cors.getMapping(), config);
return source;
}
@Bean
@Override
protected SessionAuthenticationStrategy sessionAuthenticationStrategy() {
//return new NullAuthenticatedSessionStrategy();
return new RegisterSessionAuthenticationStrategy(new SessionRegistryImpl());
}
@Override
protected void configure(HttpSecurity http) throws Exception {
super.configure(http);
http.cors().and().csrf().disable().sessionManagement()
// use previously declared bean
.sessionAuthenticationStrategy(sessionAuthenticationStrategy())
.sessionCreationPolicy(SessionCreationPolicy.STATELESS)
// keycloak filters for securisation
.and().addFilterBefore(keycloakPreAuthActionsFilter(), LogoutFilter.class)
.addFilterBefore(keycloakAuthenticationProcessingFilter(), X509AuthenticationFilter.class)
.exceptionHandling().authenticationEntryPoint(authenticationEntryPoint())
// delegate logout endpoint to spring security
.and().logout().addLogoutHandler(keycloakLogoutHandler()).logoutUrl("/logout").logoutSuccessHandler(
// logout handler for API
(HttpServletRequest request, HttpServletResponse response,
Authentication authentication) -> response.setStatus(HttpServletResponse.SC_OK))
.and()
// manage routes securisation here
.authorizeRequests().antMatchers(HttpMethod.OPTIONS).permitAll()
.antMatchers("/logout", "/", "/unsecured").permitAll().antMatchers("/poc").hasRole("poc")
.antMatchers("/admin").hasRole("admin").antMatchers("/all").hasRole("all").anyRequest().denyAll();
}
}
Resolver
public class CustomKeycloakSpringBootConfigResolver extends KeycloakSpringBootConfigResolver {
private final KeycloakDeployment keycloakDeployment;
public CustomKeycloakSpringBootConfigResolver(KeycloakSpringBootProperties properties) {
keycloakDeployment = KeycloakDeploymentBuilder.build(properties);
}
@Override
public KeycloakDeployment resolve(HttpFacade.Request facade) {
return keycloakDeployment;
}
}
это мой docker файл для создания
version: '3'
volumes:
postgres_data:
driver: local
services:
pack-solution-postgres-keycloak:
container_name: pack-solution-postgres-keycloak
image: postgres
volumes:
- postgres_data:/var/lib/postgresql/data
networks:
- pack-solution-network
environment:
- POSTGRES_PASSWORD=keycloak
- POSTGRES_DB=keycloak
- POSTGRES_USER=keycloak
pack-solution-keycloak:
container_name: pack-solution-keycloak
image: jboss/keycloak
depends_on:
- pack-solution-postgres-keycloak
volumes:
- ./Scripts/keycloak/Init-keycloak.json:/opt/jboss/keycloak/imports/Init-keycloak.json
- ./pack-theme:/opt/jboss/keycloak/themes/pack-theme
- ./fileconfig/standalone.xml:/opt/jboss/keycloak/standalone/configuration/standalone.xml
command:
- "-b 0.0.0.0 -Dkeycloak.import=/opt/jboss/keycloak/imports/Init-keycloak.json"
networks:
- pack-solution-network
environment:
- DB_VENDOR=POSTGRES
- DB_ADDR=pack-solution-postgres-keycloak
- DB_DATABASE=keycloak
- DB_USER=keycloak
- DB_PASSWORD=keycloak
- KEYCLOAK_USER=admin
- KEYCLOAK_PASSWORD=admin
- KEYCLAOK_HOSTNAME=pack-solution-keycloak
- PROXY_ADDRESS_FORWARDING=true
ports:
- 8080:8080
pack-solution-ui:
container_name: pack-solution-ui
build: ./ui/dev
networks:
- pack-solution-network
ports:
- 4200:80
pack-solution-api:
container_name: pack-solution-api
build: ./api/dev
links:
- pack-solution-keycloak
networks:
- pack-solution-network
ports:
- 8081:8080
networks:
pack-solution-network:
driver: bridge
my application.yml
########################################
# Spring Boot / Server configuration
########################################
server:
port: 8080
use-forward-headers: true
########################################
# Spring Boot / Keycloak Configuration
########################################
keycloak:
enabled: true
auth-server-url: http://pack-solution-keycloak:8080/auth
#auth-server-url: http://localhost:8080/auth
realm: Pack-Solutions
resource: PackApi
ssl-required: external
#bearer-only: false
#enable-basic-auth: false
#use-resource-role-mappings : true
verify-token-audience: true
credentials:
secret: 04ae23ef-a331-427b-8160-15edd68e78e9
cors: true
##################################################
#keycloak.securityConstraints[0].securityCollections[0].name: insecure endpoint
#keycloak.securityConstraints[0].securityCollections[0].patterns[0]: /unsecured
#keycloak.securityConstraints[0].securityCollections[0].patterns[1]: /
#keycloak.securityConstraints[1].authRoles[0]: poc
#keycloak.securityConstraints[1].securityCollections[0].patterns[0]: /*
######################################
# CORS
######################################
cross-origin-resource-sharing:
allowed-origin:
- http://pack-solution-ui:4200/*
- http://localhost:4200/*
- http://localhost:4200
- http://pack-solution-ui:4200
mapping: /**
allowed-methods:
- POST
- GET
- OPTIONS
- DELETE
- PUT
allowed-headers:
- WWW-Authenticate
- Authorization
- Content-Type
- xsrf-token
exposed-headers:
- WWW-Authenticate
- xsrf-token
max-age: 600
logging:
level:
org:
springframework:
security: DEBUG
web: DEBUG
Пожалуйста, если у вас есть вопрос или ответ?
Это работает на Windows 10, но не на linux .. .