Merge branch 'eugenp:master' into master

This commit is contained in:
@alonso_isidoro 2022-06-07 11:41:55 +02:00 committed by GitHub
commit 863a232823
21 changed files with 275 additions and 87 deletions

View File

@ -41,7 +41,7 @@ public class CustomPhysicalNamingStrategy implements PhysicalNamingStrategy {
final String newName = identifier.getText()
.replaceAll(regex, replacement)
.toLowerCase();
return Identifier.toIdentifier(newName);
return Identifier.toIdentifier(newName, identifier.isQuoted());
}
}

View File

@ -5,6 +5,7 @@ hibernate.dialect=org.hibernate.dialect.H2Dialect
hibernate.show_sql=false
hibernate.hbm2ddl.auto=create-drop
hibernate.globally_quoted_identifiers=true
hibernate.physical_naming_strategy=com.baeldung.hibernate.namingstrategy.CustomPhysicalNamingStrategy
hibernate.implicit_naming_strategy=org.hibernate.boot.model.naming.ImplicitNamingStrategyJpaCompliantImpl

View File

@ -0,0 +1,13 @@
package com.baeldung.disablingkeycloak;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication(scanBasePackages = { "com.baeldung.disablingkeycloak" })
public class App {
public static void main(String[] args) {
SpringApplication.run(App.class, args);
}
}

View File

@ -0,0 +1,20 @@
package com.baeldung.disablingkeycloak;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
@Configuration
@ConditionalOnProperty(name = "keycloak.enabled", havingValue = "false")
public class DisableSecurityConfiguration extends WebSecurityConfigurerAdapter {
@Override
protected void configure(final HttpSecurity http) throws Exception {
http.csrf()
.disable()
.authorizeRequests()
.anyRequest()
.permitAll();
}
}

View File

@ -0,0 +1,14 @@
package com.baeldung.disablingkeycloak;
import org.keycloak.adapters.springboot.KeycloakSpringBootConfigResolver;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
@Configuration
public class KeycloakConfiguration {
@Bean
public KeycloakSpringBootConfigResolver keycloakConfigResolver() {
return new KeycloakSpringBootConfigResolver();
}
}

View File

@ -0,0 +1,38 @@
package com.baeldung.disablingkeycloak;
import org.keycloak.adapters.springsecurity.KeycloakConfiguration;
import org.keycloak.adapters.springsecurity.config.KeycloakWebSecurityConfigurerAdapter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.context.annotation.Bean;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.web.authentication.session.NullAuthenticatedSessionStrategy;
import org.springframework.security.web.authentication.session.SessionAuthenticationStrategy;
@KeycloakConfiguration
@ConditionalOnProperty(name = "keycloak.enabled", havingValue = "true", matchIfMissing = true)
public class KeycloakSecurityConfig extends KeycloakWebSecurityConfigurerAdapter {
@Autowired
public void configureGlobal(AuthenticationManagerBuilder auth) {
auth.authenticationProvider(keycloakAuthenticationProvider());
}
@Bean
@Override
protected SessionAuthenticationStrategy sessionAuthenticationStrategy() {
return new NullAuthenticatedSessionStrategy();
}
@Override
protected void configure(HttpSecurity http) throws Exception {
super.configure(http);
http.csrf()
.disable()
.authorizeRequests()
.anyRequest()
.authenticated();
}
}

View File

@ -0,0 +1,40 @@
package com.baeldung.disablingkeycloak;
public class User {
private Long id;
private String firstname;
private String lastname;
public User() {
}
public User(Long id, String firstname, String lastname) {
this.id = id;
this.firstname = firstname;
this.lastname = lastname;
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getFirstname() {
return firstname;
}
public void setFirstname(String firstname) {
this.firstname = firstname;
}
public String getLastname() {
return lastname;
}
public void setLastname(String lastname) {
this.lastname = lastname;
}
}

View File

@ -0,0 +1,17 @@
package com.baeldung.disablingkeycloak;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
@RequestMapping("/users")
public class UserController {
@GetMapping("/{userId}")
public User getCustomer(@PathVariable Long userId) {
return new User(userId, "John", "Doe");
}
}

View File

@ -0,0 +1,7 @@
# Keycloak authentication is enabled for production.
keycloak.enabled=true
keycloak.realm=SpringBootKeycloak
keycloak.auth-server-url=http://localhost:8180/auth
keycloak.resource=login-app
keycloak.bearer-only=true
keycloak.ssl-required=external

View File

@ -0,0 +1,33 @@
package com.baeldung.disablingkeycloak;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import org.apache.http.HttpStatus;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.boot.test.web.client.TestRestTemplate;
import org.springframework.http.ResponseEntity;
import org.springframework.test.context.ActiveProfiles;
import org.springframework.test.context.junit4.SpringRunner;
@SpringBootTest(classes = App.class, webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
@RunWith(SpringRunner.class)
@ActiveProfiles("disablingkeycloak")
public class DisablingKeycloakIntegrationTest {
@Autowired
private TestRestTemplate restTemplate;
@Test
public void givenUnauthenticated_whenGettingUser_shouldReturnUser() {
ResponseEntity<User> responseEntity = restTemplate.getForEntity("/users/1", User.class);
assertEquals(HttpStatus.SC_OK, responseEntity.getStatusCodeValue());
assertNotNull(responseEntity.getBody()
.getFirstname());
}
}

View File

@ -1,7 +1,5 @@
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<artifactId>spring-boot-springdoc</artifactId>
<version>0.0.1-SNAPSHOT</version>
@ -112,6 +110,8 @@
<include>application.properties</include>
<include>data.sql</include>
<include>schema.sql</include>
<include>app.key</include>
<include>app.pub</include>
</includes>
</resource>
</resources>

View File

@ -52,8 +52,9 @@ public class SecurityConfiguration {
//@formatter:off
return http
.authorizeHttpRequests(authorizeRequests -> authorizeRequests
.antMatchers("/api/auth/**", "/swagger-ui.html", "/swagger-ui/**", "/v3/api-docs/**", "/webjars/**",
"/swagger-ui/index.html")
.antMatchers("/api/auth/**", "/swagger-ui-custom.html" ,"/swagger-ui.html", "/swagger-ui/**", "/v3/api-docs/**", "/webjars/**",
"/swagger-ui/index.html","/api-docs/**")
.permitAll()
.anyRequest()
.authenticated())

View File

@ -11,7 +11,6 @@ public class SecurityTokenApplication {
* @param args
*/
public static void main(String[] args) {
SpringApplication.run(SecurityTokenApplication.class, args);
SpringApplication.run(SecurityTokenApplication.class);
}
}

View File

@ -30,7 +30,7 @@ class OpenApiJwtIntegrationTest
{
assertNotNull(authenticationApi);
String response = this.restTemplate.getForObject("http://localhost:" + port + "/swagger-ui.html", String.class);
String response = this.restTemplate.getForObject("http://localhost:" + port + "/swagger-ui/index.html", String.class);
assertNotNull(response);
assertTrue(response.contains("Swagger UI"));
@ -43,8 +43,7 @@ class OpenApiJwtIntegrationTest
{
assertNotNull(authenticationApi);
ResponseEntity<String> response = this.restTemplate.getForEntity("http://localhost:" + port + "/v3/api-docs",
String.class);
ResponseEntity<String> response = this.restTemplate.getForEntity("http://localhost:" + port + "/api-docs", String.class);
assertNotNull(response);
assertEquals(HttpStatus.OK, response.getStatusCode());
@ -59,8 +58,8 @@ class OpenApiJwtIntegrationTest
{
assertNotNull(authenticationApi);
ResponseEntity<String> response = this.restTemplate.getForEntity("http://localhost:" + port + "/v3/api-docs",
String.class);
ResponseEntity<String> response = this.restTemplate.getForEntity("http://localhost:" + port + "/api-docs", String.class);
assertNotNull(response);
assertNotNull(response.getBody());
@ -75,8 +74,7 @@ class OpenApiJwtIntegrationTest
{
assertNotNull(authenticationApi);
ResponseEntity<String> response = this.restTemplate.getForEntity("http://localhost:" + port + "/v3/api-docs",
String.class);
ResponseEntity<String> response = this.restTemplate.getForEntity("http://localhost:" + port + "/api-docs", String.class);
assertNotNull(response);
assertNotNull(response.getBody());

View File

@ -1,37 +0,0 @@
package com.baeldung.reactive.security;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import reactor.core.publisher.Mono;
import java.security.Principal;
@RestController
public class GreetController {
private GreetService greetService;
public GreetController(GreetService greetService) {
this.greetService = greetService;
}
@GetMapping("/")
public Mono<String> greet(Mono<Principal> principal) {
return principal
.map(Principal::getName)
.map(name -> String.format("Hello, %s", name));
}
@GetMapping("/admin")
public Mono<String> greetAdmin(Mono<Principal> principal) {
return principal
.map(Principal::getName)
.map(name -> String.format("Admin access: %s", name));
}
@GetMapping("/greetService")
public Mono<String> greetService() {
return greetService.greet();
}
}

View File

@ -0,0 +1,37 @@
package com.baeldung.reactive.security;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import reactor.core.publisher.Mono;
import java.security.Principal;
@RestController
public class GreetingController {
private final GreetingService greetingService;
public GreetingController(GreetingService greetingService) {
this.greetingService = greetingService;
}
@GetMapping("/")
public Mono<String> greet(Mono<Principal> principal) {
return principal
.map(Principal::getName)
.map(name -> String.format("Hello, %s", name));
}
@GetMapping("/admin")
public Mono<String> greetAdmin(Mono<Principal> principal) {
return principal
.map(Principal::getName)
.map(name -> String.format("Admin access: %s", name));
}
@GetMapping("/greetingService")
public Mono<String> greetingService() {
return greetingService.greet();
}
}

View File

@ -5,7 +5,7 @@ import org.springframework.stereotype.Service;
import reactor.core.publisher.Mono;
@Service
public class GreetService {
public class GreetingService {
@PreAuthorize("hasRole('ADMIN')")
public Mono<String> greet() {

View File

@ -16,40 +16,37 @@ import org.springframework.security.web.server.SecurityWebFilterChain;
public class SecurityConfig {
@Bean
public SecurityWebFilterChain securitygWebFilterChain(ServerHttpSecurity http) {
public SecurityWebFilterChain securityWebFilterChain(ServerHttpSecurity http) {
return http.authorizeExchange()
.pathMatchers("/admin")
.hasAuthority("ROLE_ADMIN")
.anyExchange()
.authenticated()
.and()
.formLogin()
.and()
.csrf()
.disable()
.build();
.pathMatchers("/admin").hasAuthority("ROLE_ADMIN")
.anyExchange().authenticated()
.and()
.formLogin()
.and()
.csrf().disable()
.build();
}
@Bean
public MapReactiveUserDetailsService userDetailsService() {
UserDetails user = User
.withUsername("user")
.password(passwordEncoder().encode("password"))
.roles("USER")
.build();
.withUsername("user")
.password(passwordEncoder().encode("password"))
.roles("USER")
.build();
UserDetails admin = User
.withUsername("admin")
.password(passwordEncoder().encode("password"))
.roles("ADMIN")
.build();
.withUsername("admin")
.password(passwordEncoder().encode("password"))
.roles("ADMIN")
.build();
return new MapReactiveUserDetailsService(user, admin);
}
@Bean
public PasswordEncoder passwordEncoder() {
return new BCryptPasswordEncoder();
return new BCryptPasswordEncoder();
}
}

View File

@ -15,23 +15,32 @@ import org.springframework.test.web.reactive.server.WebTestClient;
public class SecurityIntegrationTest {
@Autowired
ApplicationContext context;
private ApplicationContext context;
private WebTestClient rest;
private WebTestClient webTestClient;
@BeforeEach
public void setup() {
this.rest = WebTestClient.bindToApplicationContext(this.context).configureClient().build();
webTestClient = WebTestClient.bindToApplicationContext(context)
.configureClient()
.build();
}
@Test
public void whenNoCredentials_thenRedirectToLogin() {
this.rest.get().uri("/").exchange().expectStatus().is3xxRedirection();
webTestClient.get()
.uri("/")
.exchange()
.expectStatus().is3xxRedirection();
}
@Test
@WithMockUser
public void whenHasCredentials_thenSeesGreeting() {
this.rest.get().uri("/").exchange().expectStatus().isOk().expectBody(String.class).isEqualTo("Hello, user");
webTestClient.get()
.uri("/")
.exchange()
.expectStatus().isOk()
.expectBody(String.class).isEqualTo("Hello, user");
}
}

View File

@ -50,8 +50,8 @@ class MongoAuthApplicationIntegrationTest {
setUp();
mvc = MockMvcBuilders.webAppContextSetup(context)
.apply(springSecurity())
.build();
.apply(springSecurity())
.build();
}
private void setUp() {
@ -85,34 +85,34 @@ class MongoAuthApplicationIntegrationTest {
@Test
void givenUserCredentials_whenInvokeUserAuthorizedEndPoint_thenReturn200() throws Exception {
mvc.perform(get("/user").with(httpBasic(USER_NAME, PASSWORD)))
.andExpect(status().isOk());
.andExpect(status().isOk());
}
@Test
void givenUserNotExists_whenInvokeEndPoint_thenReturn401() throws Exception {
mvc.perform(get("/user").with(httpBasic("not_existing_user", "password")))
.andExpect(status().isUnauthorized());
.andExpect(status().isUnauthorized());
}
@Test
void givenUserExistsAndWrongPassword_whenInvokeEndPoint_thenReturn401() throws Exception {
mvc.perform(get("/user").with(httpBasic(USER_NAME, "wrong_password")))
.andExpect(status().isUnauthorized());
.andExpect(status().isUnauthorized());
}
@Test
void givenUserCredentials_whenInvokeAdminAuthorizedEndPoint_thenReturn403() throws Exception {
mvc.perform(get("/admin").with(httpBasic(USER_NAME, PASSWORD)))
.andExpect(status().isForbidden());
.andExpect(status().isForbidden());
}
@Test
void givenAdminCredentials_whenInvokeAdminAuthorizedEndPoint_thenReturn200() throws Exception {
mvc.perform(get("/admin").with(httpBasic(ADMIN_NAME, PASSWORD)))
.andExpect(status().isOk());
.andExpect(status().isOk());
mvc.perform(get("/user").with(httpBasic(ADMIN_NAME, PASSWORD)))
.andExpect(status().isOk());
.andExpect(status().isOk());
}
}