From 282cd67ad4fa8b6744e862528ecb638250fe2afd Mon Sep 17 00:00:00 2001 From: Abhinav Pandey Date: Sat, 2 Jul 2022 16:56:07 +0530 Subject: [PATCH 01/16] BAEL-3201 - Unit testing with Redis test containers --- .../spring-boot-testing-2/pom.xml | 10 +++ .../RedisTestcontainersApplication.java | 13 ++++ .../redistestcontainers/hash/Product.java | 55 ++++++++++++++ .../repository/ProductRepository.java | 9 +++ .../service/ProductService.java | 31 ++++++++ .../ProductServiceIntegrationTest.java | 75 +++++++++++++++++++ 6 files changed, 193 insertions(+) create mode 100644 spring-boot-modules/spring-boot-testing-2/src/main/java/com/baeldung/redistestcontainers/RedisTestcontainersApplication.java create mode 100644 spring-boot-modules/spring-boot-testing-2/src/main/java/com/baeldung/redistestcontainers/hash/Product.java create mode 100644 spring-boot-modules/spring-boot-testing-2/src/main/java/com/baeldung/redistestcontainers/repository/ProductRepository.java create mode 100644 spring-boot-modules/spring-boot-testing-2/src/main/java/com/baeldung/redistestcontainers/service/ProductService.java create mode 100644 spring-boot-modules/spring-boot-testing-2/src/test/java/com/baeldung/redistestcontainers/service/ProductServiceIntegrationTest.java diff --git a/spring-boot-modules/spring-boot-testing-2/pom.xml b/spring-boot-modules/spring-boot-testing-2/pom.xml index 556142b480..e4f3f122af 100644 --- a/spring-boot-modules/spring-boot-testing-2/pom.xml +++ b/spring-boot-modules/spring-boot-testing-2/pom.xml @@ -23,6 +23,10 @@ org.springframework.boot spring-boot-starter-web-services + + org.springframework.boot + spring-boot-starter-data-redis + wsdl4j wsdl4j @@ -38,6 +42,12 @@ 3.1.3 test + + org.testcontainers + testcontainers + 1.17.2 + test + diff --git a/spring-boot-modules/spring-boot-testing-2/src/main/java/com/baeldung/redistestcontainers/RedisTestcontainersApplication.java b/spring-boot-modules/spring-boot-testing-2/src/main/java/com/baeldung/redistestcontainers/RedisTestcontainersApplication.java new file mode 100644 index 0000000000..50efd56751 --- /dev/null +++ b/spring-boot-modules/spring-boot-testing-2/src/main/java/com/baeldung/redistestcontainers/RedisTestcontainersApplication.java @@ -0,0 +1,13 @@ +package com.baeldung.redistestcontainers; + +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; + +@SpringBootApplication +public class RedisTestcontainersApplication { + + public static void main(String[] args) { + SpringApplication.run(RedisTestcontainersApplication.class, args); + } + +} diff --git a/spring-boot-modules/spring-boot-testing-2/src/main/java/com/baeldung/redistestcontainers/hash/Product.java b/spring-boot-modules/spring-boot-testing-2/src/main/java/com/baeldung/redistestcontainers/hash/Product.java new file mode 100644 index 0000000000..3345a17c79 --- /dev/null +++ b/spring-boot-modules/spring-boot-testing-2/src/main/java/com/baeldung/redistestcontainers/hash/Product.java @@ -0,0 +1,55 @@ +package com.baeldung.redistestcontainers.hash; + +import org.springframework.data.redis.core.RedisHash; + +import java.io.Serializable; + +@RedisHash("product") +public class Product implements Serializable { + private String id; + private String name; + private double price; + + // Constructor, getters and setters + public Product() { + } + + public Product(String id, String name, double price) { + this.id = id; + this.name = name; + this.price = price; + } + + public String getId() { + return id; + } + + public void setId(String id) { + this.id = id; + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + public double getPrice() { + return price; + } + + public void setPrice(double price) { + this.price = price; + } + + @Override + public String toString() { + return "Product{" + + "id='" + id + '\'' + + ", name='" + name + '\'' + + ", price=" + price + + '}'; + } +} \ No newline at end of file diff --git a/spring-boot-modules/spring-boot-testing-2/src/main/java/com/baeldung/redistestcontainers/repository/ProductRepository.java b/spring-boot-modules/spring-boot-testing-2/src/main/java/com/baeldung/redistestcontainers/repository/ProductRepository.java new file mode 100644 index 0000000000..5851c282e0 --- /dev/null +++ b/spring-boot-modules/spring-boot-testing-2/src/main/java/com/baeldung/redistestcontainers/repository/ProductRepository.java @@ -0,0 +1,9 @@ +package com.baeldung.redistestcontainers.repository; + +import com.baeldung.redistestcontainers.hash.Product; +import org.springframework.data.repository.CrudRepository; +import org.springframework.stereotype.Repository; + +@Repository +public interface ProductRepository extends CrudRepository { +} diff --git a/spring-boot-modules/spring-boot-testing-2/src/main/java/com/baeldung/redistestcontainers/service/ProductService.java b/spring-boot-modules/spring-boot-testing-2/src/main/java/com/baeldung/redistestcontainers/service/ProductService.java new file mode 100644 index 0000000000..3eb0149ef1 --- /dev/null +++ b/spring-boot-modules/spring-boot-testing-2/src/main/java/com/baeldung/redistestcontainers/service/ProductService.java @@ -0,0 +1,31 @@ +package com.baeldung.redistestcontainers.service; + +import com.baeldung.redistestcontainers.hash.Product; +import com.baeldung.redistestcontainers.repository.ProductRepository; +import org.springframework.stereotype.Service; + +@Service +public class ProductService { + + private final ProductRepository productRepository; + + public ProductService(ProductRepository productRepository) { + this.productRepository = productRepository; + } + + public Product getProduct(String id) { + return productRepository.findById(id).orElse(null); + } + + void createProduct(Product product) { + productRepository.save(product); + } + + void updateProduct(Product product) { + productRepository.save(product); + } + + void deleteProduct(String id) { + productRepository.deleteById(id); + } +} \ No newline at end of file diff --git a/spring-boot-modules/spring-boot-testing-2/src/test/java/com/baeldung/redistestcontainers/service/ProductServiceIntegrationTest.java b/spring-boot-modules/spring-boot-testing-2/src/test/java/com/baeldung/redistestcontainers/service/ProductServiceIntegrationTest.java new file mode 100644 index 0000000000..55ff2b8676 --- /dev/null +++ b/spring-boot-modules/spring-boot-testing-2/src/test/java/com/baeldung/redistestcontainers/service/ProductServiceIntegrationTest.java @@ -0,0 +1,75 @@ +package com.baeldung.redistestcontainers.service; + +import com.baeldung.redistestcontainers.hash.Product; +import org.junit.jupiter.api.Test; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.test.context.SpringBootTest; +import org.testcontainers.containers.GenericContainer; +import org.testcontainers.utility.DockerImageName; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNull; + +@SpringBootTest +public class ProductServiceIntegrationTest { + + static { + GenericContainer redis = new GenericContainer<>(DockerImageName.parse("redis:5.0.3-alpine")) + .withExposedPorts(6379); + redis.start(); + System.setProperty("spring.redis.host", redis.getHost()); + System.setProperty("spring.redis.port", redis.getMappedPort(6379).toString()); + } + + @Autowired + private ProductService productService; + + @Test + void testCreateProduct() { + Product product = new Product("1", "Test Product", 10.0); + productService.createProduct(product); + Product productFromDb = productService.getProduct("1"); + assertEquals("1", productFromDb.getId()); + assertEquals("Test Product", productFromDb.getName()); + assertEquals(10.0, productFromDb.getPrice()); + } + + @Test + void testUpdateProduct() { + Product product = new Product("1", "Test Product", 10.0); + productService.createProduct(product); + Product productFromDb = productService.getProduct("1"); + assertEquals("1", productFromDb.getId()); + assertEquals("Test Product", productFromDb.getName()); + assertEquals(10.0, productFromDb.getPrice()); + productFromDb.setName("Updated Product"); + productFromDb.setPrice(20.0); + productService.updateProduct(productFromDb); + Product updatedProductFromDb = productService.getProduct("1"); + assertEquals("Updated Product", updatedProductFromDb.getName()); + assertEquals(20.0, updatedProductFromDb.getPrice()); + } + + @Test + void testDeleteProduct() { + Product product = new Product("1", "Test Product", 10.0); + productService.createProduct(product); + Product productFromDb = productService.getProduct("1"); + assertEquals("1", productFromDb.getId()); + assertEquals("Test Product", productFromDb.getName()); + assertEquals(10.0, productFromDb.getPrice()); + productService.deleteProduct("1"); + Product deletedProductFromDb = productService.getProduct("1"); + assertNull(deletedProductFromDb); + } + + @Test + void testGetProduct() { + Product product = new Product("1", "Test Product", 10.0); + productService.createProduct(product); + Product productFromDb = productService.getProduct("1"); + assertEquals("1", productFromDb.getId()); + assertEquals("Test Product", productFromDb.getName()); + assertEquals(10.0, productFromDb.getPrice()); + } +} \ No newline at end of file From bc4857f6be7142ca7855efce6bbc77700fe4ecf0 Mon Sep 17 00:00:00 2001 From: Abhinav Pandey Date: Sun, 10 Jul 2022 19:14:31 +0530 Subject: [PATCH 02/16] BAEL-3201 - Updated test method names --- .../service/ProductServiceIntegrationTest.java | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/spring-boot-modules/spring-boot-testing-2/src/test/java/com/baeldung/redistestcontainers/service/ProductServiceIntegrationTest.java b/spring-boot-modules/spring-boot-testing-2/src/test/java/com/baeldung/redistestcontainers/service/ProductServiceIntegrationTest.java index 55ff2b8676..519db1b335 100644 --- a/spring-boot-modules/spring-boot-testing-2/src/test/java/com/baeldung/redistestcontainers/service/ProductServiceIntegrationTest.java +++ b/spring-boot-modules/spring-boot-testing-2/src/test/java/com/baeldung/redistestcontainers/service/ProductServiceIntegrationTest.java @@ -15,7 +15,7 @@ public class ProductServiceIntegrationTest { static { GenericContainer redis = new GenericContainer<>(DockerImageName.parse("redis:5.0.3-alpine")) - .withExposedPorts(6379); + .withExposedPorts(6379); redis.start(); System.setProperty("spring.redis.host", redis.getHost()); System.setProperty("spring.redis.port", redis.getMappedPort(6379).toString()); @@ -25,7 +25,7 @@ public class ProductServiceIntegrationTest { private ProductService productService; @Test - void testCreateProduct() { + void givenProductCreated_whenGettingProductById_thenProductExistsAndHasSameProperties() { Product product = new Product("1", "Test Product", 10.0); productService.createProduct(product); Product productFromDb = productService.getProduct("1"); @@ -35,7 +35,7 @@ public class ProductServiceIntegrationTest { } @Test - void testUpdateProduct() { + void givenProductCreatedAndUpdated_whenGettingTheProduct_thenUpdatedProductReturned() { Product product = new Product("1", "Test Product", 10.0); productService.createProduct(product); Product productFromDb = productService.getProduct("1"); @@ -51,7 +51,7 @@ public class ProductServiceIntegrationTest { } @Test - void testDeleteProduct() { + void givenProductCreatedAndDeleted_whenGettingTheProduct_thenNoProductReturned() { Product product = new Product("1", "Test Product", 10.0); productService.createProduct(product); Product productFromDb = productService.getProduct("1"); @@ -64,7 +64,7 @@ public class ProductServiceIntegrationTest { } @Test - void testGetProduct() { + void givenProductCreated_whenGettingProductById_thenSameProductReturned() { Product product = new Product("1", "Test Product", 10.0); productService.createProduct(product); Product productFromDb = productService.getProduct("1"); From 145b782d4b248cd9a3c271d09da2da8031e8e4ad Mon Sep 17 00:00:00 2001 From: "thibault.faure" Date: Sun, 10 Jul 2022 22:54:49 +0200 Subject: [PATCH 03/16] BAEL-5671 code for the validate an XML file against an XSD file article --- xml-2/pom.xml | 6 ++ .../xml/validation/XmlErrorHandler.java | 35 +++++++++++ .../baeldung/xml/validation/XmlValidator.java | 62 +++++++++++++++++++ .../resources/xml/validation/baeldung.xml | 8 +++ .../resources/xml/validation/full-person.xsd | 25 ++++++++ .../main/resources/xml/validation/person.xsd | 18 ++++++ .../xml/validation/XmlValidatorUnitTest.java | 35 +++++++++++ 7 files changed, 189 insertions(+) create mode 100644 xml-2/src/main/java/com/baeldung/xml/validation/XmlErrorHandler.java create mode 100644 xml-2/src/main/java/com/baeldung/xml/validation/XmlValidator.java create mode 100644 xml-2/src/main/resources/xml/validation/baeldung.xml create mode 100644 xml-2/src/main/resources/xml/validation/full-person.xsd create mode 100644 xml-2/src/main/resources/xml/validation/person.xsd create mode 100644 xml-2/src/test/java/com/baeldung/xml/validation/XmlValidatorUnitTest.java diff --git a/xml-2/pom.xml b/xml-2/pom.xml index 025ad682ad..c4882b0a53 100644 --- a/xml-2/pom.xml +++ b/xml-2/pom.xml @@ -20,6 +20,12 @@ dom4j ${dom4j.version} + + org.junit.jupiter + junit-jupiter-api + ${junit-jupiter.version} + test + diff --git a/xml-2/src/main/java/com/baeldung/xml/validation/XmlErrorHandler.java b/xml-2/src/main/java/com/baeldung/xml/validation/XmlErrorHandler.java new file mode 100644 index 0000000000..2a4651a029 --- /dev/null +++ b/xml-2/src/main/java/com/baeldung/xml/validation/XmlErrorHandler.java @@ -0,0 +1,35 @@ +package com.baeldung.xml.validation; + +import org.xml.sax.ErrorHandler; +import org.xml.sax.SAXParseException; + +import java.util.ArrayList; +import java.util.List; + +public class XmlErrorHandler implements ErrorHandler { + + private List exceptions; + + public XmlErrorHandler() { + this.exceptions = new ArrayList<>(); + } + + public List getExceptions() { + return exceptions; + } + + @Override + public void warning(SAXParseException exception) { + exceptions.add(exception); + } + + @Override + public void error(SAXParseException exception) { + exceptions.add(exception); + } + + @Override + public void fatalError(SAXParseException exception) { + exceptions.add(exception); + } +} diff --git a/xml-2/src/main/java/com/baeldung/xml/validation/XmlValidator.java b/xml-2/src/main/java/com/baeldung/xml/validation/XmlValidator.java new file mode 100644 index 0000000000..7d8f531bfa --- /dev/null +++ b/xml-2/src/main/java/com/baeldung/xml/validation/XmlValidator.java @@ -0,0 +1,62 @@ +package com.baeldung.xml.validation; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.xml.sax.SAXException; +import org.xml.sax.SAXParseException; + +import javax.xml.XMLConstants; +import javax.xml.transform.Source; +import javax.xml.transform.stream.StreamSource; +import javax.xml.validation.Schema; +import javax.xml.validation.SchemaFactory; +import javax.xml.validation.Validator; +import java.io.File; +import java.io.IOException; +import java.util.List; + +public class XmlValidator { + + private static final Logger LOGGER = LoggerFactory.getLogger(XmlValidator.class); + + private String xsdPath; + private String xmlPath; + + public XmlValidator(String xsdPath, String xmlPath) { + this.xsdPath = xsdPath; + this.xmlPath = xmlPath; + } + + public boolean isValid() throws IOException, SAXException { + Validator validator = initValidator(xsdPath); + try { + validator.validate(new StreamSource(getFile(xmlPath))); + return true; + } catch (SAXException e) { + return false; + } + } + + public List listParsingExceptions() throws IOException, SAXException { + XmlErrorHandler xsdErrorHandler = new XmlErrorHandler(); + Validator validator = initValidator(xsdPath); + validator.setErrorHandler(xsdErrorHandler); + try { + validator.validate(new StreamSource(getFile(xmlPath))); + } catch (SAXParseException e) {} + xsdErrorHandler.getExceptions().forEach(e -> LOGGER.info(e.getMessage())); + return xsdErrorHandler.getExceptions(); + } + + private Validator initValidator(String xsdPath) throws SAXException { + SchemaFactory factory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI); + Source schemaFile = new StreamSource(getFile(xsdPath)); + Schema schema = factory.newSchema(schemaFile); + return schema.newValidator(); + } + + private File getFile(String location) { + return new File(getClass().getClassLoader().getResource(location).getFile()); + } + +} diff --git a/xml-2/src/main/resources/xml/validation/baeldung.xml b/xml-2/src/main/resources/xml/validation/baeldung.xml new file mode 100644 index 0000000000..31ae4b4aa6 --- /dev/null +++ b/xml-2/src/main/resources/xml/validation/baeldung.xml @@ -0,0 +1,8 @@ + + + Baeldung +
+ 00001 + New York +
+
\ No newline at end of file diff --git a/xml-2/src/main/resources/xml/validation/full-person.xsd b/xml-2/src/main/resources/xml/validation/full-person.xsd new file mode 100644 index 0000000000..ea268c3a47 --- /dev/null +++ b/xml-2/src/main/resources/xml/validation/full-person.xsd @@ -0,0 +1,25 @@ + + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/xml-2/src/main/resources/xml/validation/person.xsd b/xml-2/src/main/resources/xml/validation/person.xsd new file mode 100644 index 0000000000..22c41b6a22 --- /dev/null +++ b/xml-2/src/main/resources/xml/validation/person.xsd @@ -0,0 +1,18 @@ + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/xml-2/src/test/java/com/baeldung/xml/validation/XmlValidatorUnitTest.java b/xml-2/src/test/java/com/baeldung/xml/validation/XmlValidatorUnitTest.java new file mode 100644 index 0000000000..2eb20a9bf2 --- /dev/null +++ b/xml-2/src/test/java/com/baeldung/xml/validation/XmlValidatorUnitTest.java @@ -0,0 +1,35 @@ +package com.baeldung.xml.validation; + +import org.junit.jupiter.api.Test; +import org.xml.sax.SAXException; +import java.io.IOException; + +import static org.junit.jupiter.api.Assertions.*; + +class XmlValidatorUnitTest { + + private static final String BAELDUNG_XML_PATH = "xml/validation/baeldung.xml"; + private static final String PERSON_XSD_PATH = "xml/validation/person.xsd"; + private static final String FULL_PERSON_XSD_PATH = "xml/validation/full-person.xsd"; + + @Test + public void givenValidXML_WhenIsValid_ThenTrue() throws IOException, SAXException { + assertTrue(new XmlValidator(PERSON_XSD_PATH, BAELDUNG_XML_PATH).isValid()); + } + + @Test + public void givenInvalidXML_WhenIsValid_ThenFalse() throws IOException, SAXException { + assertFalse(new XmlValidator(FULL_PERSON_XSD_PATH, BAELDUNG_XML_PATH).isValid()); + } + + @Test + public void givenValidXML_WhenListParsingExceptions_ThenNone() throws IOException, SAXException { + assertEquals(0, new XmlValidator(PERSON_XSD_PATH, BAELDUNG_XML_PATH).listParsingExceptions().size()); + } + + @Test + public void givenInvalidXML_WhenListParsingExceptions_ThenHasThree() throws IOException, SAXException { + assertEquals(3, new XmlValidator(FULL_PERSON_XSD_PATH, BAELDUNG_XML_PATH).listParsingExceptions().size()); + } + +} From 662f3c4f3e07183c2b9632b21cc9ceb4eac1bfb8 Mon Sep 17 00:00:00 2001 From: anuragkumawat Date: Sat, 16 Jul 2022 14:28:46 +0530 Subject: [PATCH 04/16] JAVA-13328 Update Convert Byte Size Into a Human-Readable Format in Java --- .../FileSizeFormatUtil.java | 108 ++++++++++++++---- .../FileSizeFormatUtilUnitTest.java | 46 +++++--- 2 files changed, 117 insertions(+), 37 deletions(-) diff --git a/core-java-modules/core-java-numbers-4/src/main/java/com/baeldung/humanreadablebytes/FileSizeFormatUtil.java b/core-java-modules/core-java-numbers-4/src/main/java/com/baeldung/humanreadablebytes/FileSizeFormatUtil.java index 941aa105aa..b4e262c95e 100644 --- a/core-java-modules/core-java-numbers-4/src/main/java/com/baeldung/humanreadablebytes/FileSizeFormatUtil.java +++ b/core-java-modules/core-java-numbers-4/src/main/java/com/baeldung/humanreadablebytes/FileSizeFormatUtil.java @@ -7,15 +7,35 @@ import java.util.List; public class FileSizeFormatUtil { private static final long BYTE = 1L; - private static final long KB = BYTE << 10; - private static final long MB = KB << 10; - private static final long GB = MB << 10; - private static final long TB = GB << 10; - private static final long PB = TB << 10; - private static final long EB = PB << 10; + private static final long KiB = BYTE << 10; + private static final long MiB = KiB << 10; + private static final long GiB = MiB << 10; + private static final long TiB = GiB << 10; + private static final long PiB = TiB << 10; + private static final long EiB = PiB << 10; + + private static final long KB = BYTE * 1000; + private static final long MB = KB * 1000; + private static final long GB = MB * 1000; + private static final long TB = GB * 1000; + private static final long PB = TB * 1000; + private static final long EB = PB * 1000; + private static final DecimalFormat DEC_FORMAT = new DecimalFormat("#.##"); - public static String toHumanReadable(long size) { + public static String toHumanReadableBinaryPrefixes(long size) { + if (size < 0) + throw new IllegalArgumentException("Invalid file size: " + size); + if (size >= EiB) return formatSize(size, EiB, "EiB"); + if (size >= PiB) return formatSize(size, PiB, "PiB"); + if (size >= TiB) return formatSize(size, TiB, "TiB"); + if (size >= GiB) return formatSize(size, GiB, "GiB"); + if (size >= MiB) return formatSize(size, MiB, "MiB"); + if (size >= KiB) return formatSize(size, KiB, "KiB"); + return formatSize(size, BYTE, "Bytes"); + } + + public static String toHumanReadableSIPrefixes(long size) { if (size < 0) throw new IllegalArgumentException("Invalid file size: " + size); if (size >= EB) return formatSize(size, EB, "EB"); @@ -26,23 +46,37 @@ public class FileSizeFormatUtil { if (size >= KB) return formatSize(size, KB, "KB"); return formatSize(size, BYTE, "Bytes"); } - + private static String formatSize(long size, long divider, String unitName) { return DEC_FORMAT.format((double) size / divider) + " " + unitName; } - public static String toHumanReadableWithEnum(long size) { - final List units = SizeUnit.unitsInDescending(); + public static String toHumanReadableBinaryPrefixesWithEnum(long size) { + final List units = SizeUnitBinaryPrefixes.unitsInDescending(); if (size < 0) throw new IllegalArgumentException("Invalid file size: " + size); String result = null; - for (SizeUnit unit : units) { + for (SizeUnitBinaryPrefixes unit : units) { if (size >= unit.getUnitBase()) { result = formatSize(size, unit.getUnitBase(), unit.name()); break; } } - return result == null ? formatSize(size, SizeUnit.Bytes.getUnitBase(), SizeUnit.Bytes.name()) : result; + return result == null ? formatSize(size, SizeUnitBinaryPrefixes.Bytes.getUnitBase(), SizeUnitBinaryPrefixes.Bytes.name()) : result; + } + + public static String toHumanReadableSIPrefixesWithEnum(long size) { + final List units = SizeUnitSIPrefixes.unitsInDescending(); + if (size < 0) + throw new IllegalArgumentException("Invalid file size: " + size); + String result = null; + for (SizeUnitSIPrefixes unit : units) { + if (size >= unit.getUnitBase()) { + result = formatSize(size, unit.getUnitBase(), unit.name()); + break; + } + } + return result == null ? formatSize(size, SizeUnitSIPrefixes.Bytes.getUnitBase(), SizeUnitSIPrefixes.Bytes.name()) : result; } public static String toHumanReadableByNumOfLeadingZeros(long size) { @@ -50,22 +84,22 @@ public class FileSizeFormatUtil { throw new IllegalArgumentException("Invalid file size: " + size); if (size < 1024) return size + " Bytes"; int unitIdx = (63 - Long.numberOfLeadingZeros(size)) / 10; - return formatSize(size, 1L << (unitIdx * 10), " KMGTPE".charAt(unitIdx) + "B"); + return formatSize(size, 1L << (unitIdx * 10), " KMGTPE".charAt(unitIdx) + "iB"); } - - enum SizeUnit { + + enum SizeUnitBinaryPrefixes { Bytes(1L), - KB(Bytes.unitBase << 10), - MB(KB.unitBase << 10), - GB(MB.unitBase << 10), - TB(GB.unitBase << 10), - PB(TB.unitBase << 10), - EB(PB.unitBase << 10); + KiB(Bytes.unitBase << 10), + MiB(KiB.unitBase << 10), + GiB(MiB.unitBase << 10), + TiB(GiB.unitBase << 10), + PiB(TiB.unitBase << 10), + EiB(PiB.unitBase << 10); private final Long unitBase; - public static List unitsInDescending() { - List list = Arrays.asList(values()); + public static List unitsInDescending() { + List list = Arrays.asList(values()); Collections.reverse(list); return list; } @@ -74,7 +108,33 @@ public class FileSizeFormatUtil { return unitBase; } - SizeUnit(long unitBase) { + SizeUnitBinaryPrefixes(long unitBase) { + this.unitBase = unitBase; + } + } + + enum SizeUnitSIPrefixes { + Bytes(1L), + KB(Bytes.unitBase * 1000), + MB(KB.unitBase * 1000), + GB(MB.unitBase * 1000), + TB(GB.unitBase * 1000), + PB(TB.unitBase * 1000), + EB(PB.unitBase * 1000); + + private final Long unitBase; + + public static List unitsInDescending() { + List list = Arrays.asList(values()); + Collections.reverse(list); + return list; + } + + public Long getUnitBase() { + return unitBase; + } + + SizeUnitSIPrefixes(long unitBase) { this.unitBase = unitBase; } } diff --git a/core-java-modules/core-java-numbers-4/src/test/java/com/baeldung/humanreadablebytes/FileSizeFormatUtilUnitTest.java b/core-java-modules/core-java-numbers-4/src/test/java/com/baeldung/humanreadablebytes/FileSizeFormatUtilUnitTest.java index 4326e92e2f..497fdc5792 100644 --- a/core-java-modules/core-java-numbers-4/src/test/java/com/baeldung/humanreadablebytes/FileSizeFormatUtilUnitTest.java +++ b/core-java-modules/core-java-numbers-4/src/test/java/com/baeldung/humanreadablebytes/FileSizeFormatUtilUnitTest.java @@ -8,33 +8,53 @@ import java.util.HashMap; import java.util.Map; public class FileSizeFormatUtilUnitTest { - private final static Map DATA_MAP = new HashMap() {{ + private final static Map DATA_MAP_BINARY_PREFIXES = new HashMap() {{ put(0L, "0 Bytes"); put(1023L, "1023 Bytes"); - put(1024L, "1 KB"); - put(12_345L, "12.06 KB"); - put(10_123_456L, "9.65 MB"); - put(10_123_456_798L, "9.43 GB"); - put(1_777_777_777_777_777_777L, "1.54 EB"); + put(1024L, "1 KiB"); + put(12_345L, "12.06 KiB"); + put(10_123_456L, "9.65 MiB"); + put(10_123_456_798L, "9.43 GiB"); + put(1_777_777_777_777_777_777L, "1.54 EiB"); }}; + private final static Map DATA_MAP_SI_PREFIXES = new HashMap() {{ + put(0L, "0 Bytes"); + put(999L, "999 Bytes"); + put(1000L, "1 KB"); + put(12_345L, "12.35 KB"); + put(10_123_456L, "10.12 MB"); + put(10_123_456_798L, "10.12 GB"); + put(1_777_777_777_777_777_777L, "1.78 EB"); + }}; + @Test - public void givenBytes_whenCalltoHumanReadableMethod_thenGetExpectedResults() { - DATA_MAP.forEach((in, expected) -> Assert.assertEquals(expected, FileSizeFormatUtil.toHumanReadable(in))); + public void givenBytes_whenCalltoHumanReadableBinaryPrefixesMethod_thenGetExpectedResults() { + DATA_MAP_BINARY_PREFIXES.forEach((in, expected) -> Assert.assertEquals(expected, FileSizeFormatUtil.toHumanReadableBinaryPrefixes(in))); + } + + @Test + public void givenBytes_whenCalltoHumanReadableSIPrefixesMethod_thenGetExpectedResults() { + DATA_MAP_SI_PREFIXES.forEach((in, expected) -> Assert.assertEquals(expected, FileSizeFormatUtil.toHumanReadableSIPrefixes(in))); } @Test - public void givenBytes_whenCalltoHumanReadableWithEnumMethod_thenGetExpectedResults() { - DATA_MAP.forEach((in, expected) -> Assert.assertEquals(expected, FileSizeFormatUtil.toHumanReadableWithEnum(in))); + public void givenBytes_whenCalltoHumanReadableBinaryPrefixesWithEnumMethod_thenGetExpectedResults() { + DATA_MAP_BINARY_PREFIXES.forEach((in, expected) -> Assert.assertEquals(expected, FileSizeFormatUtil.toHumanReadableBinaryPrefixesWithEnum(in))); } + @Test + public void givenBytes_whenCalltoHumanReadableSIPrefixesWithEnumMethod_thenGetExpectedResults() { + DATA_MAP_SI_PREFIXES.forEach((in, expected) -> Assert.assertEquals(expected, FileSizeFormatUtil.toHumanReadableSIPrefixesWithEnum(in))); + } + @Test public void givenBytes_whenCalltoHumanReadableByLeadingZeros_thenGetExpectedResults() { - DATA_MAP.forEach((in, expected) -> Assert.assertEquals(expected, FileSizeFormatUtil.toHumanReadableByNumOfLeadingZeros(in))); + DATA_MAP_BINARY_PREFIXES.forEach((in, expected) -> Assert.assertEquals(expected, FileSizeFormatUtil.toHumanReadableByNumOfLeadingZeros(in))); } - + @Test public void givenBytes_whenCalltoHumanReadableByFileUtils_thenOutputExpectedResults() { - DATA_MAP.forEach((in, expected) -> System.out.println(in + " bytes -> " + FileUtils.byteCountToDisplaySize(in))); + DATA_MAP_BINARY_PREFIXES.forEach((in, expected) -> System.out.println(in + " bytes -> " + FileUtils.byteCountToDisplaySize(in))); } } From 0518e6726b2817a5dc302e4ae545034e47919ea7 Mon Sep 17 00:00:00 2001 From: Abhinav Pandey Date: Sat, 16 Jul 2022 20:18:52 +0530 Subject: [PATCH 05/16] BAEL-3201 - Skipping test container based test --- ...ceIntegrationTest.java => ProductServiceManualTest.java} | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) rename spring-boot-modules/spring-boot-testing-2/src/test/java/com/baeldung/redistestcontainers/service/{ProductServiceIntegrationTest.java => ProductServiceManualTest.java} (95%) diff --git a/spring-boot-modules/spring-boot-testing-2/src/test/java/com/baeldung/redistestcontainers/service/ProductServiceIntegrationTest.java b/spring-boot-modules/spring-boot-testing-2/src/test/java/com/baeldung/redistestcontainers/service/ProductServiceManualTest.java similarity index 95% rename from spring-boot-modules/spring-boot-testing-2/src/test/java/com/baeldung/redistestcontainers/service/ProductServiceIntegrationTest.java rename to spring-boot-modules/spring-boot-testing-2/src/test/java/com/baeldung/redistestcontainers/service/ProductServiceManualTest.java index 519db1b335..00c0c3a1f7 100644 --- a/spring-boot-modules/spring-boot-testing-2/src/test/java/com/baeldung/redistestcontainers/service/ProductServiceIntegrationTest.java +++ b/spring-boot-modules/spring-boot-testing-2/src/test/java/com/baeldung/redistestcontainers/service/ProductServiceManualTest.java @@ -10,8 +10,12 @@ import org.testcontainers.utility.DockerImageName; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertNull; +/** + * Requires Docker running on the machine to run without errors + * Therefore, skipped from pipeline + */ @SpringBootTest -public class ProductServiceIntegrationTest { +public class ProductServiceManualTest { static { GenericContainer redis = new GenericContainer<>(DockerImageName.parse("redis:5.0.3-alpine")) From 09651da81e8bf50eca49cfd9a5056e408d19edc5 Mon Sep 17 00:00:00 2001 From: lucaCambi77 Date: Sat, 16 Jul 2022 17:37:07 +0200 Subject: [PATCH 06/16] [ BAEL-5503 ] - Difference Between links and depends_on in Docker-Compose (#12503) * updates pom-xml and adds Dockerfile to build a web-app image * add depends-on vs links yml examples --- docker-modules/docker-compose/Dockerfile | 4 +++ .../docker-compose-depends-on.yml | 14 ++++++++ .../docker-compose-links.yml | 14 ++++++++ .../docker-compose-network.yml | 36 +++++++++++++++++++ docker-modules/docker-compose/pom.xml | 10 ++++++ 5 files changed, 78 insertions(+) create mode 100644 docker-modules/docker-compose/Dockerfile create mode 100644 docker-modules/docker-compose/depends-on_vs_links/docker-compose-depends-on.yml create mode 100644 docker-modules/docker-compose/depends-on_vs_links/docker-compose-links.yml create mode 100644 docker-modules/docker-compose/depends-on_vs_links/docker-compose-network.yml diff --git a/docker-modules/docker-compose/Dockerfile b/docker-modules/docker-compose/Dockerfile new file mode 100644 index 0000000000..8d1bded77e --- /dev/null +++ b/docker-modules/docker-compose/Dockerfile @@ -0,0 +1,4 @@ +FROM openjdk:11 +MAINTAINER baeldung.com +COPY target/docker-compose-0.0.1-SNAPSHOT.jar app.jar +ENTRYPOINT ["java","-jar","/app.jar"] diff --git a/docker-modules/docker-compose/depends-on_vs_links/docker-compose-depends-on.yml b/docker-modules/docker-compose/depends-on_vs_links/docker-compose-depends-on.yml new file mode 100644 index 0000000000..1f9b42384e --- /dev/null +++ b/docker-modules/docker-compose/depends-on_vs_links/docker-compose-depends-on.yml @@ -0,0 +1,14 @@ +services: + db: + image: postgres:latest + environment: + - POSTGRES_USER=postgres + - POSTGRES_PASSWORD=postgres + ports: + - 5432:5432 + web-app: + image: web-app:latest + ports: + - 8080:8080 + depends_on: + - db \ No newline at end of file diff --git a/docker-modules/docker-compose/depends-on_vs_links/docker-compose-links.yml b/docker-modules/docker-compose/depends-on_vs_links/docker-compose-links.yml new file mode 100644 index 0000000000..cf84970b3c --- /dev/null +++ b/docker-modules/docker-compose/depends-on_vs_links/docker-compose-links.yml @@ -0,0 +1,14 @@ +services: + db: + image: postgres:latest + environment: + - POSTGRES_USER=postgres + - POSTGRES_PASSWORD=postgres + ports: + - 5432:5432 + web-app: + image: web-app:latest + ports: + - 8080:8080 + links: + - db \ No newline at end of file diff --git a/docker-modules/docker-compose/depends-on_vs_links/docker-compose-network.yml b/docker-modules/docker-compose/depends-on_vs_links/docker-compose-network.yml new file mode 100644 index 0000000000..6b6796b43d --- /dev/null +++ b/docker-modules/docker-compose/depends-on_vs_links/docker-compose-network.yml @@ -0,0 +1,36 @@ +services: + db: + image: postgres:latest + restart: always + environment: + - POSTGRES_USER=postgres + - POSTGRES_PASSWORD=postgres + ports: + - 5432:5432 + volumes: + - db:/var/lib/postgresql/data + networks: + - mynet + + web-app: + image: web-app:latest + depends_on: + - db + networks: + - mynet + ports: + - 8080:8080 + environment: + DB_HOST: db + DB_PORT: 5432 + DB_USER: postgres + DB_PASSWORD: postgres + DB_NAME: postgres + +networks: + mynet: + driver: bridge + +volumes: + db: + driver: local diff --git a/docker-modules/docker-compose/pom.xml b/docker-modules/docker-compose/pom.xml index 7215d6e159..39bad18d02 100644 --- a/docker-modules/docker-compose/pom.xml +++ b/docker-modules/docker-compose/pom.xml @@ -34,6 +34,16 @@ org.springframework.boot spring-boot-maven-plugin + + com.baeldung.docker.app.DockAppApplication + + + + + repackage + + +
From e65ce930bbe6f61c2b3279b958c31d8d42390dab Mon Sep 17 00:00:00 2001 From: Roger <587230+rojyates@users.noreply.github.com> Date: Sun, 17 Jul 2022 05:17:36 +1000 Subject: [PATCH 07/16] BAEL-5642 Using @NotNull as a method parameter (#12483) * BAEL-5642 Using @NotNull as a method parameter * BAEL-5642 Add Spring Boot and bump spring and hibernate-validator versions --- javaxval/pom.xml | 18 ++++++-- .../notnull/NotNullMethodParameter.java | 22 ++++++++++ .../javaxval/notnull/ValidatingComponent.java | 21 +++++++++ .../NotNullMethodParameterUnitTest.java | 21 +++++++++ .../ValidatingComponentIntegrationTest.java | 43 +++++++++++++++++++ 5 files changed, 122 insertions(+), 3 deletions(-) create mode 100644 javaxval/src/main/java/com/baeldung/javaxval/notnull/NotNullMethodParameter.java create mode 100644 javaxval/src/main/java/com/baeldung/javaxval/notnull/ValidatingComponent.java create mode 100644 javaxval/src/test/java/com/baeldung/javaxval/notnull/NotNullMethodParameterUnitTest.java create mode 100644 javaxval/src/test/java/com/baeldung/javaxval/notnull/ValidatingComponentIntegrationTest.java diff --git a/javaxval/pom.xml b/javaxval/pom.xml index e6ecee6cfb..a88bde35f8 100644 --- a/javaxval/pom.xml +++ b/javaxval/pom.xml @@ -34,8 +34,19 @@ spring-test ${org.springframework.version} + + org.springframework.boot + spring-boot-starter-validation + ${spring.boot.version} + + + org.springframework.boot + spring-boot-starter-test + ${spring.boot.version} + test + - + - 6.0.13.Final + 6.2.3.Final 6.2.0.Final 3.6.1 1.8 1.8 3.0.0 - 5.0.2.RELEASE + 5.3.21 + 2.7.1 \ No newline at end of file diff --git a/javaxval/src/main/java/com/baeldung/javaxval/notnull/NotNullMethodParameter.java b/javaxval/src/main/java/com/baeldung/javaxval/notnull/NotNullMethodParameter.java new file mode 100644 index 0000000000..47f0ee69fe --- /dev/null +++ b/javaxval/src/main/java/com/baeldung/javaxval/notnull/NotNullMethodParameter.java @@ -0,0 +1,22 @@ +package com.baeldung.javaxval.notnull; + +import javax.validation.Validation; +import javax.validation.Validator; +import javax.validation.ValidatorFactory; +import javax.validation.constraints.NotNull; + +public class NotNullMethodParameter { + + ValidatorFactory factory = Validation.buildDefaultValidatorFactory(); + Validator validator = factory.getValidator(); + + public int doesNotValidateNotNull(@NotNull String myString) { + return myString.length(); + } + + public int validateNotNull(@NotNull String myString) { + validator.validate(myString); + return myString.length(); + } + +} \ No newline at end of file diff --git a/javaxval/src/main/java/com/baeldung/javaxval/notnull/ValidatingComponent.java b/javaxval/src/main/java/com/baeldung/javaxval/notnull/ValidatingComponent.java new file mode 100644 index 0000000000..919001bd55 --- /dev/null +++ b/javaxval/src/main/java/com/baeldung/javaxval/notnull/ValidatingComponent.java @@ -0,0 +1,21 @@ +package com.baeldung.javaxval.notnull; + +import org.springframework.stereotype.Component; +import org.springframework.validation.annotation.Validated; + +import javax.validation.constraints.NotNull; + +@Component +@Validated +public class ValidatingComponent { + + public int validateNotNull(@NotNull String data) + { + return data.length(); + } + + public int callAnnotatedMethod(String data) { + return validateNotNull(data); + } + +} diff --git a/javaxval/src/test/java/com/baeldung/javaxval/notnull/NotNullMethodParameterUnitTest.java b/javaxval/src/test/java/com/baeldung/javaxval/notnull/NotNullMethodParameterUnitTest.java new file mode 100644 index 0000000000..bfc34331e5 --- /dev/null +++ b/javaxval/src/test/java/com/baeldung/javaxval/notnull/NotNullMethodParameterUnitTest.java @@ -0,0 +1,21 @@ +package com.baeldung.javaxval.notnull; + +import org.junit.jupiter.api.Test; + +import static org.junit.jupiter.api.Assertions.assertThrows; + +class NotNullMethodParameterUnitTest { + + private NotNullMethodParameter demo = new NotNullMethodParameter(); + + @Test + public void givenNull_whenInvokedwithNoValidator_thenNullPointerException() { + assertThrows(NullPointerException.class, () -> demo.doesNotValidateNotNull(null)); + } + + @Test + public void givenNull_whenInvokedWithValidator_thenIllegalArgumentException() { + assertThrows(IllegalArgumentException.class, () -> demo.validateNotNull(null)); + } + +} \ No newline at end of file diff --git a/javaxval/src/test/java/com/baeldung/javaxval/notnull/ValidatingComponentIntegrationTest.java b/javaxval/src/test/java/com/baeldung/javaxval/notnull/ValidatingComponentIntegrationTest.java new file mode 100644 index 0000000000..dbeba3e812 --- /dev/null +++ b/javaxval/src/test/java/com/baeldung/javaxval/notnull/ValidatingComponentIntegrationTest.java @@ -0,0 +1,43 @@ +package com.baeldung.javaxval.notnull; + +import org.junit.jupiter.api.Test; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.autoconfigure.SpringBootApplication; +import org.springframework.boot.test.context.SpringBootTest; + +import javax.validation.ConstraintViolation; +import javax.validation.ConstraintViolationException; +import javax.validation.constraints.NotNull; +import java.util.Set; + +import static org.hamcrest.MatcherAssert.assertThat; +import static org.hamcrest.Matchers.is; +import static org.junit.jupiter.api.Assertions.assertThrows; + +@SpringBootTest +class ValidatingComponentIntegrationTest { + + @Autowired ValidatingComponent component; + + @Test + void givenValue_whenValidate_thenSuccess() { + assertThat(component.validateNotNull("Not null!"), is(9)); + } + + @Test + void givenNull_whenValidate_thenConstraintViolationException() { + ConstraintViolationException constraintViolationException = assertThrows(ConstraintViolationException.class, () -> component.validateNotNull(null)); + Set> constraintViolations = constraintViolationException.getConstraintViolations(); + assertThat(constraintViolations.iterator().next().getConstraintDescriptor().getAnnotation().annotationType(), is(NotNull.class)); + } + + @Test + void givenNull_whenOnlyCalledMethodHasAnnotation_thenNoValidation() { + assertThrows(NullPointerException.class, () -> component.callAnnotatedMethod(null)); + } + + @SpringBootApplication + static class TestApplication { + } + +} \ No newline at end of file From 958bbb5cea6daf1b0368e74be144c042f37ff09d Mon Sep 17 00:00:00 2001 From: Haroon Khan Date: Sun, 17 Jul 2022 10:31:59 +0100 Subject: [PATCH 08/16] [JAVA-12608] Split test scenarios and add logging --- .../webclient/WebClientIntegrationTest.java | 47 +++++++++++++------ 1 file changed, 33 insertions(+), 14 deletions(-) diff --git a/spring-5-reactive-modules/spring-reactive/src/test/java/com/baeldung/reactive/webclient/WebClientIntegrationTest.java b/spring-5-reactive-modules/spring-reactive/src/test/java/com/baeldung/reactive/webclient/WebClientIntegrationTest.java index f52a20b149..5f42610c3d 100644 --- a/spring-5-reactive-modules/spring-reactive/src/test/java/com/baeldung/reactive/webclient/WebClientIntegrationTest.java +++ b/spring-5-reactive-modules/spring-reactive/src/test/java/com/baeldung/reactive/webclient/WebClientIntegrationTest.java @@ -82,6 +82,16 @@ class WebClientIntegrationTest { .verify(); } + @Test + void givenWebClientCreationWithoutUri_whenUsed_thenObtainExpectedResponse() { + WebClient client = WebClient.create(); + + StepVerifier.create(retrieveResponse(client)) + .expectErrorMatches(ex -> WebClientRequestException.class.isAssignableFrom(ex.getClass()) && ex.getMessage() + .contains("Connection refused")) + .verify(); + } + @Test void givenDifferentMethodSpecifications_whenUsed_thenObtainExpectedResponse() { // request specification @@ -111,12 +121,6 @@ class WebClientIntegrationTest { .build()); RequestBodySpec bodySpecusingURI = createDefaultPostRequest().uri( URI.create("http://localhost:" + port + "/resource")); - RequestBodySpec bodySpecOverridenBaseUri = createDefaultPostRequest().uri(URI.create("/resource")); - RequestBodySpec bodySpecOverridenBaseUri2 = WebClient.builder() - .baseUrl("http://localhost:" + port) - .build() - .post() - .uri(URI.create("/resource")); // response assertions StepVerifier.create(retrieveResponse(bodySpecUsingString)) @@ -128,12 +132,22 @@ class WebClientIntegrationTest { StepVerifier.create(retrieveResponse(bodySpecusingURI)) .expectNext("processed-bodyValue") .verifyComplete(); - // assert sending request overriding base URI - StepVerifier.create(retrieveResponse(bodySpecOverridenBaseUri)) + } + + @Test + void givenOverriddenUriSpecifications_whenUsed_thenObtainExpectedResponse() { + RequestBodySpec bodySpecOverriddenBaseUri = createDefaultPostRequest().uri(URI.create("/resource")); + StepVerifier.create(retrieveResponse(bodySpecOverriddenBaseUri)) .expectErrorMatches(ex -> WebClientRequestException.class.isAssignableFrom(ex.getClass()) && ex.getMessage() .contains("Connection refused")) .verify(); - StepVerifier.create(retrieveResponse(bodySpecOverridenBaseUri2)) + + RequestBodySpec bodySpecOverriddenBaseUri2 = WebClient.builder() + .baseUrl("http://localhost:" + port) + .build() + .post() + .uri(URI.create("/resource")); + StepVerifier.create(retrieveResponse(bodySpecOverriddenBaseUri2)) .expectErrorMatches(ex -> WebClientRequestException.class.isAssignableFrom(ex.getClass()) && ex.getMessage() .contains("Connection refused")) .verify(); @@ -301,30 +315,35 @@ class WebClientIntegrationTest { .uri("/resource") .bodyValue(BODY_VALUE) .retrieve() - .bodyToMono(String.class); + .bodyToMono(String.class) + .log(); } private Mono retrieveResponse(RequestBodyUriSpec spec) { return spec.uri("/resource") .bodyValue(BODY_VALUE) .retrieve() - .bodyToMono(String.class); + .bodyToMono(String.class) + .log(); } private Mono> retrieveGetResponse(RequestHeadersUriSpec spec) { return spec.uri("/resource") .retrieve() - .bodyToMono(MAP_RESPONSE_REF); + .bodyToMono(MAP_RESPONSE_REF) + .log(); } private Mono retrieveResponse(RequestBodySpec spec) { return spec.bodyValue(BODY_VALUE) .retrieve() - .bodyToMono(String.class); + .bodyToMono(String.class) + .log(); } private Mono retrieveResponse(RequestHeadersSpec spec) { return spec.retrieve() - .bodyToMono(String.class); + .bodyToMono(String.class) + .log(); } } From bf5ed18f63eac52bcf15613aa4d1a128656239b5 Mon Sep 17 00:00:00 2001 From: Abhinav Pandey Date: Mon, 18 Jul 2022 14:35:30 +0000 Subject: [PATCH 09/16] BAEL-3201 - Deleting Integration Test file --- .../ProductServiceIntegrationTest.java | 75 ------------------- 1 file changed, 75 deletions(-) delete mode 100644 spring-boot-modules/spring-boot-testing-2/src/test/java/com/baeldung/redistestcontainers/service/ProductServiceIntegrationTest.java diff --git a/spring-boot-modules/spring-boot-testing-2/src/test/java/com/baeldung/redistestcontainers/service/ProductServiceIntegrationTest.java b/spring-boot-modules/spring-boot-testing-2/src/test/java/com/baeldung/redistestcontainers/service/ProductServiceIntegrationTest.java deleted file mode 100644 index 519db1b335..0000000000 --- a/spring-boot-modules/spring-boot-testing-2/src/test/java/com/baeldung/redistestcontainers/service/ProductServiceIntegrationTest.java +++ /dev/null @@ -1,75 +0,0 @@ -package com.baeldung.redistestcontainers.service; - -import com.baeldung.redistestcontainers.hash.Product; -import org.junit.jupiter.api.Test; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.boot.test.context.SpringBootTest; -import org.testcontainers.containers.GenericContainer; -import org.testcontainers.utility.DockerImageName; - -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertNull; - -@SpringBootTest -public class ProductServiceIntegrationTest { - - static { - GenericContainer redis = new GenericContainer<>(DockerImageName.parse("redis:5.0.3-alpine")) - .withExposedPorts(6379); - redis.start(); - System.setProperty("spring.redis.host", redis.getHost()); - System.setProperty("spring.redis.port", redis.getMappedPort(6379).toString()); - } - - @Autowired - private ProductService productService; - - @Test - void givenProductCreated_whenGettingProductById_thenProductExistsAndHasSameProperties() { - Product product = new Product("1", "Test Product", 10.0); - productService.createProduct(product); - Product productFromDb = productService.getProduct("1"); - assertEquals("1", productFromDb.getId()); - assertEquals("Test Product", productFromDb.getName()); - assertEquals(10.0, productFromDb.getPrice()); - } - - @Test - void givenProductCreatedAndUpdated_whenGettingTheProduct_thenUpdatedProductReturned() { - Product product = new Product("1", "Test Product", 10.0); - productService.createProduct(product); - Product productFromDb = productService.getProduct("1"); - assertEquals("1", productFromDb.getId()); - assertEquals("Test Product", productFromDb.getName()); - assertEquals(10.0, productFromDb.getPrice()); - productFromDb.setName("Updated Product"); - productFromDb.setPrice(20.0); - productService.updateProduct(productFromDb); - Product updatedProductFromDb = productService.getProduct("1"); - assertEquals("Updated Product", updatedProductFromDb.getName()); - assertEquals(20.0, updatedProductFromDb.getPrice()); - } - - @Test - void givenProductCreatedAndDeleted_whenGettingTheProduct_thenNoProductReturned() { - Product product = new Product("1", "Test Product", 10.0); - productService.createProduct(product); - Product productFromDb = productService.getProduct("1"); - assertEquals("1", productFromDb.getId()); - assertEquals("Test Product", productFromDb.getName()); - assertEquals(10.0, productFromDb.getPrice()); - productService.deleteProduct("1"); - Product deletedProductFromDb = productService.getProduct("1"); - assertNull(deletedProductFromDb); - } - - @Test - void givenProductCreated_whenGettingProductById_thenSameProductReturned() { - Product product = new Product("1", "Test Product", 10.0); - productService.createProduct(product); - Product productFromDb = productService.getProduct("1"); - assertEquals("1", productFromDb.getId()); - assertEquals("Test Product", productFromDb.getName()); - assertEquals(10.0, productFromDb.getPrice()); - } -} \ No newline at end of file From 7e0f6db35b510b25001db6270e8c1eb30c237136 Mon Sep 17 00:00:00 2001 From: sampadawagde Date: Mon, 18 Jul 2022 20:20:06 +0530 Subject: [PATCH 10/16] JAVA-12754: parent module pom changes --- spring-security-modules/pom.xml | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/spring-security-modules/pom.xml b/spring-security-modules/pom.xml index a75638d085..2bd6d23058 100644 --- a/spring-security-modules/pom.xml +++ b/spring-security-modules/pom.xml @@ -14,8 +14,7 @@ 1.0.0-SNAPSHOT - - spring-5-security + spring-security-acl spring-security-auth0 spring-security-cognito @@ -35,6 +34,7 @@ spring-security-web-boot-3 spring-security-web-digest-auth spring-security-web-login + spring-security-web-login-2 spring-security-web-mvc-custom spring-security-web-mvc spring-security-web-persistent-login From 4761c771c18971ad5518d11c4b8108593d0efc58 Mon Sep 17 00:00:00 2001 From: sampadawagde Date: Mon, 18 Jul 2022 20:20:42 +0530 Subject: [PATCH 11/16] JAVA-12754: removed module spring-5-security --- .../spring-5-security/README.md | 13 - .../spring-5-security/pom.xml | 84 --- .../authresolver/AuthResolverApplication.java | 11 - .../authresolver/AuthResolverController.java | 18 - .../CustomWebSecurityConfigurer.java | 96 --- .../dsl/ClientErrorLoggingConfigurer.java | 32 - .../dsl/ClientErrorLoggingFilter.java | 57 -- .../dsl/CustomConfigurerApplication.java | 13 - .../java/com/baeldung/dsl/MyController.java | 14 - .../java/com/baeldung/dsl/SecurityConfig.java | 50 -- .../inmemory/InMemoryAuthApplication.java | 14 - .../inmemory/InMemoryAuthController.java | 21 - .../InMemoryAuthWebSecurityConfigurer.java | 34 -- ...InMemoryNoOpAuthWebSecurityConfigurer.java | 29 - .../logoutredirects/LogoutApplication.java | 13 - .../securityconfig/SpringSecurityConfig.java | 27 - .../manuallogout/ManualLogoutApplication.java | 11 - .../SimpleSecurityConfiguration.java | 95 --- .../BaeldungPasswordEncoderSetup.java | 35 -- .../PasswordStorageApplication.java | 13 - .../PasswordStorageWebSecurityConfigurer.java | 55 -- .../java/com/baeldung/xss/Application.java | 14 - .../java/com/baeldung/xss/SecurityConf.java | 25 - .../src/main/resources/ESAPI.properties | 545 ------------------ .../src/main/resources/application.properties | 7 - .../src/main/resources/logback.xml | 13 - .../src/main/resources/templates/index.html | 11 - .../java/com/baeldung/SpringContextTest.java | 17 - .../AuthResolverIntegrationTest.java | 82 --- ...InMemoryAuthControllerIntegrationTest.java | 48 -- .../LogoutApplicationUnitTest.java | 34 -- .../ManualLogoutIntegrationTest.java | 96 --- .../src/test/resources/logback-test.xml | 12 - 33 files changed, 1639 deletions(-) delete mode 100644 spring-security-modules/spring-5-security/README.md delete mode 100644 spring-security-modules/spring-5-security/pom.xml delete mode 100644 spring-security-modules/spring-5-security/src/main/java/com/baeldung/authresolver/AuthResolverApplication.java delete mode 100644 spring-security-modules/spring-5-security/src/main/java/com/baeldung/authresolver/AuthResolverController.java delete mode 100644 spring-security-modules/spring-5-security/src/main/java/com/baeldung/authresolver/CustomWebSecurityConfigurer.java delete mode 100644 spring-security-modules/spring-5-security/src/main/java/com/baeldung/dsl/ClientErrorLoggingConfigurer.java delete mode 100644 spring-security-modules/spring-5-security/src/main/java/com/baeldung/dsl/ClientErrorLoggingFilter.java delete mode 100644 spring-security-modules/spring-5-security/src/main/java/com/baeldung/dsl/CustomConfigurerApplication.java delete mode 100644 spring-security-modules/spring-5-security/src/main/java/com/baeldung/dsl/MyController.java delete mode 100644 spring-security-modules/spring-5-security/src/main/java/com/baeldung/dsl/SecurityConfig.java delete mode 100644 spring-security-modules/spring-5-security/src/main/java/com/baeldung/inmemory/InMemoryAuthApplication.java delete mode 100644 spring-security-modules/spring-5-security/src/main/java/com/baeldung/inmemory/InMemoryAuthController.java delete mode 100644 spring-security-modules/spring-5-security/src/main/java/com/baeldung/inmemory/InMemoryAuthWebSecurityConfigurer.java delete mode 100644 spring-security-modules/spring-5-security/src/main/java/com/baeldung/inmemory/InMemoryNoOpAuthWebSecurityConfigurer.java delete mode 100644 spring-security-modules/spring-5-security/src/main/java/com/baeldung/logoutredirects/LogoutApplication.java delete mode 100644 spring-security-modules/spring-5-security/src/main/java/com/baeldung/logoutredirects/securityconfig/SpringSecurityConfig.java delete mode 100644 spring-security-modules/spring-5-security/src/main/java/com/baeldung/manuallogout/ManualLogoutApplication.java delete mode 100644 spring-security-modules/spring-5-security/src/main/java/com/baeldung/manuallogout/SimpleSecurityConfiguration.java delete mode 100644 spring-security-modules/spring-5-security/src/main/java/com/baeldung/passwordstorage/BaeldungPasswordEncoderSetup.java delete mode 100644 spring-security-modules/spring-5-security/src/main/java/com/baeldung/passwordstorage/PasswordStorageApplication.java delete mode 100644 spring-security-modules/spring-5-security/src/main/java/com/baeldung/passwordstorage/PasswordStorageWebSecurityConfigurer.java delete mode 100644 spring-security-modules/spring-5-security/src/main/java/com/baeldung/xss/Application.java delete mode 100644 spring-security-modules/spring-5-security/src/main/java/com/baeldung/xss/SecurityConf.java delete mode 100644 spring-security-modules/spring-5-security/src/main/resources/ESAPI.properties delete mode 100644 spring-security-modules/spring-5-security/src/main/resources/application.properties delete mode 100644 spring-security-modules/spring-5-security/src/main/resources/logback.xml delete mode 100644 spring-security-modules/spring-5-security/src/main/resources/templates/index.html delete mode 100644 spring-security-modules/spring-5-security/src/test/java/com/baeldung/SpringContextTest.java delete mode 100644 spring-security-modules/spring-5-security/src/test/java/com/baeldung/authresolver/AuthResolverIntegrationTest.java delete mode 100644 spring-security-modules/spring-5-security/src/test/java/com/baeldung/inmemory/InMemoryAuthControllerIntegrationTest.java delete mode 100644 spring-security-modules/spring-5-security/src/test/java/com/baeldung/logoutredirects/LogoutApplicationUnitTest.java delete mode 100644 spring-security-modules/spring-5-security/src/test/java/com/baeldung/manuallogout/ManualLogoutIntegrationTest.java delete mode 100644 spring-security-modules/spring-5-security/src/test/resources/logback-test.xml diff --git a/spring-security-modules/spring-5-security/README.md b/spring-security-modules/spring-5-security/README.md deleted file mode 100644 index dac2d0f6b8..0000000000 --- a/spring-security-modules/spring-5-security/README.md +++ /dev/null @@ -1,13 +0,0 @@ -## Spring 5 Security - -This module contains articles about Spring Security 5 - -## Relevant articles: - -- [A Custom Spring SecurityConfigurer](https://www.baeldung.com/spring-security-custom-configurer) -- [New Password Storage In Spring Security 5](https://www.baeldung.com/spring-security-5-password-storage) -- [Default Password Encoder in Spring Security 5](https://www.baeldung.com/spring-security-5-default-password-encoder) -- [Guide to the AuthenticationManagerResolver in Spring Security](https://www.baeldung.com/spring-security-authenticationmanagerresolver) -- [Manual Logout With Spring Security](https://www.baeldung.com/spring-security-manual-logout) -- [How to Disable Spring Security Logout Redirects](https://www.baeldung.com/spring-security-disable-logout-redirects) -- [Prevent Cross-Site Scripting (XSS) in a Spring Application](https://www.baeldung.com/spring-prevent-xss) diff --git a/spring-security-modules/spring-5-security/pom.xml b/spring-security-modules/spring-5-security/pom.xml deleted file mode 100644 index b487e8b282..0000000000 --- a/spring-security-modules/spring-5-security/pom.xml +++ /dev/null @@ -1,84 +0,0 @@ - - - 4.0.0 - spring-5-security - 0.0.1-SNAPSHOT - spring-5-security - jar - spring 5 security sample project - - - com.baeldung - parent-boot-2 - 0.0.1-SNAPSHOT - ../../parent-boot-2 - - - - - org.springframework.boot - spring-boot-starter-security - - - org.springframework.boot - spring-boot-starter-web - - - org.springframework.boot - spring-boot-starter-thymeleaf - - - org.thymeleaf.extras - thymeleaf-extras-springsecurity5 - - - org.springframework - spring-test - - - org.springframework.boot - spring-boot-starter-test - test - - - org.springframework.security - spring-security-test - test - - - org.owasp.esapi - esapi - ${esapi.version} - - - org.jsoup - jsoup - ${jsoup.version} - - - commons-io - commons-io - ${commons-io.version} - - - - - - - org.springframework.boot - spring-boot-maven-plugin - - com.baeldung.passwordstorage.PasswordStorageApplication - JAR - - - - - - - 1.13.1 - - - \ No newline at end of file diff --git a/spring-security-modules/spring-5-security/src/main/java/com/baeldung/authresolver/AuthResolverApplication.java b/spring-security-modules/spring-5-security/src/main/java/com/baeldung/authresolver/AuthResolverApplication.java deleted file mode 100644 index 96ee674b15..0000000000 --- a/spring-security-modules/spring-5-security/src/main/java/com/baeldung/authresolver/AuthResolverApplication.java +++ /dev/null @@ -1,11 +0,0 @@ -package com.baeldung.authresolver; - -import org.springframework.boot.SpringApplication; -import org.springframework.boot.autoconfigure.SpringBootApplication; - -@SpringBootApplication -public class AuthResolverApplication { - public static void main(String[] args) { - SpringApplication.run(AuthResolverApplication.class, args); - } -} diff --git a/spring-security-modules/spring-5-security/src/main/java/com/baeldung/authresolver/AuthResolverController.java b/spring-security-modules/spring-5-security/src/main/java/com/baeldung/authresolver/AuthResolverController.java deleted file mode 100644 index 7dc6900b5a..0000000000 --- a/spring-security-modules/spring-5-security/src/main/java/com/baeldung/authresolver/AuthResolverController.java +++ /dev/null @@ -1,18 +0,0 @@ -package com.baeldung.authresolver; - -import org.springframework.security.core.Authentication; -import org.springframework.web.bind.annotation.GetMapping; -import org.springframework.web.bind.annotation.RestController; - -@RestController -public class AuthResolverController { - @GetMapping("/customer/welcome") - public String sayWelcomeToCustomer(Authentication authentication) { - return String.format("Welcome to our site, %s!", authentication.getPrincipal()); - } - - @GetMapping("/employee/welcome") - public String sayWelcomeToEmployee(Authentication authentication) { - return String.format("Welcome to our company, %s!", authentication.getPrincipal()); - } -} diff --git a/spring-security-modules/spring-5-security/src/main/java/com/baeldung/authresolver/CustomWebSecurityConfigurer.java b/spring-security-modules/spring-5-security/src/main/java/com/baeldung/authresolver/CustomWebSecurityConfigurer.java deleted file mode 100644 index 33ef692173..0000000000 --- a/spring-security-modules/spring-5-security/src/main/java/com/baeldung/authresolver/CustomWebSecurityConfigurer.java +++ /dev/null @@ -1,96 +0,0 @@ -package com.baeldung.authresolver; - -import java.util.Collections; -import javax.servlet.http.HttpServletRequest; -import org.springframework.context.annotation.Configuration; -import org.springframework.security.authentication.AuthenticationManager; -import org.springframework.security.authentication.AuthenticationManagerResolver; -import org.springframework.security.authentication.UsernamePasswordAuthenticationToken; -import org.springframework.security.config.annotation.web.builders.HttpSecurity; -import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter; -import org.springframework.security.core.Authentication; -import org.springframework.security.core.authority.SimpleGrantedAuthority; -import org.springframework.security.core.userdetails.UsernameNotFoundException; -import org.springframework.security.web.authentication.AuthenticationConverter; -import org.springframework.security.web.authentication.AuthenticationFilter; -import org.springframework.security.web.authentication.www.BasicAuthenticationConverter; -import org.springframework.security.web.authentication.www.BasicAuthenticationFilter; - -@Configuration -public class CustomWebSecurityConfigurer extends WebSecurityConfigurerAdapter { - - public AuthenticationConverter authenticationConverter() { - return new BasicAuthenticationConverter(); - } - - public AuthenticationManagerResolver resolver() { - return request -> { - if (request - .getPathInfo() - .startsWith("/employee")) { - return employeesAuthenticationManager(); - } - return customersAuthenticationManager(); - }; - } - - public AuthenticationManager customersAuthenticationManager() { - return authentication -> { - if (isCustomer(authentication)) { - return new UsernamePasswordAuthenticationToken( - authentication.getPrincipal(), - authentication.getCredentials(), - Collections.singletonList(new SimpleGrantedAuthority("ROLE_USER")) - ); - } - throw new UsernameNotFoundException(authentication - .getPrincipal() - .toString()); - }; - } - - private boolean isCustomer(Authentication authentication) { - return (authentication - .getPrincipal() - .toString() - .startsWith("customer")); - } - - private boolean isEmployee(Authentication authentication) { - return (authentication - .getPrincipal() - .toString() - .startsWith("employee")); - } - - private AuthenticationFilter authenticationFilter() { - AuthenticationFilter filter = new AuthenticationFilter( - resolver(), authenticationConverter()); - filter.setSuccessHandler((request, response, auth) -> {}); - return filter; - } - - private AuthenticationManager employeesAuthenticationManager() { - return authentication -> { - if (isEmployee(authentication)) { - return new UsernamePasswordAuthenticationToken( - authentication.getPrincipal(), - authentication.getCredentials(), - Collections.singletonList(new SimpleGrantedAuthority("ROLE_USER")) - ); - } - throw new UsernameNotFoundException(authentication - .getPrincipal() - .toString()); - }; - } - - @Override - protected void configure(HttpSecurity http) { - http.addFilterBefore( - authenticationFilter(), - BasicAuthenticationFilter.class - ); - } - -} diff --git a/spring-security-modules/spring-5-security/src/main/java/com/baeldung/dsl/ClientErrorLoggingConfigurer.java b/spring-security-modules/spring-5-security/src/main/java/com/baeldung/dsl/ClientErrorLoggingConfigurer.java deleted file mode 100644 index 5a9479b664..0000000000 --- a/spring-security-modules/spring-5-security/src/main/java/com/baeldung/dsl/ClientErrorLoggingConfigurer.java +++ /dev/null @@ -1,32 +0,0 @@ -package com.baeldung.dsl; - -import java.util.List; - -import org.springframework.http.HttpStatus; -import org.springframework.security.config.annotation.web.builders.HttpSecurity; -import org.springframework.security.config.annotation.web.configurers.AbstractHttpConfigurer; -import org.springframework.security.web.access.intercept.FilterSecurityInterceptor; - -public class ClientErrorLoggingConfigurer extends AbstractHttpConfigurer { - - private List errorCodes; - - public ClientErrorLoggingConfigurer(List errorCodes) { - this.errorCodes = errorCodes; - } - - public ClientErrorLoggingConfigurer() { - - } - - @Override - public void init(HttpSecurity http) throws Exception { - // initialization code - } - - @Override - public void configure(HttpSecurity http) throws Exception { - http.addFilterAfter(new ClientErrorLoggingFilter(errorCodes), FilterSecurityInterceptor.class); - } - -} diff --git a/spring-security-modules/spring-5-security/src/main/java/com/baeldung/dsl/ClientErrorLoggingFilter.java b/spring-security-modules/spring-5-security/src/main/java/com/baeldung/dsl/ClientErrorLoggingFilter.java deleted file mode 100644 index cb174cad28..0000000000 --- a/spring-security-modules/spring-5-security/src/main/java/com/baeldung/dsl/ClientErrorLoggingFilter.java +++ /dev/null @@ -1,57 +0,0 @@ -package com.baeldung.dsl; - -import java.io.IOException; -import java.util.List; - -import javax.servlet.FilterChain; -import javax.servlet.ServletException; -import javax.servlet.ServletRequest; -import javax.servlet.ServletResponse; -import javax.servlet.http.HttpServletResponse; - -import org.apache.logging.log4j.LogManager; -import org.apache.logging.log4j.Logger; -import org.springframework.http.HttpStatus; -import org.springframework.security.core.Authentication; -import org.springframework.security.core.context.SecurityContextHolder; -import org.springframework.web.filter.GenericFilterBean; - -public class ClientErrorLoggingFilter extends GenericFilterBean { - - private static final Logger logger = LogManager.getLogger(ClientErrorLoggingFilter.class); - - private List errorCodes; - - public ClientErrorLoggingFilter(List errorCodes) { - this.errorCodes = errorCodes; - } - - @Override - public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { - - Authentication auth = SecurityContextHolder.getContext() - .getAuthentication(); - - if (auth == null) { - chain.doFilter(request, response); - return; - } - int status = ((HttpServletResponse) response).getStatus(); - if (status < 400 || status >= 500) { - chain.doFilter(request, response); - return; - } - - if (errorCodes == null) { - logger.debug("User " + auth.getName() + " encountered error " + status); - } else { - if (errorCodes.stream() - .anyMatch(s -> s.value() == status)) { - logger.debug("User " + auth.getName() + " encountered error " + status); - } - } - - chain.doFilter(request, response); - } - -} diff --git a/spring-security-modules/spring-5-security/src/main/java/com/baeldung/dsl/CustomConfigurerApplication.java b/spring-security-modules/spring-5-security/src/main/java/com/baeldung/dsl/CustomConfigurerApplication.java deleted file mode 100644 index 2cd3d7fc7f..0000000000 --- a/spring-security-modules/spring-5-security/src/main/java/com/baeldung/dsl/CustomConfigurerApplication.java +++ /dev/null @@ -1,13 +0,0 @@ -package com.baeldung.dsl; - -import org.springframework.boot.SpringApplication; -import org.springframework.boot.autoconfigure.SpringBootApplication; - -@SpringBootApplication -public class CustomConfigurerApplication { - - public static void main(String[] args) { - SpringApplication.run(CustomConfigurerApplication.class, args); - } - -} diff --git a/spring-security-modules/spring-5-security/src/main/java/com/baeldung/dsl/MyController.java b/spring-security-modules/spring-5-security/src/main/java/com/baeldung/dsl/MyController.java deleted file mode 100644 index c69046afb5..0000000000 --- a/spring-security-modules/spring-5-security/src/main/java/com/baeldung/dsl/MyController.java +++ /dev/null @@ -1,14 +0,0 @@ -package com.baeldung.dsl; - -import org.springframework.web.bind.annotation.GetMapping; -import org.springframework.web.bind.annotation.RestController; - -@RestController -public class MyController { - - @GetMapping("/admin") - public String getAdminPage() { - return "Hello Admin"; - } - -} diff --git a/spring-security-modules/spring-5-security/src/main/java/com/baeldung/dsl/SecurityConfig.java b/spring-security-modules/spring-5-security/src/main/java/com/baeldung/dsl/SecurityConfig.java deleted file mode 100644 index 382e222f64..0000000000 --- a/spring-security-modules/spring-5-security/src/main/java/com/baeldung/dsl/SecurityConfig.java +++ /dev/null @@ -1,50 +0,0 @@ -package com.baeldung.dsl; - -import org.springframework.context.annotation.Bean; -import org.springframework.context.annotation.Configuration; -import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder; -import org.springframework.security.config.annotation.web.builders.HttpSecurity; -import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter; -import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder; -import org.springframework.security.crypto.password.PasswordEncoder; - -@Configuration -public class SecurityConfig extends WebSecurityConfigurerAdapter { - - @Override - protected void configure(HttpSecurity http) throws Exception { - http.authorizeRequests() - .antMatchers("/admin*") - .hasAnyRole("ADMIN") - .anyRequest() - .authenticated() - .and() - .formLogin() - .and() - .apply(clientErrorLogging()); - } - - @Bean - public ClientErrorLoggingConfigurer clientErrorLogging() { - return new ClientErrorLoggingConfigurer(); - } - - @Override - protected void configure(AuthenticationManagerBuilder auth) throws Exception { - auth.inMemoryAuthentication() - .passwordEncoder(passwordEncoder()) - .withUser("user1") - .password(passwordEncoder().encode("user")) - .roles("USER") - .and() - .withUser("admin") - .password(passwordEncoder().encode("admin")) - .roles("ADMIN"); - } - - @Bean - public PasswordEncoder passwordEncoder() { - return new BCryptPasswordEncoder(); - } - -} diff --git a/spring-security-modules/spring-5-security/src/main/java/com/baeldung/inmemory/InMemoryAuthApplication.java b/spring-security-modules/spring-5-security/src/main/java/com/baeldung/inmemory/InMemoryAuthApplication.java deleted file mode 100644 index 6ccfd04553..0000000000 --- a/spring-security-modules/spring-5-security/src/main/java/com/baeldung/inmemory/InMemoryAuthApplication.java +++ /dev/null @@ -1,14 +0,0 @@ -package com.baeldung.inmemory; - -import org.springframework.boot.SpringApplication; -import org.springframework.boot.autoconfigure.SpringBootApplication; - -@SpringBootApplication -public class InMemoryAuthApplication { - - public static void main(String[] args) { - SpringApplication.run(InMemoryAuthApplication.class, args); - } - - -} diff --git a/spring-security-modules/spring-5-security/src/main/java/com/baeldung/inmemory/InMemoryAuthController.java b/spring-security-modules/spring-5-security/src/main/java/com/baeldung/inmemory/InMemoryAuthController.java deleted file mode 100644 index ff7ae9a131..0000000000 --- a/spring-security-modules/spring-5-security/src/main/java/com/baeldung/inmemory/InMemoryAuthController.java +++ /dev/null @@ -1,21 +0,0 @@ -package com.baeldung.inmemory; - -import java.util.Arrays; -import java.util.List; -import org.springframework.web.bind.annotation.GetMapping; -import org.springframework.web.bind.annotation.RestController; - -@RestController -public class InMemoryAuthController { - - @GetMapping("/public/hello") - public List publicHello() { - return Arrays.asList("Hello", "World", "from", "Public"); - } - - @GetMapping("/private/hello") - public List privateHello() { - return Arrays.asList("Hello", "World", "from", "Private"); - } - -} diff --git a/spring-security-modules/spring-5-security/src/main/java/com/baeldung/inmemory/InMemoryAuthWebSecurityConfigurer.java b/spring-security-modules/spring-5-security/src/main/java/com/baeldung/inmemory/InMemoryAuthWebSecurityConfigurer.java deleted file mode 100644 index 4b32a1126e..0000000000 --- a/spring-security-modules/spring-5-security/src/main/java/com/baeldung/inmemory/InMemoryAuthWebSecurityConfigurer.java +++ /dev/null @@ -1,34 +0,0 @@ -package com.baeldung.inmemory; - -import org.springframework.context.annotation.Configuration; -import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder; -import org.springframework.security.config.annotation.web.builders.HttpSecurity; -import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter; -import org.springframework.security.crypto.factory.PasswordEncoderFactories; -import org.springframework.security.crypto.password.PasswordEncoder; - -@Configuration -public class InMemoryAuthWebSecurityConfigurer extends WebSecurityConfigurerAdapter { - - @Override - protected void configure(AuthenticationManagerBuilder auth) throws Exception { - PasswordEncoder encoder = PasswordEncoderFactories.createDelegatingPasswordEncoder(); - auth.inMemoryAuthentication() - .passwordEncoder(encoder) - .withUser("spring") - .password(encoder.encode("secret")) - .roles("USER"); - } - - @Override - protected void configure(HttpSecurity http) throws Exception { - http.authorizeRequests() - .antMatchers("/private/**") - .authenticated() - .antMatchers("/public/**") - .permitAll() - .and() - .httpBasic(); - } - -} diff --git a/spring-security-modules/spring-5-security/src/main/java/com/baeldung/inmemory/InMemoryNoOpAuthWebSecurityConfigurer.java b/spring-security-modules/spring-5-security/src/main/java/com/baeldung/inmemory/InMemoryNoOpAuthWebSecurityConfigurer.java deleted file mode 100644 index 4b6494f666..0000000000 --- a/spring-security-modules/spring-5-security/src/main/java/com/baeldung/inmemory/InMemoryNoOpAuthWebSecurityConfigurer.java +++ /dev/null @@ -1,29 +0,0 @@ -package com.baeldung.inmemory; - -import org.springframework.context.annotation.Configuration; -import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder; -import org.springframework.security.config.annotation.web.builders.HttpSecurity; -import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter; - -//@Configuration -public class InMemoryNoOpAuthWebSecurityConfigurer extends WebSecurityConfigurerAdapter { - - @Override - protected void configure(AuthenticationManagerBuilder auth) throws Exception { - auth.inMemoryAuthentication() - .withUser("spring") - .password("{noop}secret") - .roles("USER"); - } - - @Override - protected void configure(HttpSecurity http) throws Exception { - http.authorizeRequests() - .antMatchers("/private/**") - .authenticated() - .antMatchers("/public/**") - .permitAll() - .and() - .httpBasic(); - } -} diff --git a/spring-security-modules/spring-5-security/src/main/java/com/baeldung/logoutredirects/LogoutApplication.java b/spring-security-modules/spring-5-security/src/main/java/com/baeldung/logoutredirects/LogoutApplication.java deleted file mode 100644 index ef8175ffb2..0000000000 --- a/spring-security-modules/spring-5-security/src/main/java/com/baeldung/logoutredirects/LogoutApplication.java +++ /dev/null @@ -1,13 +0,0 @@ -package com.baeldung.logoutredirects; - -import org.springframework.boot.SpringApplication; -import org.springframework.boot.autoconfigure.SpringBootApplication; - -@SpringBootApplication -public class LogoutApplication { - - public static void main(String[] args) { - SpringApplication.run(LogoutApplication.class, args); - } - -} diff --git a/spring-security-modules/spring-5-security/src/main/java/com/baeldung/logoutredirects/securityconfig/SpringSecurityConfig.java b/spring-security-modules/spring-5-security/src/main/java/com/baeldung/logoutredirects/securityconfig/SpringSecurityConfig.java deleted file mode 100644 index 64141f63d8..0000000000 --- a/spring-security-modules/spring-5-security/src/main/java/com/baeldung/logoutredirects/securityconfig/SpringSecurityConfig.java +++ /dev/null @@ -1,27 +0,0 @@ -package com.baeldung.logoutredirects.securityconfig; - -import javax.servlet.http.HttpServletResponse; - -import org.springframework.context.annotation.Configuration; -import org.springframework.security.config.annotation.web.builders.HttpSecurity; -import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity; -import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter; - -@Configuration -@EnableWebSecurity -public class SpringSecurityConfig extends WebSecurityConfigurerAdapter { - - @Override - protected void configure(HttpSecurity http) throws Exception { - http.authorizeRequests(authz -> authz.mvcMatchers("/login") - .permitAll() - .anyRequest() - .authenticated()) - .logout(logout -> logout.permitAll() - .logoutSuccessHandler((request, response, authentication) -> { - response.setStatus(HttpServletResponse.SC_OK); - })); - - } - -} diff --git a/spring-security-modules/spring-5-security/src/main/java/com/baeldung/manuallogout/ManualLogoutApplication.java b/spring-security-modules/spring-5-security/src/main/java/com/baeldung/manuallogout/ManualLogoutApplication.java deleted file mode 100644 index 50ea356f03..0000000000 --- a/spring-security-modules/spring-5-security/src/main/java/com/baeldung/manuallogout/ManualLogoutApplication.java +++ /dev/null @@ -1,11 +0,0 @@ -package com.baeldung.manuallogout; - -import org.springframework.boot.SpringApplication; -import org.springframework.boot.autoconfigure.SpringBootApplication; - -@SpringBootApplication -public class ManualLogoutApplication { - public static void main(String[] args) { - SpringApplication.run(ManualLogoutApplication.class, args); - } -} diff --git a/spring-security-modules/spring-5-security/src/main/java/com/baeldung/manuallogout/SimpleSecurityConfiguration.java b/spring-security-modules/spring-5-security/src/main/java/com/baeldung/manuallogout/SimpleSecurityConfiguration.java deleted file mode 100644 index 303a139215..0000000000 --- a/spring-security-modules/spring-5-security/src/main/java/com/baeldung/manuallogout/SimpleSecurityConfiguration.java +++ /dev/null @@ -1,95 +0,0 @@ -package com.baeldung.manuallogout; - -import static org.springframework.security.web.header.writers.ClearSiteDataHeaderWriter.Directive.CACHE; -import static org.springframework.security.web.header.writers.ClearSiteDataHeaderWriter.Directive.COOKIES; -import static org.springframework.security.web.header.writers.ClearSiteDataHeaderWriter.Directive.EXECUTION_CONTEXTS; -import static org.springframework.security.web.header.writers.ClearSiteDataHeaderWriter.Directive.STORAGE; - -import javax.servlet.ServletException; -import javax.servlet.http.Cookie; - -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import org.springframework.context.annotation.Configuration; -import org.springframework.core.annotation.Order; -import org.springframework.security.config.annotation.web.builders.HttpSecurity; -import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity; -import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter; -import org.springframework.security.web.authentication.logout.HeaderWriterLogoutHandler; -import org.springframework.security.web.authentication.logout.SecurityContextLogoutHandler; -import org.springframework.security.web.header.writers.ClearSiteDataHeaderWriter; - -@Configuration -@EnableWebSecurity -public class SimpleSecurityConfiguration { - - private static Logger logger = LoggerFactory.getLogger(SimpleSecurityConfiguration.class); - - @Order(4) - @Configuration - public static class LogoutOnRequestConfiguration extends WebSecurityConfigurerAdapter { - @Override - protected void configure(HttpSecurity http) throws Exception { - http.antMatcher("/request/**") - .authorizeRequests(authz -> authz.anyRequest() - .permitAll()) - .logout(logout -> logout.logoutUrl("/request/logout") - .addLogoutHandler((request, response, auth) -> { - try { - request.logout(); - } catch (ServletException e) { - logger.error(e.getMessage()); - } - })); - } - } - - @Order(3) - @Configuration - public static class DefaultLogoutConfiguration extends WebSecurityConfigurerAdapter { - @Override - protected void configure(HttpSecurity http) throws Exception { - http.antMatcher("/basic/**") - .authorizeRequests(authz -> authz.anyRequest() - .permitAll()) - .logout(logout -> logout.logoutUrl("/basic/basiclogout")); - } - } - - @Order(2) - @Configuration - public static class AllCookieClearingLogoutConfiguration extends WebSecurityConfigurerAdapter { - @Override - protected void configure(HttpSecurity http) throws Exception { - http.antMatcher("/cookies/**") - .authorizeRequests(authz -> authz.anyRequest() - .permitAll()) - .logout(logout -> logout.logoutUrl("/cookies/cookielogout") - .addLogoutHandler(new SecurityContextLogoutHandler()) - .addLogoutHandler((request, response, auth) -> { - for (Cookie cookie : request.getCookies()) { - String cookieName = cookie.getName(); - Cookie cookieToDelete = new Cookie(cookieName, null); - cookieToDelete.setMaxAge(0); - response.addCookie(cookieToDelete); - } - })); - } - } - - @Order(1) - @Configuration - public static class ClearSiteDataHeaderLogoutConfiguration extends WebSecurityConfigurerAdapter { - - private static final ClearSiteDataHeaderWriter.Directive[] SOURCE = { CACHE, COOKIES, STORAGE, EXECUTION_CONTEXTS }; - - @Override - protected void configure(HttpSecurity http) throws Exception { - http.antMatcher("/csd/**") - .authorizeRequests(authz -> authz.anyRequest() - .permitAll()) - .logout(logout -> logout.logoutUrl("/csd/csdlogout") - .addLogoutHandler(new HeaderWriterLogoutHandler(new ClearSiteDataHeaderWriter(SOURCE)))); - } - } -} diff --git a/spring-security-modules/spring-5-security/src/main/java/com/baeldung/passwordstorage/BaeldungPasswordEncoderSetup.java b/spring-security-modules/spring-5-security/src/main/java/com/baeldung/passwordstorage/BaeldungPasswordEncoderSetup.java deleted file mode 100644 index 94987029db..0000000000 --- a/spring-security-modules/spring-5-security/src/main/java/com/baeldung/passwordstorage/BaeldungPasswordEncoderSetup.java +++ /dev/null @@ -1,35 +0,0 @@ -package com.baeldung.passwordstorage; - -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import org.springframework.context.ApplicationListener; -import org.springframework.context.annotation.Bean; -import org.springframework.context.annotation.Configuration; -import org.springframework.security.authentication.UsernamePasswordAuthenticationToken; -import org.springframework.security.authentication.event.AuthenticationSuccessEvent; -import org.springframework.security.core.Authentication; -import org.springframework.security.crypto.password.PasswordEncoder; - -@Configuration -public class BaeldungPasswordEncoderSetup { - - private final static Logger LOG = LoggerFactory.getLogger(BaeldungPasswordEncoderSetup.class); - - @Bean - public ApplicationListener authenticationSuccessListener(final PasswordEncoder encoder) { - - return (AuthenticationSuccessEvent event) -> { - final Authentication auth = event.getAuthentication(); - - if (auth instanceof UsernamePasswordAuthenticationToken && auth.getCredentials() != null) { - - final CharSequence clearTextPass = (CharSequence) auth.getCredentials(); // 1 - final String newPasswordHash = encoder.encode(clearTextPass); // 2 - - LOG.info("New password hash {} for user {}", newPasswordHash, auth.getName()); - - ((UsernamePasswordAuthenticationToken) auth).eraseCredentials(); // 3 - } - }; - } -} diff --git a/spring-security-modules/spring-5-security/src/main/java/com/baeldung/passwordstorage/PasswordStorageApplication.java b/spring-security-modules/spring-5-security/src/main/java/com/baeldung/passwordstorage/PasswordStorageApplication.java deleted file mode 100644 index 173d979a45..0000000000 --- a/spring-security-modules/spring-5-security/src/main/java/com/baeldung/passwordstorage/PasswordStorageApplication.java +++ /dev/null @@ -1,13 +0,0 @@ -package com.baeldung.passwordstorage; - -import org.springframework.boot.SpringApplication; -import org.springframework.boot.autoconfigure.SpringBootApplication; - -@SpringBootApplication -public class PasswordStorageApplication { - - public static void main(String[] args) { - SpringApplication.run(PasswordStorageApplication.class, args); - } - -} diff --git a/spring-security-modules/spring-5-security/src/main/java/com/baeldung/passwordstorage/PasswordStorageWebSecurityConfigurer.java b/spring-security-modules/spring-5-security/src/main/java/com/baeldung/passwordstorage/PasswordStorageWebSecurityConfigurer.java deleted file mode 100644 index 59a2ae1dc2..0000000000 --- a/spring-security-modules/spring-5-security/src/main/java/com/baeldung/passwordstorage/PasswordStorageWebSecurityConfigurer.java +++ /dev/null @@ -1,55 +0,0 @@ -package com.baeldung.passwordstorage; - -import org.springframework.context.annotation.Bean; -import org.springframework.context.annotation.Configuration; -import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder; -import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter; -import org.springframework.security.core.userdetails.User; -import org.springframework.security.core.userdetails.UserDetailsService; -import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder; -import org.springframework.security.crypto.password.DelegatingPasswordEncoder; -import org.springframework.security.crypto.password.NoOpPasswordEncoder; -import org.springframework.security.crypto.password.PasswordEncoder; -import org.springframework.security.crypto.password.StandardPasswordEncoder; -import org.springframework.security.crypto.scrypt.SCryptPasswordEncoder; -import org.springframework.security.provisioning.InMemoryUserDetailsManager; - -import java.util.Collections; -import java.util.HashMap; -import java.util.Map; - -@Configuration -public class PasswordStorageWebSecurityConfigurer extends WebSecurityConfigurerAdapter { - - @Override - protected void configure(AuthenticationManagerBuilder auth) throws Exception { - auth.eraseCredentials(false) // 4 - .userDetailsService(getUserDefaultDetailsService()) - .passwordEncoder(passwordEncoder()); - } - - @Bean - public UserDetailsService getUserDefaultDetailsService() { - return new InMemoryUserDetailsManager(User - .withUsername("baeldung") - .password("{noop}SpringSecurity5") - .authorities(Collections.emptyList()) - .build()); - } - - @Bean - public PasswordEncoder passwordEncoder() { - // set up the list of supported encoders and their prefixes - PasswordEncoder defaultEncoder = new StandardPasswordEncoder(); - Map encoders = new HashMap<>(); - encoders.put("bcrypt", new BCryptPasswordEncoder()); - encoders.put("scrypt", new SCryptPasswordEncoder()); - encoders.put("noop", NoOpPasswordEncoder.getInstance()); - - DelegatingPasswordEncoder passwordEncoder = new DelegatingPasswordEncoder("bcrypt", encoders); - passwordEncoder.setDefaultPasswordEncoderForMatches(defaultEncoder); - - return passwordEncoder; - } - -} diff --git a/spring-security-modules/spring-5-security/src/main/java/com/baeldung/xss/Application.java b/spring-security-modules/spring-5-security/src/main/java/com/baeldung/xss/Application.java deleted file mode 100644 index b463a7adc3..0000000000 --- a/spring-security-modules/spring-5-security/src/main/java/com/baeldung/xss/Application.java +++ /dev/null @@ -1,14 +0,0 @@ -package com.baeldung.xss; - -import org.springframework.boot.SpringApplication; -import org.springframework.boot.autoconfigure.SpringBootApplication; -import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity; - -@SpringBootApplication -@EnableWebSecurity -public class Application { - - public static void main(String[] args) { - SpringApplication.run(Application.class, args); - } -} diff --git a/spring-security-modules/spring-5-security/src/main/java/com/baeldung/xss/SecurityConf.java b/spring-security-modules/spring-5-security/src/main/java/com/baeldung/xss/SecurityConf.java deleted file mode 100644 index 25d8026e4a..0000000000 --- a/spring-security-modules/spring-5-security/src/main/java/com/baeldung/xss/SecurityConf.java +++ /dev/null @@ -1,25 +0,0 @@ -package com.baeldung.xss; - -import org.springframework.context.annotation.Configuration; -import org.springframework.security.config.annotation.web.builders.HttpSecurity; -import org.springframework.security.config.annotation.web.builders.WebSecurity; -import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter; - -@Configuration -public class SecurityConf extends WebSecurityConfigurerAdapter { - - @Override - public void configure(WebSecurity web) { - // Ignoring here is only for this example. Normally people would apply their own authentication/authorization policies - web.ignoring().antMatchers("/**"); - } - - @Override - protected void configure(HttpSecurity http) throws Exception { - http - .headers() - .xssProtection() - .and() - .contentSecurityPolicy("script-src 'self'"); - } -} diff --git a/spring-security-modules/spring-5-security/src/main/resources/ESAPI.properties b/spring-security-modules/spring-5-security/src/main/resources/ESAPI.properties deleted file mode 100644 index a2746a4dbc..0000000000 --- a/spring-security-modules/spring-5-security/src/main/resources/ESAPI.properties +++ /dev/null @@ -1,545 +0,0 @@ -# -# OWASP Enterprise Security API (ESAPI) Properties file -- PRODUCTION Version -# -# This file is part of the Open Web Application Security Project (OWASP) -# Enterprise Security API (ESAPI) project. For details, please see -# https://owasp.org/www-project-enterprise-security-api/ -# -# Copyright (c) 2008,2009 - The OWASP Foundation -# -# DISCUSS: This may cause a major backwards compatibility issue, etc. but -# from a name space perspective, we probably should have prefaced -# all the property names with ESAPI or at least OWASP. Otherwise -# there could be problems is someone loads this properties file into -# the System properties. We could also put this file into the -# esapi.jar file (perhaps as a ResourceBundle) and then allow an external -# ESAPI properties be defined that would overwrite these defaults. -# That keeps the application's properties relatively simple as usually -# they will only want to override a few properties. If looks like we -# already support multiple override levels of this in the -# DefaultSecurityConfiguration class, but I'm suggesting placing the -# defaults in the esapi.jar itself. That way, if the jar is signed, -# we could detect if those properties had been tampered with. (The -# code to check the jar signatures is pretty simple... maybe 70-90 LOC, -# but off course there is an execution penalty (similar to the way -# that the separate sunjce.jar used to be when a class from it was -# first loaded). Thoughts? -############################################################################### -# -# WARNING: Operating system protection should be used to lock down the .esapi -# resources directory and all the files inside and all the directories all the -# way up to the root directory of the file system. Note that if you are using -# file-based implementations, that some files may need to be read-write as they -# get updated dynamically. -# -#=========================================================================== -# ESAPI Configuration -# -# If true, then print all the ESAPI properties set here when they are loaded. -# If false, they are not printed. Useful to reduce output when running JUnit tests. -# If you need to troubleshoot a properties related problem, turning this on may help. -# This is 'false' in the src/test/resources/.esapi version. It is 'true' by -# default for reasons of backward compatibility with earlier ESAPI versions. -ESAPI.printProperties=true - -# ESAPI is designed to be easily extensible. You can use the reference implementation -# or implement your own providers to take advantage of your enterprise's security -# infrastructure. The functions in ESAPI are referenced using the ESAPI locator, like: -# -# String ciphertext = -# ESAPI.encryptor().encrypt("Secret message"); // Deprecated in 2.0 -# CipherText cipherText = -# ESAPI.encryptor().encrypt(new PlainText("Secret message")); // Preferred -# -# Below you can specify the classname for the provider that you wish to use in your -# application. The only requirement is that it implement the appropriate ESAPI interface. -# This allows you to switch security implementations in the future without rewriting the -# entire application. -# -# ExperimentalAccessController requires ESAPI-AccessControlPolicy.xml in .esapi directory -ESAPI.AccessControl=org.owasp.esapi.reference.DefaultAccessController -# FileBasedAuthenticator requires users.txt file in .esapi directory -ESAPI.Authenticator=org.owasp.esapi.reference.FileBasedAuthenticator -ESAPI.Encoder=org.owasp.esapi.reference.DefaultEncoder -ESAPI.Encryptor=org.owasp.esapi.reference.crypto.JavaEncryptor - -ESAPI.Executor=org.owasp.esapi.reference.DefaultExecutor -ESAPI.HTTPUtilities=org.owasp.esapi.reference.DefaultHTTPUtilities -ESAPI.IntrusionDetector=org.owasp.esapi.reference.DefaultIntrusionDetector -# Log4JFactory Requires log4j.xml or log4j.properties in classpath - http://www.laliluna.de/log4j-tutorial.html -# Note that this is now considered deprecated! -ESAPI.Logger=org.owasp.esapi.logging.slf4j.Slf4JLogFactory -#ESAPI.Logger=org.owasp.esapi.logging.log4j.Log4JLogFactory -#ESAPI.Logger=org.owasp.esapi.logging.java.JavaLogFactory -# To use the new SLF4J logger in ESAPI (see GitHub issue #129), set -# ESAPI.Logger=org.owasp.esapi.logging.slf4j.Slf4JLogFactory -# and do whatever other normal SLF4J configuration that you normally would do for your application. -ESAPI.Randomizer=org.owasp.esapi.reference.DefaultRandomizer -ESAPI.Validator=org.owasp.esapi.reference.DefaultValidator - -#=========================================================================== -# ESAPI Authenticator -# -Authenticator.AllowedLoginAttempts=3 -Authenticator.MaxOldPasswordHashes=13 -Authenticator.UsernameParameterName=username -Authenticator.PasswordParameterName=password -# RememberTokenDuration (in days) -Authenticator.RememberTokenDuration=14 -# Session Timeouts (in minutes) -Authenticator.IdleTimeoutDuration=20 -Authenticator.AbsoluteTimeoutDuration=120 - -#=========================================================================== -# ESAPI Encoder -# -# ESAPI canonicalizes input before validation to prevent bypassing filters with encoded attacks. -# Failure to canonicalize input is a very common mistake when implementing validation schemes. -# Canonicalization is automatic when using the ESAPI Validator, but you can also use the -# following code to canonicalize data. -# -# ESAPI.Encoder().canonicalize( "%22hello world"" ); -# -# Multiple encoding is when a single encoding format is applied multiple times. Allowing -# multiple encoding is strongly discouraged. -Encoder.AllowMultipleEncoding=false - -# Mixed encoding is when multiple different encoding formats are applied, or when -# multiple formats are nested. Allowing multiple encoding is strongly discouraged. -Encoder.AllowMixedEncoding=false - -# The default list of codecs to apply when canonicalizing untrusted data. The list should include the codecs -# for all downstream interpreters or decoders. For example, if the data is likely to end up in a URL, HTML, or -# inside JavaScript, then the list of codecs below is appropriate. The order of the list is not terribly important. -Encoder.DefaultCodecList=HTMLEntityCodec,PercentCodec,JavaScriptCodec - - -#=========================================================================== -# ESAPI Encryption -# -# The ESAPI Encryptor provides basic cryptographic functions with a simplified API. -# To get started, generate a new key using java -classpath esapi.jar org.owasp.esapi.reference.crypto.JavaEncryptor -# There is not currently any support for key rotation, so be careful when changing your key and salt as it -# will invalidate all signed, encrypted, and hashed data. -# -# WARNING: Not all combinations of algorithms and key lengths are supported. -# If you choose to use a key length greater than 128, you MUST download the -# unlimited strength policy files and install in the lib directory of your JRE/JDK. -# See http://java.sun.com/javase/downloads/index.jsp for more information. -# -# ***** IMPORTANT: Do NOT forget to replace these with your own values! ***** -# To calculate these values, you can run: -# java -classpath esapi.jar org.owasp.esapi.reference.crypto.JavaEncryptor -# -#Encryptor.MasterKey= -#Encryptor.MasterSalt= - -# Provides the default JCE provider that ESAPI will "prefer" for its symmetric -# encryption and hashing. (That is it will look to this provider first, but it -# will defer to other providers if the requested algorithm is not implemented -# by this provider.) If left unset, ESAPI will just use your Java VM's current -# preferred JCE provider, which is generally set in the file -# "$JAVA_HOME/jre/lib/security/java.security". -# -# The main intent of this is to allow ESAPI symmetric encryption to be -# used with a FIPS 140-2 compliant crypto-module. For details, see the section -# "Using ESAPI Symmetric Encryption with FIPS 140-2 Cryptographic Modules" in -# the ESAPI 2.0 Symmetric Encryption User Guide, at: -# http://owasp-esapi-java.googlecode.com/svn/trunk/documentation/esapi4java-core-2.0-symmetric-crypto-user-guide.html -# However, this property also allows you to easily use an alternate JCE provider -# such as "Bouncy Castle" without having to make changes to "java.security". -# See Javadoc for SecurityProviderLoader for further details. If you wish to use -# a provider that is not known to SecurityProviderLoader, you may specify the -# fully-qualified class name of the JCE provider class that implements -# java.security.Provider. If the name contains a '.', this is interpreted as -# a fully-qualified class name that implements java.security.Provider. -# -# NOTE: Setting this property has the side-effect of changing it in your application -# as well, so if you are using JCE in your application directly rather than -# through ESAPI (you wouldn't do that, would you? ;-), it will change the -# preferred JCE provider there as well. -# -# Default: Keeps the JCE provider set to whatever JVM sets it to. -Encryptor.PreferredJCEProvider= - -# AES is the most widely used and strongest encryption algorithm. This -# should agree with your Encryptor.CipherTransformation property. -# Warning: This property does not control the default reference implementation for -# ESAPI 2.0 using JavaEncryptor. Also, this property will be dropped -# in the future. -# @deprecated -Encryptor.EncryptionAlgorithm=AES -# For ESAPI Java 2.0 - New encrypt / decrypt methods use this. -Encryptor.CipherTransformation=AES/CBC/PKCS5Padding - -# Applies to ESAPI 2.0 and later only! -# Comma-separated list of cipher modes that provide *BOTH* -# confidentiality *AND* message authenticity. (NIST refers to such cipher -# modes as "combined modes" so that's what we shall call them.) If any of these -# cipher modes are used then no MAC is calculated and stored -# in the CipherText upon encryption. Likewise, if one of these -# cipher modes is used with decryption, no attempt will be made -# to validate the MAC contained in the CipherText object regardless -# of whether it contains one or not. Since the expectation is that -# these cipher modes support support message authenticity already, -# injecting a MAC in the CipherText object would be at best redundant. -# -# Note that as of JDK 1.5, the SunJCE provider does not support *any* -# of these cipher modes. Of these listed, only GCM and CCM are currently -# NIST approved. YMMV for other JCE providers. E.g., Bouncy Castle supports -# GCM and CCM with "NoPadding" mode, but not with "PKCS5Padding" or other -# padding modes. -Encryptor.cipher_modes.combined_modes=GCM,CCM,IAPM,EAX,OCB,CWC - -# Applies to ESAPI 2.0 and later only! -# Additional cipher modes allowed for ESAPI 2.0 encryption. These -# cipher modes are in _addition_ to those specified by the property -# 'Encryptor.cipher_modes.combined_modes'. -# Note: We will add support for streaming modes like CFB & OFB once -# we add support for 'specified' to the property 'Encryptor.ChooseIVMethod' -# (probably in ESAPI 2.1). -# DISCUSS: Better name? -Encryptor.cipher_modes.additional_allowed=CBC - -# Default key size to use for cipher specified by Encryptor.EncryptionAlgorithm. -# Note that this MUST be a valid key size for the algorithm being used -# (as specified by Encryptor.EncryptionAlgorithm). So for example, if AES is used, -# it must be 128, 192, or 256. If DESede is chosen, then it must be either 112 or 168. -# -# Note that 128-bits is almost always sufficient and for AES it appears to be more -# somewhat more resistant to related key attacks than is 256-bit AES.) -# -# Defaults to 128-bits if left blank. -# -# NOTE: If you use a key size > 128-bits, then you MUST have the JCE Unlimited -# Strength Jurisdiction Policy files installed!!! -# -Encryptor.EncryptionKeyLength=128 - -# This is the _minimum_ key size (in bits) that we allow with ANY symmetric -# cipher for doing encryption. (There is no minimum for decryption.) -# -# Generally, if you only use one algorithm, this should be set the same as -# the Encryptor.EncryptionKeyLength property. -Encryptor.MinEncryptionKeyLength=128 - -# Because 2.x uses CBC mode by default, it requires an initialization vector (IV). -# (All cipher modes except ECB require an IV.) There are two choices: we can either -# use a fixed IV known to both parties or allow ESAPI to choose a random IV. While -# the IV does not need to be hidden from adversaries, it is important that the -# adversary not be allowed to choose it. Also, random IVs are generally much more -# secure than fixed IVs. (In fact, it is essential that feed-back cipher modes -# such as CFB and OFB use a different IV for each encryption with a given key so -# in such cases, random IVs are much preferred. By default, ESAPI 2.0 uses random -# IVs. If you wish to use 'fixed' IVs, set 'Encryptor.ChooseIVMethod=fixed' and -# uncomment the Encryptor.fixedIV. -# -# Valid values: random|fixed|specified 'specified' not yet implemented; planned for 2.3 -# 'fixed' is deprecated as of 2.2 -# and will be removed in 2.3. -Encryptor.ChooseIVMethod=random - - -# If you choose to use a fixed IV, then you must place a fixed IV here that -# is known to all others who are sharing your secret key. The format should -# be a hex string that is the same length as the cipher block size for the -# cipher algorithm that you are using. The following is an *example* for AES -# from an AES test vector for AES-128/CBC as described in: -# NIST Special Publication 800-38A (2001 Edition) -# "Recommendation for Block Cipher Modes of Operation". -# (Note that the block size for AES is 16 bytes == 128 bits.) -# -# @Deprecated -- fixed IVs are deprecated as of the 2.2 release and support -# will be removed in the next release (tentatively, 2.3). -# If you MUST use this, at least replace this IV with one -# that your legacy application was using. -Encryptor.fixedIV=0x000102030405060708090a0b0c0d0e0f - -# Whether or not CipherText should use a message authentication code (MAC) with it. -# This prevents an adversary from altering the IV as well as allowing a more -# fool-proof way of determining the decryption failed because of an incorrect -# key being supplied. This refers to the "separate" MAC calculated and stored -# in CipherText, not part of any MAC that is calculated as a result of a -# "combined mode" cipher mode. -# -# If you are using ESAPI with a FIPS 140-2 cryptographic module, you *must* also -# set this property to false. That is because ESAPI takes the master key and -# derives 2 keys from it--a key for the MAC and a key for encryption--and -# because ESAPI is not itself FIPS 140-2 verified such intermediary aterations -# to keys from FIPS approved sources would have the effect of making your FIPS -# approved key generation and thus your FIPS approved JCE provider unapproved! -# More details in -# documentation/esapi4java-core-2.0-readme-crypto-changes.html -# documentation/esapi4java-core-2.0-symmetric-crypto-user-guide.html -# You have been warned. -Encryptor.CipherText.useMAC=true - -# Whether or not the PlainText object may be overwritten and then marked -# eligible for garbage collection. If not set, this is still treated as 'true'. -Encryptor.PlainText.overwrite=true - -# Do not use DES except in a legacy situations. 56-bit is way too small key size. -#Encryptor.EncryptionKeyLength=56 -#Encryptor.MinEncryptionKeyLength=56 -#Encryptor.EncryptionAlgorithm=DES - -# TripleDES is considered strong enough for most purposes. -# Note: There is also a 112-bit version of DESede. Using the 168-bit version -# requires downloading the special jurisdiction policy from Sun. -#Encryptor.EncryptionKeyLength=168 -#Encryptor.MinEncryptionKeyLength=112 -#Encryptor.EncryptionAlgorithm=DESede - -Encryptor.HashAlgorithm=SHA-512 -Encryptor.HashIterations=1024 -Encryptor.DigitalSignatureAlgorithm=SHA1withDSA -Encryptor.DigitalSignatureKeyLength=1024 -Encryptor.RandomAlgorithm=SHA1PRNG -Encryptor.CharacterEncoding=UTF-8 - -# This is the Pseudo Random Function (PRF) that ESAPI's Key Derivation Function -# (KDF) normally uses. Note this is *only* the PRF used for ESAPI's KDF and -# *not* what is used for ESAPI's MAC. (Currently, HmacSHA1 is always used for -# the MAC, mostly to keep the overall size at a minimum.) -# -# Currently supported choices for JDK 1.5 and 1.6 are: -# HmacSHA1 (160 bits), HmacSHA256 (256 bits), HmacSHA384 (384 bits), and -# HmacSHA512 (512 bits). -# Note that HmacMD5 is *not* supported for the PRF used by the KDF even though -# the JDKs support it. See the ESAPI 2.0 Symmetric Encryption User Guide -# further details. -Encryptor.KDF.PRF=HmacSHA256 -#=========================================================================== -# ESAPI HttpUtilties -# -# The HttpUtilities provide basic protections to HTTP requests and responses. Primarily these methods -# protect against malicious data from attackers, such as unprintable characters, escaped characters, -# and other simple attacks. The HttpUtilities also provides utility methods for dealing with cookies, -# headers, and CSRF tokens. -# -# Default file upload location (remember to escape backslashes with \\) -HttpUtilities.UploadDir=C:\\ESAPI\\testUpload -HttpUtilities.UploadTempDir=C:\\temp -# Force flags on cookies, if you use HttpUtilities to set cookies -HttpUtilities.ForceHttpOnlySession=false -HttpUtilities.ForceSecureSession=false -HttpUtilities.ForceHttpOnlyCookies=true -HttpUtilities.ForceSecureCookies=true -# Maximum size of HTTP header key--the validator regex may have additional values. -HttpUtilities.MaxHeaderNameSize=256 -# Maximum size of HTTP header value--the validator regex may have additional values. -HttpUtilities.MaxHeaderValueSize=4096 -# Maximum size of JSESSIONID for the application--the validator regex may have additional values. -HttpUtilities.HTTPJSESSIONIDLENGTH=50 -# Maximum length of a URL (see https://stackoverflow.com/questions/417142/what-is-the-maximum-length-of-a-url-in-different-browsers) -HttpUtilities.URILENGTH=2000 -# Maximum length of a redirect -HttpUtilities.maxRedirectLength=512 -# Maximum length for an http scheme -HttpUtilities.HTTPSCHEMELENGTH=10 -# Maximum length for an http host -HttpUtilities.HTTPHOSTLENGTH=100 -# Maximum length for an http path -HttpUtilities.HTTPPATHLENGTH=150 -#Maximum length for a context path -HttpUtilities.contextPathLength=150 -#Maximum length for an httpServletPath -HttpUtilities.HTTPSERVLETPATHLENGTH=100 -#Maximum length for an http query parameter name -HttpUtilities.httpQueryParamNameLength=100 -#Maximum length for an http query parameter -- old default was 2000, but that's the max length for a URL... -HttpUtilities.httpQueryParamValueLength=500 -# File upload configuration -HttpUtilities.ApprovedUploadExtensions=.pdf,.doc,.docx,.ppt,.pptx,.xls,.xlsx,.rtf,.txt,.jpg,.png -HttpUtilities.MaxUploadFileBytes=500000000 -# Using UTF-8 throughout your stack is highly recommended. That includes your database driver, -# container, and any other technologies you may be using. Failure to do this may expose you -# to Unicode transcoding injection attacks. Use of UTF-8 does not hinder internationalization. -HttpUtilities.ResponseContentType=text/html; charset=UTF-8 -# This is the name of the cookie used to represent the HTTP session -# Typically this will be the default "JSESSIONID" -HttpUtilities.HttpSessionIdName=JSESSIONID -#Sets whether or not we will overwrite http status codes to 200. -HttpUtilities.OverwriteStatusCodes=true -#Sets the application's base character encoding. This is forked from the Java Encryptor property. -HttpUtilities.CharacterEncoding=UTF-8 - -#=========================================================================== -# ESAPI Executor -# CHECKME - This should be made OS independent. Don't use unsafe defaults. -# # Examples only -- do NOT blindly copy! -# For Windows: -# Executor.WorkingDirectory=C:\\Windows\\Temp -# Executor.ApprovedExecutables=C:\\Windows\\System32\\cmd.exe,C:\\Windows\\System32\\runas.exe -# For *nux, MacOS: -# Executor.WorkingDirectory=/tmp -# Executor.ApprovedExecutables=/bin/bash -Executor.WorkingDirectory= -Executor.ApprovedExecutables= - - -#=========================================================================== -# ESAPI Logging -# Set the application name if these logs are combined with other applications -Logger.ApplicationName=ExampleApplication -# If you use an HTML log viewer that does not properly HTML escape log data, you can set LogEncodingRequired to true -Logger.LogEncodingRequired=false -# Determines whether ESAPI should log the application name. This might be clutter in some single-server/single-app environments. -Logger.LogApplicationName=true -# Determines whether ESAPI should log the server IP and port. This might be clutter in some single-server environments. -Logger.LogServerIP=true -# LogFileName, the name of the logging file. Provide a full directory path (e.g., C:\\ESAPI\\ESAPI_logging_file) if you -# want to place it in a specific directory. -Logger.LogFileName=ESAPI_logging_file -# MaxLogFileSize, the max size (in bytes) of a single log file before it cuts over to a new one (default is 10,000,000) -Logger.MaxLogFileSize=10000000 -# Determines whether ESAPI should log the user info. -Logger.UserInfo=true -# Determines whether ESAPI should log the session id and client IP. -Logger.ClientInfo=true - -#=========================================================================== -# ESAPI Intrusion Detection -# -# Each event has a base to which .count, .interval, and .action are added -# The IntrusionException will fire if we receive "count" events within "interval" seconds -# The IntrusionDetector is configurable to take the following actions: log, logout, and disable -# (multiple actions separated by commas are allowed e.g. event.test.actions=log,disable -# -# Custom Events -# Names must start with "event." as the base -# Use IntrusionDetector.addEvent( "test" ) in your code to trigger "event.test" here -# You can also disable intrusion detection completely by changing -# the following parameter to true -# -IntrusionDetector.Disable=false -# -IntrusionDetector.event.test.count=2 -IntrusionDetector.event.test.interval=10 -IntrusionDetector.event.test.actions=disable,log - -# Exception Events -# All EnterpriseSecurityExceptions are registered automatically -# Call IntrusionDetector.getInstance().addException(e) for Exceptions that do not extend EnterpriseSecurityException -# Use the fully qualified classname of the exception as the base - -# any intrusion is an attack -IntrusionDetector.org.owasp.esapi.errors.IntrusionException.count=1 -IntrusionDetector.org.owasp.esapi.errors.IntrusionException.interval=1 -IntrusionDetector.org.owasp.esapi.errors.IntrusionException.actions=log,disable,logout - -# for test purposes -# CHECKME: Shouldn't there be something in the property name itself that designates -# that these are for testing??? -IntrusionDetector.org.owasp.esapi.errors.IntegrityException.count=10 -IntrusionDetector.org.owasp.esapi.errors.IntegrityException.interval=5 -IntrusionDetector.org.owasp.esapi.errors.IntegrityException.actions=log,disable,logout - -# rapid validation errors indicate scans or attacks in progress -# org.owasp.esapi.errors.ValidationException.count=10 -# org.owasp.esapi.errors.ValidationException.interval=10 -# org.owasp.esapi.errors.ValidationException.actions=log,logout - -# sessions jumping between hosts indicates session hijacking -IntrusionDetector.org.owasp.esapi.errors.AuthenticationHostException.count=2 -IntrusionDetector.org.owasp.esapi.errors.AuthenticationHostException.interval=10 -IntrusionDetector.org.owasp.esapi.errors.AuthenticationHostException.actions=log,logout - - -#=========================================================================== -# ESAPI Validation -# -# The ESAPI Validator works on regular expressions with defined names. You can define names -# either here, or you may define application specific patterns in a separate file defined below. -# This allows enterprises to specify both organizational standards as well as application specific -# validation rules. -# -# Use '\p{L}' (without the quotes) within the character class to match -# any Unicode LETTER. You can also use a range, like: \u00C0-\u017F -# You can also use any of the regex flags as documented at -# https://docs.oracle.com/javase/tutorial/essential/regex/pattern.html, e.g. (?u) -# -Validator.ConfigurationFile=validation.properties - -# Validators used by ESAPI -Validator.AccountName=^[a-zA-Z0-9]{3,20}$ -Validator.SystemCommand=^[a-zA-Z\\-\\/]{1,64}$ -Validator.RoleName=^[a-z]{1,20}$ - -#the word TEST below should be changed to your application -#name - only relative URL's are supported -Validator.Redirect=^\\/test.*$ - -# Global HTTP Validation Rules -# Values with Base64 encoded data (e.g. encrypted state) will need at least [a-zA-Z0-9\/+=] -Validator.HTTPScheme=^(http|https)$ -Validator.HTTPServerName=^[a-zA-Z0-9_.\\-]*$ -Validator.HTTPCookieName=^[a-zA-Z0-9\\-_]{1,32}$ -Validator.HTTPCookieValue=^[a-zA-Z0-9\\-\\/+=_ ]*$ -# Note that headerName and Value length is also configured in the HTTPUtilities section -Validator.HTTPHeaderName=^[a-zA-Z0-9\\-_]{1,256}$ -Validator.HTTPHeaderValue=^[a-zA-Z0-9()\\-=\\*\\.\\?;,+\\/:&_ ]*$ -Validator.HTTPServletPath=^[a-zA-Z0-9.\\-\\/_]*$ -Validator.HTTPPath=^[a-zA-Z0-9.\\-_]*$ -Validator.HTTPURL=^.*$ -Validator.HTTPJSESSIONID=^[A-Z0-9]{10,32}$ - - -# Contributed by Fraenku@gmx.ch -# Github Issue 126 https://github.com/ESAPI/esapi-java-legacy/issues/126 -Validator.HTTPParameterName=^[a-zA-Z0-9_\\-]{1,32}$ -Validator.HTTPParameterValue=^[\\p{L}\\p{N}.\\-/+=_ !$*?@]{0,1000}$ -Validator.HTTPContextPath=^/[a-zA-Z0-9.\\-_]*$ -Validator.HTTPQueryString=^([a-zA-Z0-9_\\-]{1,32}=[\\p{L}\\p{N}.\\-/+=_ !$*?@%]*&?)*$ -Validator.HTTPURI=^/([a-zA-Z0-9.\\-_]*/?)*$ - - -# Validation of file related input -Validator.FileName=^[a-zA-Z0-9!@#$%^&{}\\[\\]()_+\\-=,.~'` ]{1,255}$ -Validator.DirectoryName=^[a-zA-Z0-9:/\\\\!@#$%^&{}\\[\\]()_+\\-=,.~'` ]{1,255}$ - -# Validation of dates. Controls whether or not 'lenient' dates are accepted. -# See DataFormat.setLenient(boolean flag) for further details. -Validator.AcceptLenientDates=false - -# ~~~~~ Important Note ~~~~~ -# This is a workaround to make sure that a commit to address GitHub issue #509 -# doesn't accidentally break someone's production code. So essentially what we -# are doing is to reverting back to the previous possibly buggy (by -# documentation intent at least), but, by now, expected legacy behavior. -# Prior to the code changes for issue #509, if invalid / malicious HTML input was -# observed, AntiSamy would simply attempt to sanitize (cleanse) it and it would -# only be logged. However, the code change made ESAPI comply with its -# documentation, which stated that a ValidationException should be thrown in -# such cases. Unfortunately, changing this behavior--especially when no one is -# 100% certain that the documentation was correct--could break existing code -# using ESAPI so after a lot of debate, issue #521 was created to restore the -# previous behavior, but still allow the documented behavior. (We did this -# because it wasn't really causing an security issues since AntiSamy would clean -# it up anyway and we value backward compatibility as long as it doesn't clearly -# present security vulnerabilities.) -# More defaults about this are written up under GitHub issue #521 and -# the pull request it references. Future major releases of ESAPI (e.g., ESAPI 3.x) -# will not support this previous behavior, but it will remain for ESAPI 2.x. -# Set this to 'throw' if you want the originally intended behavior of throwing -# that was fixed via issue #509. Set to 'clean' if you want want the HTML input -# sanitized instead. -# -# Possible values: -# clean -- Use the legacy behavior where unsafe HTML input is logged and the -# sanitized (i.e., clean) input as determined by AntiSamy and your -# AntiSamy rules is returned. This is the default behavior if this -# new property is not found. -# throw -- The new, presumably correct and originally intended behavior where -# a ValidationException is thrown when unsafe HTML input is -# encountered. -# -#Validator.HtmlValidationAction=clean -Validator.HtmlValidationAction=throw - -# With the fix for #310 to enable loading antisamy-esapi.xml from the classpath -# also an enhancement was made to be able to use a different filename for the configuration. -# You don't have to configure the filename here, but in that case the code will keep looking for antisamy-esapi.xml. -# This is the default behaviour of ESAPI. -# -#Validator.HtmlValidationConfigurationFile=antisamy-esapi.xml \ No newline at end of file diff --git a/spring-security-modules/spring-5-security/src/main/resources/application.properties b/spring-security-modules/spring-5-security/src/main/resources/application.properties deleted file mode 100644 index 8159ace060..0000000000 --- a/spring-security-modules/spring-5-security/src/main/resources/application.properties +++ /dev/null @@ -1,7 +0,0 @@ -server.port=8081 - -logging.level.root=INFO - -logging.level.com.baeldung.dsl.ClientErrorLoggingFilter=DEBUG - -logging.level.org.springframework.security=DEBUG \ No newline at end of file diff --git a/spring-security-modules/spring-5-security/src/main/resources/logback.xml b/spring-security-modules/spring-5-security/src/main/resources/logback.xml deleted file mode 100644 index 7d900d8ea8..0000000000 --- a/spring-security-modules/spring-5-security/src/main/resources/logback.xml +++ /dev/null @@ -1,13 +0,0 @@ - - - - - %d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n - - - - - - - - \ No newline at end of file diff --git a/spring-security-modules/spring-5-security/src/main/resources/templates/index.html b/spring-security-modules/spring-5-security/src/main/resources/templates/index.html deleted file mode 100644 index 4216d74037..0000000000 --- a/spring-security-modules/spring-5-security/src/main/resources/templates/index.html +++ /dev/null @@ -1,11 +0,0 @@ - - - - Home - - - - Home - Welcome! - - \ No newline at end of file diff --git a/spring-security-modules/spring-5-security/src/test/java/com/baeldung/SpringContextTest.java b/spring-security-modules/spring-5-security/src/test/java/com/baeldung/SpringContextTest.java deleted file mode 100644 index 7812a5c063..0000000000 --- a/spring-security-modules/spring-5-security/src/test/java/com/baeldung/SpringContextTest.java +++ /dev/null @@ -1,17 +0,0 @@ -package com.baeldung; - -import org.junit.Test; -import org.junit.runner.RunWith; -import org.springframework.boot.test.context.SpringBootTest; -import org.springframework.test.context.junit4.SpringRunner; - -import com.baeldung.dsl.CustomConfigurerApplication; - -@RunWith(SpringRunner.class) -@SpringBootTest(classes = CustomConfigurerApplication.class) -public class SpringContextTest { - - @Test - public void whenSpringContextIsBootstrapped_thenNoExceptions() { - } -} diff --git a/spring-security-modules/spring-5-security/src/test/java/com/baeldung/authresolver/AuthResolverIntegrationTest.java b/spring-security-modules/spring-5-security/src/test/java/com/baeldung/authresolver/AuthResolverIntegrationTest.java deleted file mode 100644 index c87f8c1a3a..0000000000 --- a/spring-security-modules/spring-5-security/src/test/java/com/baeldung/authresolver/AuthResolverIntegrationTest.java +++ /dev/null @@ -1,82 +0,0 @@ -package com.baeldung.authresolver; - -import org.junit.Before; -import org.junit.FixMethodOrder; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.junit.runners.MethodSorters; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.boot.test.context.SpringBootTest; -import org.springframework.security.web.FilterChainProxy; -import org.springframework.test.context.junit4.SpringRunner; -import org.springframework.test.web.servlet.MockMvc; -import org.springframework.test.web.servlet.setup.MockMvcBuilders; -import org.springframework.util.Base64Utils; -import org.springframework.web.context.WebApplicationContext; - -import static org.springframework.security.test.web.servlet.setup.SecurityMockMvcConfigurers.springSecurity; -import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; -import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; - -@RunWith(SpringRunner.class) -@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT, classes = AuthResolverApplication.class) -@FixMethodOrder(MethodSorters.NAME_ASCENDING) -public class AuthResolverIntegrationTest { - - @Autowired - private FilterChainProxy springSecurityFilterChain; - - @Autowired - private WebApplicationContext wac; - - private MockMvc mockMvc; - - @Before - public void setup() { - this.mockMvc = MockMvcBuilders - .webAppContextSetup(wac) - .apply(springSecurity(springSecurityFilterChain)) - .build(); - } - - @Test - public void givenCustomerCredential_whenWelcomeCustomer_thenExpectOk() throws Exception { - this.mockMvc - .perform(get("/customer/welcome") - .header( - "Authorization", String.format("Basic %s", Base64Utils.encodeToString("customer1:pass1".getBytes())) - ) - ) - .andExpect(status().is2xxSuccessful()); - } - - @Test - public void givenEmployeeCredential_whenWelcomeCustomer_thenExpect401Status() throws Exception { - this.mockMvc - .perform(get("/customer/welcome") - .header( - "Authorization", "Basic " + Base64Utils.encodeToString("employee1:pass1".getBytes())) - ) - .andExpect(status().isUnauthorized()); - } - - @Test - public void givenEmployeeCredential_whenWelcomeEmployee_thenExpectOk() throws Exception { - this.mockMvc - .perform(get("/employee/welcome") - .header( - "Authorization", "Basic " + Base64Utils.encodeToString("employee1:pass1".getBytes())) - ) - .andExpect(status().is2xxSuccessful()); - } - - @Test - public void givenCustomerCredential_whenWelcomeEmployee_thenExpect401Status() throws Exception { - this.mockMvc - .perform(get("/employee/welcome") - .header( - "Authorization", "Basic " + Base64Utils.encodeToString("customer1:pass1".getBytes())) - ) - .andExpect(status().isUnauthorized()); - } -} diff --git a/spring-security-modules/spring-5-security/src/test/java/com/baeldung/inmemory/InMemoryAuthControllerIntegrationTest.java b/spring-security-modules/spring-5-security/src/test/java/com/baeldung/inmemory/InMemoryAuthControllerIntegrationTest.java deleted file mode 100644 index 9d08cb7cfa..0000000000 --- a/spring-security-modules/spring-5-security/src/test/java/com/baeldung/inmemory/InMemoryAuthControllerIntegrationTest.java +++ /dev/null @@ -1,48 +0,0 @@ -package com.baeldung.inmemory; - -import static org.junit.Assert.assertEquals; - -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.context.SpringBootTest.WebEnvironment; -import org.springframework.boot.test.web.client.TestRestTemplate; -import org.springframework.http.HttpStatus; -import org.springframework.http.ResponseEntity; -import org.springframework.test.context.junit4.SpringRunner; - -@RunWith(SpringRunner.class) -@SpringBootTest(classes = InMemoryAuthApplication.class, webEnvironment = WebEnvironment.RANDOM_PORT) -public class InMemoryAuthControllerIntegrationTest { - - @Autowired - private TestRestTemplate template; - - @Test - public void givenRequestOnPublicService_shouldSucceedWith200() throws Exception { - ResponseEntity result = template.getForEntity("/public/hello", String.class); - assertEquals(HttpStatus.OK, result.getStatusCode()); - } - - @Test - public void givenRequestOnPrivateService_shouldFailWith401() throws Exception { - ResponseEntity result = template.getForEntity("/private/hello", String.class); - assertEquals(HttpStatus.UNAUTHORIZED, result.getStatusCode()); - } - - @Test - public void givenAuthRequestOnPrivateService_shouldSucceedWith200() throws Exception { - ResponseEntity result = template.withBasicAuth("spring", "secret") - .getForEntity("/private/hello", String.class); - assertEquals(HttpStatus.OK, result.getStatusCode()); - } - - @Test - public void givenInvalidAuthRequestOnPrivateService_shouldSucceedWith200() throws Exception { - ResponseEntity result = template.withBasicAuth("spring", "wrong") - .getForEntity("/private/hello", String.class); - assertEquals(HttpStatus.UNAUTHORIZED, result.getStatusCode()); - } - -} diff --git a/spring-security-modules/spring-5-security/src/test/java/com/baeldung/logoutredirects/LogoutApplicationUnitTest.java b/spring-security-modules/spring-5-security/src/test/java/com/baeldung/logoutredirects/LogoutApplicationUnitTest.java deleted file mode 100644 index 519a6bdc99..0000000000 --- a/spring-security-modules/spring-5-security/src/test/java/com/baeldung/logoutredirects/LogoutApplicationUnitTest.java +++ /dev/null @@ -1,34 +0,0 @@ -package com.baeldung.logoutredirects; - -import org.junit.Test; -import org.junit.runner.RunWith; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.boot.test.autoconfigure.web.servlet.WebMvcTest; -import org.springframework.security.test.context.support.WithMockUser; -import org.springframework.test.context.junit4.SpringRunner; -import org.springframework.test.web.servlet.MockMvc; - -import static org.springframework.security.test.web.servlet.request.SecurityMockMvcRequestPostProcessors.csrf; -import static org.springframework.security.test.web.servlet.response.SecurityMockMvcResultMatchers.unauthenticated; -import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post; -import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.*; - -@RunWith(SpringRunner.class) -@WebMvcTest() -public class LogoutApplicationUnitTest { - - @Autowired - private MockMvc mockMvc; - - @WithMockUser(value = "spring") - @Test - public void whenLogout_thenDisableRedirect() throws Exception { - - this.mockMvc.perform(post("/logout").with(csrf())) - .andExpect(status().isOk()) - .andExpect(jsonPath("$").doesNotExist()) - .andExpect(unauthenticated()) - .andReturn(); - } - -} \ No newline at end of file diff --git a/spring-security-modules/spring-5-security/src/test/java/com/baeldung/manuallogout/ManualLogoutIntegrationTest.java b/spring-security-modules/spring-5-security/src/test/java/com/baeldung/manuallogout/ManualLogoutIntegrationTest.java deleted file mode 100644 index 06dc01e116..0000000000 --- a/spring-security-modules/spring-5-security/src/test/java/com/baeldung/manuallogout/ManualLogoutIntegrationTest.java +++ /dev/null @@ -1,96 +0,0 @@ -package com.baeldung.manuallogout; - -import static org.junit.Assert.assertNull; -import static org.springframework.security.test.web.servlet.request.SecurityMockMvcRequestPostProcessors.csrf; -import static org.springframework.security.test.web.servlet.response.SecurityMockMvcResultMatchers.unauthenticated; -import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post; -import static org.springframework.test.web.servlet.result.MockMvcResultHandlers.print; -import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.cookie; -import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.header; -import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; - -import javax.servlet.http.Cookie; -import javax.servlet.http.HttpSession; - -import org.junit.Test; -import org.junit.runner.RunWith; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.boot.test.autoconfigure.web.servlet.WebMvcTest; -import org.springframework.mock.web.MockHttpServletRequest; -import org.springframework.mock.web.MockHttpSession; -import org.springframework.security.test.context.support.WithMockUser; -import org.springframework.test.context.junit4.SpringRunner; -import org.springframework.test.web.servlet.MockMvc; - -@RunWith(SpringRunner.class) -@WebMvcTest() -public class ManualLogoutIntegrationTest { - - private static final String CLEAR_SITE_DATA_HEADER = "Clear-Site-Data"; - public static final int EXPIRY = 60 * 10; - public static final String COOKIE_NAME = "customerName"; - public static final String COOKIE_VALUE = "myName"; - public static final String ATTRIBUTE_NAME = "att"; - public static final String ATTRIBUTE_VALUE = "attvalue"; - - @Autowired - private MockMvc mockMvc; - - @WithMockUser(value = "spring") - @Test - public void givenLoggedUserWhenUserLogoutThenSessionClearedAndNecessaryCookieCleared() throws Exception { - - this.mockMvc.perform(post("/basic/basiclogout").secure(true) - .with(csrf())) - .andExpect(status().is3xxRedirection()) - .andExpect(unauthenticated()) - .andReturn(); - } - - @WithMockUser(value = "spring") - @Test - public void givenLoggedUserWhenUserLogoutThenSessionClearedAndAllCookiesCleared() throws Exception { - - MockHttpSession session = new MockHttpSession(); - session.setAttribute(ATTRIBUTE_NAME, ATTRIBUTE_VALUE); - - Cookie randomCookie = new Cookie(COOKIE_NAME, COOKIE_VALUE); - randomCookie.setMaxAge(EXPIRY); // 10 minutes - - MockHttpServletRequest requestStateAfterLogout = this.mockMvc.perform(post("/cookies/cookielogout").secure(true) - .with(csrf()) - .session(session) - .cookie(randomCookie)) - .andExpect(status().is3xxRedirection()) - .andExpect(unauthenticated()) - .andExpect(cookie().maxAge(COOKIE_NAME, 0)) - .andReturn() - .getRequest(); - - HttpSession sessionStateAfterLogout = requestStateAfterLogout.getSession(); - assertNull(sessionStateAfterLogout.getAttribute(ATTRIBUTE_NAME)); - } - - @WithMockUser(value = "spring") - @Test - public void givenLoggedUserWhenUserLogoutThenClearDataSiteHeaderPresent() throws Exception { - - this.mockMvc.perform(post("/csd/csdlogout").secure(true) - .with(csrf())) - .andDo(print()) - .andExpect(status().is3xxRedirection()) - .andExpect(header().exists(CLEAR_SITE_DATA_HEADER)) - .andReturn(); - } - - @WithMockUser(value = "spring") - @Test - public void givenLoggedUserWhenUserLogoutOnRequestThenSessionCleared() throws Exception { - - this.mockMvc.perform(post("/request/logout").secure(true) - .with(csrf())) - .andExpect(status().is3xxRedirection()) - .andExpect(unauthenticated()) - .andReturn(); - } -} \ No newline at end of file diff --git a/spring-security-modules/spring-5-security/src/test/resources/logback-test.xml b/spring-security-modules/spring-5-security/src/test/resources/logback-test.xml deleted file mode 100644 index 8d4771e308..0000000000 --- a/spring-security-modules/spring-5-security/src/test/resources/logback-test.xml +++ /dev/null @@ -1,12 +0,0 @@ - - - - - [%d{ISO8601}]-[%thread] %-5level %logger - %msg%n - - - - - - - \ No newline at end of file From b7033fadfd03d06d6dc8fdc0d5fe06a0a9025956 Mon Sep 17 00:00:00 2001 From: sampadawagde Date: Mon, 18 Jul 2022 20:21:49 +0530 Subject: [PATCH 12/16] JAVA-12754: Moved 3 articles to spring-security-core-2 --- .../spring-security-core-2/README.md | 3 + .../authresolver/AuthResolverApplication.java | 11 +++ .../authresolver/AuthResolverController.java | 18 ++++ .../CustomWebSecurityConfigurer.java | 96 +++++++++++++++++++ .../dsl/ClientErrorLoggingConfigurer.java | 32 +++++++ .../dsl/ClientErrorLoggingFilter.java | 57 +++++++++++ .../dsl/CustomConfigurerApplication.java | 13 +++ .../java/com/baeldung/dsl/MyController.java | 14 +++ .../java/com/baeldung/dsl/SecurityConfig.java | 50 ++++++++++ .../java/com/baeldung/xss/Application.java | 14 +++ .../java/com/baeldung/xss/SecurityConf.java | 25 +++++ .../java/com/baeldung/SpringContextTest.java | 18 ++++ .../AuthResolverIntegrationTest.java | 82 ++++++++++++++++ 13 files changed, 433 insertions(+) create mode 100644 spring-security-modules/spring-security-core-2/src/main/java/com/baeldung/authresolver/AuthResolverApplication.java create mode 100644 spring-security-modules/spring-security-core-2/src/main/java/com/baeldung/authresolver/AuthResolverController.java create mode 100644 spring-security-modules/spring-security-core-2/src/main/java/com/baeldung/authresolver/CustomWebSecurityConfigurer.java create mode 100644 spring-security-modules/spring-security-core-2/src/main/java/com/baeldung/dsl/ClientErrorLoggingConfigurer.java create mode 100644 spring-security-modules/spring-security-core-2/src/main/java/com/baeldung/dsl/ClientErrorLoggingFilter.java create mode 100644 spring-security-modules/spring-security-core-2/src/main/java/com/baeldung/dsl/CustomConfigurerApplication.java create mode 100644 spring-security-modules/spring-security-core-2/src/main/java/com/baeldung/dsl/MyController.java create mode 100644 spring-security-modules/spring-security-core-2/src/main/java/com/baeldung/dsl/SecurityConfig.java create mode 100644 spring-security-modules/spring-security-core-2/src/main/java/com/baeldung/xss/Application.java create mode 100644 spring-security-modules/spring-security-core-2/src/main/java/com/baeldung/xss/SecurityConf.java create mode 100644 spring-security-modules/spring-security-core-2/src/test/java/com/baeldung/SpringContextTest.java create mode 100644 spring-security-modules/spring-security-core-2/src/test/java/com/baeldung/authresolver/AuthResolverIntegrationTest.java diff --git a/spring-security-modules/spring-security-core-2/README.md b/spring-security-modules/spring-security-core-2/README.md index bf70693eb5..8fc705a949 100644 --- a/spring-security-modules/spring-security-core-2/README.md +++ b/spring-security-modules/spring-security-core-2/README.md @@ -5,6 +5,9 @@ This module contains articles about core Spring Security ### Relevant Articles: - [Handle Spring Security Exceptions](https://www.baeldung.com/spring-security-exceptions) - [Handle Spring Security Exceptions With @ExceptionHandler](https://www.baeldung.com/spring-security-exceptionhandler) +- [Prevent Cross-Site Scripting (XSS) in a Spring Application](https://www.baeldung.com/spring-prevent-xss) +- [Guide to the AuthenticationManagerResolver in Spring Security](https://www.baeldung.com/spring-security-authenticationmanagerresolver) +- [A Custom Spring SecurityConfigurer|https://www.baeldung.com/spring-security-custom-configurer] ### Build the Project diff --git a/spring-security-modules/spring-security-core-2/src/main/java/com/baeldung/authresolver/AuthResolverApplication.java b/spring-security-modules/spring-security-core-2/src/main/java/com/baeldung/authresolver/AuthResolverApplication.java new file mode 100644 index 0000000000..96ee674b15 --- /dev/null +++ b/spring-security-modules/spring-security-core-2/src/main/java/com/baeldung/authresolver/AuthResolverApplication.java @@ -0,0 +1,11 @@ +package com.baeldung.authresolver; + +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; + +@SpringBootApplication +public class AuthResolverApplication { + public static void main(String[] args) { + SpringApplication.run(AuthResolverApplication.class, args); + } +} diff --git a/spring-security-modules/spring-security-core-2/src/main/java/com/baeldung/authresolver/AuthResolverController.java b/spring-security-modules/spring-security-core-2/src/main/java/com/baeldung/authresolver/AuthResolverController.java new file mode 100644 index 0000000000..7dc6900b5a --- /dev/null +++ b/spring-security-modules/spring-security-core-2/src/main/java/com/baeldung/authresolver/AuthResolverController.java @@ -0,0 +1,18 @@ +package com.baeldung.authresolver; + +import org.springframework.security.core.Authentication; +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.RestController; + +@RestController +public class AuthResolverController { + @GetMapping("/customer/welcome") + public String sayWelcomeToCustomer(Authentication authentication) { + return String.format("Welcome to our site, %s!", authentication.getPrincipal()); + } + + @GetMapping("/employee/welcome") + public String sayWelcomeToEmployee(Authentication authentication) { + return String.format("Welcome to our company, %s!", authentication.getPrincipal()); + } +} diff --git a/spring-security-modules/spring-security-core-2/src/main/java/com/baeldung/authresolver/CustomWebSecurityConfigurer.java b/spring-security-modules/spring-security-core-2/src/main/java/com/baeldung/authresolver/CustomWebSecurityConfigurer.java new file mode 100644 index 0000000000..33ef692173 --- /dev/null +++ b/spring-security-modules/spring-security-core-2/src/main/java/com/baeldung/authresolver/CustomWebSecurityConfigurer.java @@ -0,0 +1,96 @@ +package com.baeldung.authresolver; + +import java.util.Collections; +import javax.servlet.http.HttpServletRequest; +import org.springframework.context.annotation.Configuration; +import org.springframework.security.authentication.AuthenticationManager; +import org.springframework.security.authentication.AuthenticationManagerResolver; +import org.springframework.security.authentication.UsernamePasswordAuthenticationToken; +import org.springframework.security.config.annotation.web.builders.HttpSecurity; +import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter; +import org.springframework.security.core.Authentication; +import org.springframework.security.core.authority.SimpleGrantedAuthority; +import org.springframework.security.core.userdetails.UsernameNotFoundException; +import org.springframework.security.web.authentication.AuthenticationConverter; +import org.springframework.security.web.authentication.AuthenticationFilter; +import org.springframework.security.web.authentication.www.BasicAuthenticationConverter; +import org.springframework.security.web.authentication.www.BasicAuthenticationFilter; + +@Configuration +public class CustomWebSecurityConfigurer extends WebSecurityConfigurerAdapter { + + public AuthenticationConverter authenticationConverter() { + return new BasicAuthenticationConverter(); + } + + public AuthenticationManagerResolver resolver() { + return request -> { + if (request + .getPathInfo() + .startsWith("/employee")) { + return employeesAuthenticationManager(); + } + return customersAuthenticationManager(); + }; + } + + public AuthenticationManager customersAuthenticationManager() { + return authentication -> { + if (isCustomer(authentication)) { + return new UsernamePasswordAuthenticationToken( + authentication.getPrincipal(), + authentication.getCredentials(), + Collections.singletonList(new SimpleGrantedAuthority("ROLE_USER")) + ); + } + throw new UsernameNotFoundException(authentication + .getPrincipal() + .toString()); + }; + } + + private boolean isCustomer(Authentication authentication) { + return (authentication + .getPrincipal() + .toString() + .startsWith("customer")); + } + + private boolean isEmployee(Authentication authentication) { + return (authentication + .getPrincipal() + .toString() + .startsWith("employee")); + } + + private AuthenticationFilter authenticationFilter() { + AuthenticationFilter filter = new AuthenticationFilter( + resolver(), authenticationConverter()); + filter.setSuccessHandler((request, response, auth) -> {}); + return filter; + } + + private AuthenticationManager employeesAuthenticationManager() { + return authentication -> { + if (isEmployee(authentication)) { + return new UsernamePasswordAuthenticationToken( + authentication.getPrincipal(), + authentication.getCredentials(), + Collections.singletonList(new SimpleGrantedAuthority("ROLE_USER")) + ); + } + throw new UsernameNotFoundException(authentication + .getPrincipal() + .toString()); + }; + } + + @Override + protected void configure(HttpSecurity http) { + http.addFilterBefore( + authenticationFilter(), + BasicAuthenticationFilter.class + ); + } + +} diff --git a/spring-security-modules/spring-security-core-2/src/main/java/com/baeldung/dsl/ClientErrorLoggingConfigurer.java b/spring-security-modules/spring-security-core-2/src/main/java/com/baeldung/dsl/ClientErrorLoggingConfigurer.java new file mode 100644 index 0000000000..5a9479b664 --- /dev/null +++ b/spring-security-modules/spring-security-core-2/src/main/java/com/baeldung/dsl/ClientErrorLoggingConfigurer.java @@ -0,0 +1,32 @@ +package com.baeldung.dsl; + +import java.util.List; + +import org.springframework.http.HttpStatus; +import org.springframework.security.config.annotation.web.builders.HttpSecurity; +import org.springframework.security.config.annotation.web.configurers.AbstractHttpConfigurer; +import org.springframework.security.web.access.intercept.FilterSecurityInterceptor; + +public class ClientErrorLoggingConfigurer extends AbstractHttpConfigurer { + + private List errorCodes; + + public ClientErrorLoggingConfigurer(List errorCodes) { + this.errorCodes = errorCodes; + } + + public ClientErrorLoggingConfigurer() { + + } + + @Override + public void init(HttpSecurity http) throws Exception { + // initialization code + } + + @Override + public void configure(HttpSecurity http) throws Exception { + http.addFilterAfter(new ClientErrorLoggingFilter(errorCodes), FilterSecurityInterceptor.class); + } + +} diff --git a/spring-security-modules/spring-security-core-2/src/main/java/com/baeldung/dsl/ClientErrorLoggingFilter.java b/spring-security-modules/spring-security-core-2/src/main/java/com/baeldung/dsl/ClientErrorLoggingFilter.java new file mode 100644 index 0000000000..cb174cad28 --- /dev/null +++ b/spring-security-modules/spring-security-core-2/src/main/java/com/baeldung/dsl/ClientErrorLoggingFilter.java @@ -0,0 +1,57 @@ +package com.baeldung.dsl; + +import java.io.IOException; +import java.util.List; + +import javax.servlet.FilterChain; +import javax.servlet.ServletException; +import javax.servlet.ServletRequest; +import javax.servlet.ServletResponse; +import javax.servlet.http.HttpServletResponse; + +import org.apache.logging.log4j.LogManager; +import org.apache.logging.log4j.Logger; +import org.springframework.http.HttpStatus; +import org.springframework.security.core.Authentication; +import org.springframework.security.core.context.SecurityContextHolder; +import org.springframework.web.filter.GenericFilterBean; + +public class ClientErrorLoggingFilter extends GenericFilterBean { + + private static final Logger logger = LogManager.getLogger(ClientErrorLoggingFilter.class); + + private List errorCodes; + + public ClientErrorLoggingFilter(List errorCodes) { + this.errorCodes = errorCodes; + } + + @Override + public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { + + Authentication auth = SecurityContextHolder.getContext() + .getAuthentication(); + + if (auth == null) { + chain.doFilter(request, response); + return; + } + int status = ((HttpServletResponse) response).getStatus(); + if (status < 400 || status >= 500) { + chain.doFilter(request, response); + return; + } + + if (errorCodes == null) { + logger.debug("User " + auth.getName() + " encountered error " + status); + } else { + if (errorCodes.stream() + .anyMatch(s -> s.value() == status)) { + logger.debug("User " + auth.getName() + " encountered error " + status); + } + } + + chain.doFilter(request, response); + } + +} diff --git a/spring-security-modules/spring-security-core-2/src/main/java/com/baeldung/dsl/CustomConfigurerApplication.java b/spring-security-modules/spring-security-core-2/src/main/java/com/baeldung/dsl/CustomConfigurerApplication.java new file mode 100644 index 0000000000..2cd3d7fc7f --- /dev/null +++ b/spring-security-modules/spring-security-core-2/src/main/java/com/baeldung/dsl/CustomConfigurerApplication.java @@ -0,0 +1,13 @@ +package com.baeldung.dsl; + +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; + +@SpringBootApplication +public class CustomConfigurerApplication { + + public static void main(String[] args) { + SpringApplication.run(CustomConfigurerApplication.class, args); + } + +} diff --git a/spring-security-modules/spring-security-core-2/src/main/java/com/baeldung/dsl/MyController.java b/spring-security-modules/spring-security-core-2/src/main/java/com/baeldung/dsl/MyController.java new file mode 100644 index 0000000000..c69046afb5 --- /dev/null +++ b/spring-security-modules/spring-security-core-2/src/main/java/com/baeldung/dsl/MyController.java @@ -0,0 +1,14 @@ +package com.baeldung.dsl; + +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.RestController; + +@RestController +public class MyController { + + @GetMapping("/admin") + public String getAdminPage() { + return "Hello Admin"; + } + +} diff --git a/spring-security-modules/spring-security-core-2/src/main/java/com/baeldung/dsl/SecurityConfig.java b/spring-security-modules/spring-security-core-2/src/main/java/com/baeldung/dsl/SecurityConfig.java new file mode 100644 index 0000000000..382e222f64 --- /dev/null +++ b/spring-security-modules/spring-security-core-2/src/main/java/com/baeldung/dsl/SecurityConfig.java @@ -0,0 +1,50 @@ +package com.baeldung.dsl; + +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; +import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder; +import org.springframework.security.config.annotation.web.builders.HttpSecurity; +import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter; +import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder; +import org.springframework.security.crypto.password.PasswordEncoder; + +@Configuration +public class SecurityConfig extends WebSecurityConfigurerAdapter { + + @Override + protected void configure(HttpSecurity http) throws Exception { + http.authorizeRequests() + .antMatchers("/admin*") + .hasAnyRole("ADMIN") + .anyRequest() + .authenticated() + .and() + .formLogin() + .and() + .apply(clientErrorLogging()); + } + + @Bean + public ClientErrorLoggingConfigurer clientErrorLogging() { + return new ClientErrorLoggingConfigurer(); + } + + @Override + protected void configure(AuthenticationManagerBuilder auth) throws Exception { + auth.inMemoryAuthentication() + .passwordEncoder(passwordEncoder()) + .withUser("user1") + .password(passwordEncoder().encode("user")) + .roles("USER") + .and() + .withUser("admin") + .password(passwordEncoder().encode("admin")) + .roles("ADMIN"); + } + + @Bean + public PasswordEncoder passwordEncoder() { + return new BCryptPasswordEncoder(); + } + +} diff --git a/spring-security-modules/spring-security-core-2/src/main/java/com/baeldung/xss/Application.java b/spring-security-modules/spring-security-core-2/src/main/java/com/baeldung/xss/Application.java new file mode 100644 index 0000000000..b463a7adc3 --- /dev/null +++ b/spring-security-modules/spring-security-core-2/src/main/java/com/baeldung/xss/Application.java @@ -0,0 +1,14 @@ +package com.baeldung.xss; + +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; +import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity; + +@SpringBootApplication +@EnableWebSecurity +public class Application { + + public static void main(String[] args) { + SpringApplication.run(Application.class, args); + } +} diff --git a/spring-security-modules/spring-security-core-2/src/main/java/com/baeldung/xss/SecurityConf.java b/spring-security-modules/spring-security-core-2/src/main/java/com/baeldung/xss/SecurityConf.java new file mode 100644 index 0000000000..25d8026e4a --- /dev/null +++ b/spring-security-modules/spring-security-core-2/src/main/java/com/baeldung/xss/SecurityConf.java @@ -0,0 +1,25 @@ +package com.baeldung.xss; + +import org.springframework.context.annotation.Configuration; +import org.springframework.security.config.annotation.web.builders.HttpSecurity; +import org.springframework.security.config.annotation.web.builders.WebSecurity; +import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter; + +@Configuration +public class SecurityConf extends WebSecurityConfigurerAdapter { + + @Override + public void configure(WebSecurity web) { + // Ignoring here is only for this example. Normally people would apply their own authentication/authorization policies + web.ignoring().antMatchers("/**"); + } + + @Override + protected void configure(HttpSecurity http) throws Exception { + http + .headers() + .xssProtection() + .and() + .contentSecurityPolicy("script-src 'self'"); + } +} diff --git a/spring-security-modules/spring-security-core-2/src/test/java/com/baeldung/SpringContextTest.java b/spring-security-modules/spring-security-core-2/src/test/java/com/baeldung/SpringContextTest.java new file mode 100644 index 0000000000..dc1dbf34f3 --- /dev/null +++ b/spring-security-modules/spring-security-core-2/src/test/java/com/baeldung/SpringContextTest.java @@ -0,0 +1,18 @@ +package com.baeldung; + + +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.test.context.junit4.SpringRunner; + +import com.baeldung.dsl.CustomConfigurerApplication; + +@RunWith(SpringRunner.class) +@SpringBootTest(classes = CustomConfigurerApplication.class) +public class SpringContextTest { + + @Test + public void whenSpringContextIsBootstrapped_thenNoExceptions() { + } +} diff --git a/spring-security-modules/spring-security-core-2/src/test/java/com/baeldung/authresolver/AuthResolverIntegrationTest.java b/spring-security-modules/spring-security-core-2/src/test/java/com/baeldung/authresolver/AuthResolverIntegrationTest.java new file mode 100644 index 0000000000..c87f8c1a3a --- /dev/null +++ b/spring-security-modules/spring-security-core-2/src/test/java/com/baeldung/authresolver/AuthResolverIntegrationTest.java @@ -0,0 +1,82 @@ +package com.baeldung.authresolver; + +import org.junit.Before; +import org.junit.FixMethodOrder; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.junit.runners.MethodSorters; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.security.web.FilterChainProxy; +import org.springframework.test.context.junit4.SpringRunner; +import org.springframework.test.web.servlet.MockMvc; +import org.springframework.test.web.servlet.setup.MockMvcBuilders; +import org.springframework.util.Base64Utils; +import org.springframework.web.context.WebApplicationContext; + +import static org.springframework.security.test.web.servlet.setup.SecurityMockMvcConfigurers.springSecurity; +import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; + +@RunWith(SpringRunner.class) +@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT, classes = AuthResolverApplication.class) +@FixMethodOrder(MethodSorters.NAME_ASCENDING) +public class AuthResolverIntegrationTest { + + @Autowired + private FilterChainProxy springSecurityFilterChain; + + @Autowired + private WebApplicationContext wac; + + private MockMvc mockMvc; + + @Before + public void setup() { + this.mockMvc = MockMvcBuilders + .webAppContextSetup(wac) + .apply(springSecurity(springSecurityFilterChain)) + .build(); + } + + @Test + public void givenCustomerCredential_whenWelcomeCustomer_thenExpectOk() throws Exception { + this.mockMvc + .perform(get("/customer/welcome") + .header( + "Authorization", String.format("Basic %s", Base64Utils.encodeToString("customer1:pass1".getBytes())) + ) + ) + .andExpect(status().is2xxSuccessful()); + } + + @Test + public void givenEmployeeCredential_whenWelcomeCustomer_thenExpect401Status() throws Exception { + this.mockMvc + .perform(get("/customer/welcome") + .header( + "Authorization", "Basic " + Base64Utils.encodeToString("employee1:pass1".getBytes())) + ) + .andExpect(status().isUnauthorized()); + } + + @Test + public void givenEmployeeCredential_whenWelcomeEmployee_thenExpectOk() throws Exception { + this.mockMvc + .perform(get("/employee/welcome") + .header( + "Authorization", "Basic " + Base64Utils.encodeToString("employee1:pass1".getBytes())) + ) + .andExpect(status().is2xxSuccessful()); + } + + @Test + public void givenCustomerCredential_whenWelcomeEmployee_thenExpect401Status() throws Exception { + this.mockMvc + .perform(get("/employee/welcome") + .header( + "Authorization", "Basic " + Base64Utils.encodeToString("customer1:pass1".getBytes())) + ) + .andExpect(status().isUnauthorized()); + } +} From 0db8c73f75c2a186a5d89295ce8639f5ad5c225c Mon Sep 17 00:00:00 2001 From: sampadawagde Date: Mon, 18 Jul 2022 20:25:11 +0530 Subject: [PATCH 13/16] JAVA-12754: Moved 2 articles to new module spring-security-web-login-2 --- .../spring-security-web-login-2/README.md | 9 ++ .../spring-security-web-login-2/pom.xml | 60 ++++++++++++ .../logoutredirects/LogoutApplication.java | 13 +++ .../securityconfig/SpringSecurityConfig.java | 27 ++++++ .../manuallogout/ManualLogoutApplication.java | 11 +++ .../SimpleSecurityConfiguration.java | 95 ++++++++++++++++++ .../src/main/resources/application.properties | 5 + .../src/main/resources/logback.xml | 13 +++ .../LogoutApplicationUnitTest.java | 34 +++++++ .../ManualLogoutIntegrationTest.java | 96 +++++++++++++++++++ .../src/test/resources/logback-test.xml | 12 +++ 11 files changed, 375 insertions(+) create mode 100644 spring-security-modules/spring-security-web-login-2/README.md create mode 100644 spring-security-modules/spring-security-web-login-2/pom.xml create mode 100644 spring-security-modules/spring-security-web-login-2/src/main/java/com/baeldung/logoutredirects/LogoutApplication.java create mode 100644 spring-security-modules/spring-security-web-login-2/src/main/java/com/baeldung/logoutredirects/securityconfig/SpringSecurityConfig.java create mode 100644 spring-security-modules/spring-security-web-login-2/src/main/java/com/baeldung/manuallogout/ManualLogoutApplication.java create mode 100644 spring-security-modules/spring-security-web-login-2/src/main/java/com/baeldung/manuallogout/SimpleSecurityConfiguration.java create mode 100644 spring-security-modules/spring-security-web-login-2/src/main/resources/application.properties create mode 100644 spring-security-modules/spring-security-web-login-2/src/main/resources/logback.xml create mode 100644 spring-security-modules/spring-security-web-login-2/src/test/java/com/baeldung/logoutredirects/LogoutApplicationUnitTest.java create mode 100644 spring-security-modules/spring-security-web-login-2/src/test/java/com/baeldung/manuallogout/ManualLogoutIntegrationTest.java create mode 100644 spring-security-modules/spring-security-web-login-2/src/test/resources/logback-test.xml diff --git a/spring-security-modules/spring-security-web-login-2/README.md b/spring-security-modules/spring-security-web-login-2/README.md new file mode 100644 index 0000000000..826301c0fe --- /dev/null +++ b/spring-security-modules/spring-security-web-login-2/README.md @@ -0,0 +1,9 @@ +## Spring Security Login - 2 + +This module contains articles about login/logout mechanisms with Spring Security. + +## Relevant articles: + +- [Manual Logout With Spring Security](https://www.baeldung.com/spring-security-manual-logout) +- [How to Disable Spring Security Logout Redirects](https://www.baeldung.com/spring-security-disable-logout-redirects) +- More articles: [[<-- prev]](/spring-security-modules/spring-security-web-login) diff --git a/spring-security-modules/spring-security-web-login-2/pom.xml b/spring-security-modules/spring-security-web-login-2/pom.xml new file mode 100644 index 0000000000..d5e5a4426e --- /dev/null +++ b/spring-security-modules/spring-security-web-login-2/pom.xml @@ -0,0 +1,60 @@ + + + 4.0.0 + spring-security-web-login-2 + 0.0.1-SNAPSHOT + spring-security-web-login-2 + jar + + + com.baeldung + parent-boot-2 + 0.0.1-SNAPSHOT + ../../parent-boot-2 + + + + + org.springframework.boot + spring-boot-starter-security + + + org.springframework.boot + spring-boot-starter-web + + + org.springframework.boot + spring-boot-starter-thymeleaf + + + org.thymeleaf.extras + thymeleaf-extras-springsecurity5 + + + org.springframework + spring-test + + + org.springframework.boot + spring-boot-starter-test + test + + + org.springframework.security + spring-security-test + test + + + + + + + org.springframework.boot + spring-boot-maven-plugin + + + + + \ No newline at end of file diff --git a/spring-security-modules/spring-security-web-login-2/src/main/java/com/baeldung/logoutredirects/LogoutApplication.java b/spring-security-modules/spring-security-web-login-2/src/main/java/com/baeldung/logoutredirects/LogoutApplication.java new file mode 100644 index 0000000000..ef8175ffb2 --- /dev/null +++ b/spring-security-modules/spring-security-web-login-2/src/main/java/com/baeldung/logoutredirects/LogoutApplication.java @@ -0,0 +1,13 @@ +package com.baeldung.logoutredirects; + +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; + +@SpringBootApplication +public class LogoutApplication { + + public static void main(String[] args) { + SpringApplication.run(LogoutApplication.class, args); + } + +} diff --git a/spring-security-modules/spring-security-web-login-2/src/main/java/com/baeldung/logoutredirects/securityconfig/SpringSecurityConfig.java b/spring-security-modules/spring-security-web-login-2/src/main/java/com/baeldung/logoutredirects/securityconfig/SpringSecurityConfig.java new file mode 100644 index 0000000000..64141f63d8 --- /dev/null +++ b/spring-security-modules/spring-security-web-login-2/src/main/java/com/baeldung/logoutredirects/securityconfig/SpringSecurityConfig.java @@ -0,0 +1,27 @@ +package com.baeldung.logoutredirects.securityconfig; + +import javax.servlet.http.HttpServletResponse; + +import org.springframework.context.annotation.Configuration; +import org.springframework.security.config.annotation.web.builders.HttpSecurity; +import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity; +import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter; + +@Configuration +@EnableWebSecurity +public class SpringSecurityConfig extends WebSecurityConfigurerAdapter { + + @Override + protected void configure(HttpSecurity http) throws Exception { + http.authorizeRequests(authz -> authz.mvcMatchers("/login") + .permitAll() + .anyRequest() + .authenticated()) + .logout(logout -> logout.permitAll() + .logoutSuccessHandler((request, response, authentication) -> { + response.setStatus(HttpServletResponse.SC_OK); + })); + + } + +} diff --git a/spring-security-modules/spring-security-web-login-2/src/main/java/com/baeldung/manuallogout/ManualLogoutApplication.java b/spring-security-modules/spring-security-web-login-2/src/main/java/com/baeldung/manuallogout/ManualLogoutApplication.java new file mode 100644 index 0000000000..50ea356f03 --- /dev/null +++ b/spring-security-modules/spring-security-web-login-2/src/main/java/com/baeldung/manuallogout/ManualLogoutApplication.java @@ -0,0 +1,11 @@ +package com.baeldung.manuallogout; + +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; + +@SpringBootApplication +public class ManualLogoutApplication { + public static void main(String[] args) { + SpringApplication.run(ManualLogoutApplication.class, args); + } +} diff --git a/spring-security-modules/spring-security-web-login-2/src/main/java/com/baeldung/manuallogout/SimpleSecurityConfiguration.java b/spring-security-modules/spring-security-web-login-2/src/main/java/com/baeldung/manuallogout/SimpleSecurityConfiguration.java new file mode 100644 index 0000000000..303a139215 --- /dev/null +++ b/spring-security-modules/spring-security-web-login-2/src/main/java/com/baeldung/manuallogout/SimpleSecurityConfiguration.java @@ -0,0 +1,95 @@ +package com.baeldung.manuallogout; + +import static org.springframework.security.web.header.writers.ClearSiteDataHeaderWriter.Directive.CACHE; +import static org.springframework.security.web.header.writers.ClearSiteDataHeaderWriter.Directive.COOKIES; +import static org.springframework.security.web.header.writers.ClearSiteDataHeaderWriter.Directive.EXECUTION_CONTEXTS; +import static org.springframework.security.web.header.writers.ClearSiteDataHeaderWriter.Directive.STORAGE; + +import javax.servlet.ServletException; +import javax.servlet.http.Cookie; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.context.annotation.Configuration; +import org.springframework.core.annotation.Order; +import org.springframework.security.config.annotation.web.builders.HttpSecurity; +import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity; +import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter; +import org.springframework.security.web.authentication.logout.HeaderWriterLogoutHandler; +import org.springframework.security.web.authentication.logout.SecurityContextLogoutHandler; +import org.springframework.security.web.header.writers.ClearSiteDataHeaderWriter; + +@Configuration +@EnableWebSecurity +public class SimpleSecurityConfiguration { + + private static Logger logger = LoggerFactory.getLogger(SimpleSecurityConfiguration.class); + + @Order(4) + @Configuration + public static class LogoutOnRequestConfiguration extends WebSecurityConfigurerAdapter { + @Override + protected void configure(HttpSecurity http) throws Exception { + http.antMatcher("/request/**") + .authorizeRequests(authz -> authz.anyRequest() + .permitAll()) + .logout(logout -> logout.logoutUrl("/request/logout") + .addLogoutHandler((request, response, auth) -> { + try { + request.logout(); + } catch (ServletException e) { + logger.error(e.getMessage()); + } + })); + } + } + + @Order(3) + @Configuration + public static class DefaultLogoutConfiguration extends WebSecurityConfigurerAdapter { + @Override + protected void configure(HttpSecurity http) throws Exception { + http.antMatcher("/basic/**") + .authorizeRequests(authz -> authz.anyRequest() + .permitAll()) + .logout(logout -> logout.logoutUrl("/basic/basiclogout")); + } + } + + @Order(2) + @Configuration + public static class AllCookieClearingLogoutConfiguration extends WebSecurityConfigurerAdapter { + @Override + protected void configure(HttpSecurity http) throws Exception { + http.antMatcher("/cookies/**") + .authorizeRequests(authz -> authz.anyRequest() + .permitAll()) + .logout(logout -> logout.logoutUrl("/cookies/cookielogout") + .addLogoutHandler(new SecurityContextLogoutHandler()) + .addLogoutHandler((request, response, auth) -> { + for (Cookie cookie : request.getCookies()) { + String cookieName = cookie.getName(); + Cookie cookieToDelete = new Cookie(cookieName, null); + cookieToDelete.setMaxAge(0); + response.addCookie(cookieToDelete); + } + })); + } + } + + @Order(1) + @Configuration + public static class ClearSiteDataHeaderLogoutConfiguration extends WebSecurityConfigurerAdapter { + + private static final ClearSiteDataHeaderWriter.Directive[] SOURCE = { CACHE, COOKIES, STORAGE, EXECUTION_CONTEXTS }; + + @Override + protected void configure(HttpSecurity http) throws Exception { + http.antMatcher("/csd/**") + .authorizeRequests(authz -> authz.anyRequest() + .permitAll()) + .logout(logout -> logout.logoutUrl("/csd/csdlogout") + .addLogoutHandler(new HeaderWriterLogoutHandler(new ClearSiteDataHeaderWriter(SOURCE)))); + } + } +} diff --git a/spring-security-modules/spring-security-web-login-2/src/main/resources/application.properties b/spring-security-modules/spring-security-web-login-2/src/main/resources/application.properties new file mode 100644 index 0000000000..7fc55efed9 --- /dev/null +++ b/spring-security-modules/spring-security-web-login-2/src/main/resources/application.properties @@ -0,0 +1,5 @@ +server.port=8081 + +logging.level.root=INFO + +logging.level.org.springframework.security=DEBUG \ No newline at end of file diff --git a/spring-security-modules/spring-security-web-login-2/src/main/resources/logback.xml b/spring-security-modules/spring-security-web-login-2/src/main/resources/logback.xml new file mode 100644 index 0000000000..7d900d8ea8 --- /dev/null +++ b/spring-security-modules/spring-security-web-login-2/src/main/resources/logback.xml @@ -0,0 +1,13 @@ + + + + + %d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n + + + + + + + + \ No newline at end of file diff --git a/spring-security-modules/spring-security-web-login-2/src/test/java/com/baeldung/logoutredirects/LogoutApplicationUnitTest.java b/spring-security-modules/spring-security-web-login-2/src/test/java/com/baeldung/logoutredirects/LogoutApplicationUnitTest.java new file mode 100644 index 0000000000..519a6bdc99 --- /dev/null +++ b/spring-security-modules/spring-security-web-login-2/src/test/java/com/baeldung/logoutredirects/LogoutApplicationUnitTest.java @@ -0,0 +1,34 @@ +package com.baeldung.logoutredirects; + +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.test.autoconfigure.web.servlet.WebMvcTest; +import org.springframework.security.test.context.support.WithMockUser; +import org.springframework.test.context.junit4.SpringRunner; +import org.springframework.test.web.servlet.MockMvc; + +import static org.springframework.security.test.web.servlet.request.SecurityMockMvcRequestPostProcessors.csrf; +import static org.springframework.security.test.web.servlet.response.SecurityMockMvcResultMatchers.unauthenticated; +import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.*; + +@RunWith(SpringRunner.class) +@WebMvcTest() +public class LogoutApplicationUnitTest { + + @Autowired + private MockMvc mockMvc; + + @WithMockUser(value = "spring") + @Test + public void whenLogout_thenDisableRedirect() throws Exception { + + this.mockMvc.perform(post("/logout").with(csrf())) + .andExpect(status().isOk()) + .andExpect(jsonPath("$").doesNotExist()) + .andExpect(unauthenticated()) + .andReturn(); + } + +} \ No newline at end of file diff --git a/spring-security-modules/spring-security-web-login-2/src/test/java/com/baeldung/manuallogout/ManualLogoutIntegrationTest.java b/spring-security-modules/spring-security-web-login-2/src/test/java/com/baeldung/manuallogout/ManualLogoutIntegrationTest.java new file mode 100644 index 0000000000..06dc01e116 --- /dev/null +++ b/spring-security-modules/spring-security-web-login-2/src/test/java/com/baeldung/manuallogout/ManualLogoutIntegrationTest.java @@ -0,0 +1,96 @@ +package com.baeldung.manuallogout; + +import static org.junit.Assert.assertNull; +import static org.springframework.security.test.web.servlet.request.SecurityMockMvcRequestPostProcessors.csrf; +import static org.springframework.security.test.web.servlet.response.SecurityMockMvcResultMatchers.unauthenticated; +import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post; +import static org.springframework.test.web.servlet.result.MockMvcResultHandlers.print; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.cookie; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.header; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; + +import javax.servlet.http.Cookie; +import javax.servlet.http.HttpSession; + +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.test.autoconfigure.web.servlet.WebMvcTest; +import org.springframework.mock.web.MockHttpServletRequest; +import org.springframework.mock.web.MockHttpSession; +import org.springframework.security.test.context.support.WithMockUser; +import org.springframework.test.context.junit4.SpringRunner; +import org.springframework.test.web.servlet.MockMvc; + +@RunWith(SpringRunner.class) +@WebMvcTest() +public class ManualLogoutIntegrationTest { + + private static final String CLEAR_SITE_DATA_HEADER = "Clear-Site-Data"; + public static final int EXPIRY = 60 * 10; + public static final String COOKIE_NAME = "customerName"; + public static final String COOKIE_VALUE = "myName"; + public static final String ATTRIBUTE_NAME = "att"; + public static final String ATTRIBUTE_VALUE = "attvalue"; + + @Autowired + private MockMvc mockMvc; + + @WithMockUser(value = "spring") + @Test + public void givenLoggedUserWhenUserLogoutThenSessionClearedAndNecessaryCookieCleared() throws Exception { + + this.mockMvc.perform(post("/basic/basiclogout").secure(true) + .with(csrf())) + .andExpect(status().is3xxRedirection()) + .andExpect(unauthenticated()) + .andReturn(); + } + + @WithMockUser(value = "spring") + @Test + public void givenLoggedUserWhenUserLogoutThenSessionClearedAndAllCookiesCleared() throws Exception { + + MockHttpSession session = new MockHttpSession(); + session.setAttribute(ATTRIBUTE_NAME, ATTRIBUTE_VALUE); + + Cookie randomCookie = new Cookie(COOKIE_NAME, COOKIE_VALUE); + randomCookie.setMaxAge(EXPIRY); // 10 minutes + + MockHttpServletRequest requestStateAfterLogout = this.mockMvc.perform(post("/cookies/cookielogout").secure(true) + .with(csrf()) + .session(session) + .cookie(randomCookie)) + .andExpect(status().is3xxRedirection()) + .andExpect(unauthenticated()) + .andExpect(cookie().maxAge(COOKIE_NAME, 0)) + .andReturn() + .getRequest(); + + HttpSession sessionStateAfterLogout = requestStateAfterLogout.getSession(); + assertNull(sessionStateAfterLogout.getAttribute(ATTRIBUTE_NAME)); + } + + @WithMockUser(value = "spring") + @Test + public void givenLoggedUserWhenUserLogoutThenClearDataSiteHeaderPresent() throws Exception { + + this.mockMvc.perform(post("/csd/csdlogout").secure(true) + .with(csrf())) + .andDo(print()) + .andExpect(status().is3xxRedirection()) + .andExpect(header().exists(CLEAR_SITE_DATA_HEADER)) + .andReturn(); + } + + @WithMockUser(value = "spring") + @Test + public void givenLoggedUserWhenUserLogoutOnRequestThenSessionCleared() throws Exception { + + this.mockMvc.perform(post("/request/logout").secure(true) + .with(csrf())) + .andExpect(status().is3xxRedirection()) + .andExpect(unauthenticated()) + .andReturn(); + } +} \ No newline at end of file diff --git a/spring-security-modules/spring-security-web-login-2/src/test/resources/logback-test.xml b/spring-security-modules/spring-security-web-login-2/src/test/resources/logback-test.xml new file mode 100644 index 0000000000..8d4771e308 --- /dev/null +++ b/spring-security-modules/spring-security-web-login-2/src/test/resources/logback-test.xml @@ -0,0 +1,12 @@ + + + + + [%d{ISO8601}]-[%thread] %-5level %logger - %msg%n + + + + + + + \ No newline at end of file From 8faf52f3633d515e0a232156eda17bda7c1c9761 Mon Sep 17 00:00:00 2001 From: sampadawagde Date: Mon, 18 Jul 2022 20:25:59 +0530 Subject: [PATCH 14/16] JAVA-12754: Moved 2 articles to spring-security-web-rest-basic-auth --- .../spring-security-web-rest-basic-auth/README.md | 3 +++ 1 file changed, 3 insertions(+) diff --git a/spring-security-modules/spring-security-web-rest-basic-auth/README.md b/spring-security-modules/spring-security-web-rest-basic-auth/README.md index 97f682acd3..ad1bd098bb 100644 --- a/spring-security-modules/spring-security-web-rest-basic-auth/README.md +++ b/spring-security-modules/spring-security-web-rest-basic-auth/README.md @@ -11,3 +11,6 @@ The "Learn Spring Security" Classes: http://github.learnspringsecurity.com - [Basic Authentication with the RestTemplate](https://www.baeldung.com/how-to-use-resttemplate-with-basic-authentication-in-spring) - [A Custom Filter in the Spring Security Filter Chain](https://www.baeldung.com/spring-security-custom-filter) - [Spring Security Basic Authentication](https://www.baeldung.com/spring-security-basic-authentication) +- [New Password Storage In Spring Security 5](https://www.baeldung.com/spring-security-5-password-storage) +- [Default Password Encoder in Spring Security 5](https://www.baeldung.com/spring-security-5-default-password-encoder) + From 39108198348282dae09337f70990df62d211021c Mon Sep 17 00:00:00 2001 From: sampadawagde Date: Mon, 18 Jul 2022 20:27:20 +0530 Subject: [PATCH 15/16] JAVA-12754: Moved 2 articles to spring-security-web-rest-basic-auth --- .../pom.xml | 24 ++------ .../inmemory/InMemoryAuthApplication.java | 14 +++++ .../inmemory/InMemoryAuthController.java | 21 +++++++ .../InMemoryAuthWebSecurityConfigurer.java | 34 ++++++++++++ ...InMemoryNoOpAuthWebSecurityConfigurer.java | 29 ++++++++++ .../BaeldungPasswordEncoderSetup.java | 35 ++++++++++++ .../PasswordStorageApplication.java | 13 +++++ .../PasswordStorageWebSecurityConfigurer.java | 55 +++++++++++++++++++ ...InMemoryAuthControllerIntegrationTest.java | 48 ++++++++++++++++ 9 files changed, 255 insertions(+), 18 deletions(-) create mode 100644 spring-security-modules/spring-security-web-rest-basic-auth/src/main/java/com/baeldung/inmemory/InMemoryAuthApplication.java create mode 100644 spring-security-modules/spring-security-web-rest-basic-auth/src/main/java/com/baeldung/inmemory/InMemoryAuthController.java create mode 100644 spring-security-modules/spring-security-web-rest-basic-auth/src/main/java/com/baeldung/inmemory/InMemoryAuthWebSecurityConfigurer.java create mode 100644 spring-security-modules/spring-security-web-rest-basic-auth/src/main/java/com/baeldung/inmemory/InMemoryNoOpAuthWebSecurityConfigurer.java create mode 100644 spring-security-modules/spring-security-web-rest-basic-auth/src/main/java/com/baeldung/passwordstorage/BaeldungPasswordEncoderSetup.java create mode 100644 spring-security-modules/spring-security-web-rest-basic-auth/src/main/java/com/baeldung/passwordstorage/PasswordStorageApplication.java create mode 100644 spring-security-modules/spring-security-web-rest-basic-auth/src/main/java/com/baeldung/passwordstorage/PasswordStorageWebSecurityConfigurer.java create mode 100644 spring-security-modules/spring-security-web-rest-basic-auth/src/test/java/com/baeldung/inmemory/InMemoryAuthControllerIntegrationTest.java diff --git a/spring-security-modules/spring-security-web-rest-basic-auth/pom.xml b/spring-security-modules/spring-security-web-rest-basic-auth/pom.xml index 30b92be5ac..41f508c1a3 100644 --- a/spring-security-modules/spring-security-web-rest-basic-auth/pom.xml +++ b/spring-security-modules/spring-security-web-rest-basic-auth/pom.xml @@ -10,28 +10,29 @@ com.baeldung - parent-spring-5 + parent-boot-2 0.0.1-SNAPSHOT - ../../parent-spring-5 + ../../parent-boot-2 + + org.springframework.boot + spring-boot-starter-web + org.springframework.security spring-security-web - ${spring-security.version} org.springframework.security spring-security-config - ${spring-security.version} org.springframework spring-core - ${spring.version} commons-logging @@ -42,59 +43,48 @@ org.springframework spring-context - ${spring.version} org.springframework spring-jdbc - ${spring.version} org.springframework spring-beans - ${spring.version} org.springframework spring-aop - ${spring.version} org.springframework spring-tx - ${spring.version} org.springframework spring-expression - ${spring.version} org.springframework spring-web - ${spring.version} org.springframework spring-webmvc - ${spring.version} org.springframework spring-oxm - ${spring.version} com.fasterxml.jackson.core jackson-databind - ${jackson.version} org.apache.httpcomponents httpcore - ${httpcore.version} commons-logging @@ -105,7 +95,6 @@ org.apache.httpcomponents httpclient - ${httpclient.version} commons-logging @@ -136,7 +125,6 @@ org.springframework spring-test - ${spring.version} test diff --git a/spring-security-modules/spring-security-web-rest-basic-auth/src/main/java/com/baeldung/inmemory/InMemoryAuthApplication.java b/spring-security-modules/spring-security-web-rest-basic-auth/src/main/java/com/baeldung/inmemory/InMemoryAuthApplication.java new file mode 100644 index 0000000000..6ccfd04553 --- /dev/null +++ b/spring-security-modules/spring-security-web-rest-basic-auth/src/main/java/com/baeldung/inmemory/InMemoryAuthApplication.java @@ -0,0 +1,14 @@ +package com.baeldung.inmemory; + +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; + +@SpringBootApplication +public class InMemoryAuthApplication { + + public static void main(String[] args) { + SpringApplication.run(InMemoryAuthApplication.class, args); + } + + +} diff --git a/spring-security-modules/spring-security-web-rest-basic-auth/src/main/java/com/baeldung/inmemory/InMemoryAuthController.java b/spring-security-modules/spring-security-web-rest-basic-auth/src/main/java/com/baeldung/inmemory/InMemoryAuthController.java new file mode 100644 index 0000000000..ff7ae9a131 --- /dev/null +++ b/spring-security-modules/spring-security-web-rest-basic-auth/src/main/java/com/baeldung/inmemory/InMemoryAuthController.java @@ -0,0 +1,21 @@ +package com.baeldung.inmemory; + +import java.util.Arrays; +import java.util.List; +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.RestController; + +@RestController +public class InMemoryAuthController { + + @GetMapping("/public/hello") + public List publicHello() { + return Arrays.asList("Hello", "World", "from", "Public"); + } + + @GetMapping("/private/hello") + public List privateHello() { + return Arrays.asList("Hello", "World", "from", "Private"); + } + +} diff --git a/spring-security-modules/spring-security-web-rest-basic-auth/src/main/java/com/baeldung/inmemory/InMemoryAuthWebSecurityConfigurer.java b/spring-security-modules/spring-security-web-rest-basic-auth/src/main/java/com/baeldung/inmemory/InMemoryAuthWebSecurityConfigurer.java new file mode 100644 index 0000000000..4b32a1126e --- /dev/null +++ b/spring-security-modules/spring-security-web-rest-basic-auth/src/main/java/com/baeldung/inmemory/InMemoryAuthWebSecurityConfigurer.java @@ -0,0 +1,34 @@ +package com.baeldung.inmemory; + +import org.springframework.context.annotation.Configuration; +import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder; +import org.springframework.security.config.annotation.web.builders.HttpSecurity; +import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter; +import org.springframework.security.crypto.factory.PasswordEncoderFactories; +import org.springframework.security.crypto.password.PasswordEncoder; + +@Configuration +public class InMemoryAuthWebSecurityConfigurer extends WebSecurityConfigurerAdapter { + + @Override + protected void configure(AuthenticationManagerBuilder auth) throws Exception { + PasswordEncoder encoder = PasswordEncoderFactories.createDelegatingPasswordEncoder(); + auth.inMemoryAuthentication() + .passwordEncoder(encoder) + .withUser("spring") + .password(encoder.encode("secret")) + .roles("USER"); + } + + @Override + protected void configure(HttpSecurity http) throws Exception { + http.authorizeRequests() + .antMatchers("/private/**") + .authenticated() + .antMatchers("/public/**") + .permitAll() + .and() + .httpBasic(); + } + +} diff --git a/spring-security-modules/spring-security-web-rest-basic-auth/src/main/java/com/baeldung/inmemory/InMemoryNoOpAuthWebSecurityConfigurer.java b/spring-security-modules/spring-security-web-rest-basic-auth/src/main/java/com/baeldung/inmemory/InMemoryNoOpAuthWebSecurityConfigurer.java new file mode 100644 index 0000000000..4b6494f666 --- /dev/null +++ b/spring-security-modules/spring-security-web-rest-basic-auth/src/main/java/com/baeldung/inmemory/InMemoryNoOpAuthWebSecurityConfigurer.java @@ -0,0 +1,29 @@ +package com.baeldung.inmemory; + +import org.springframework.context.annotation.Configuration; +import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder; +import org.springframework.security.config.annotation.web.builders.HttpSecurity; +import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter; + +//@Configuration +public class InMemoryNoOpAuthWebSecurityConfigurer extends WebSecurityConfigurerAdapter { + + @Override + protected void configure(AuthenticationManagerBuilder auth) throws Exception { + auth.inMemoryAuthentication() + .withUser("spring") + .password("{noop}secret") + .roles("USER"); + } + + @Override + protected void configure(HttpSecurity http) throws Exception { + http.authorizeRequests() + .antMatchers("/private/**") + .authenticated() + .antMatchers("/public/**") + .permitAll() + .and() + .httpBasic(); + } +} diff --git a/spring-security-modules/spring-security-web-rest-basic-auth/src/main/java/com/baeldung/passwordstorage/BaeldungPasswordEncoderSetup.java b/spring-security-modules/spring-security-web-rest-basic-auth/src/main/java/com/baeldung/passwordstorage/BaeldungPasswordEncoderSetup.java new file mode 100644 index 0000000000..94987029db --- /dev/null +++ b/spring-security-modules/spring-security-web-rest-basic-auth/src/main/java/com/baeldung/passwordstorage/BaeldungPasswordEncoderSetup.java @@ -0,0 +1,35 @@ +package com.baeldung.passwordstorage; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.context.ApplicationListener; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; +import org.springframework.security.authentication.UsernamePasswordAuthenticationToken; +import org.springframework.security.authentication.event.AuthenticationSuccessEvent; +import org.springframework.security.core.Authentication; +import org.springframework.security.crypto.password.PasswordEncoder; + +@Configuration +public class BaeldungPasswordEncoderSetup { + + private final static Logger LOG = LoggerFactory.getLogger(BaeldungPasswordEncoderSetup.class); + + @Bean + public ApplicationListener authenticationSuccessListener(final PasswordEncoder encoder) { + + return (AuthenticationSuccessEvent event) -> { + final Authentication auth = event.getAuthentication(); + + if (auth instanceof UsernamePasswordAuthenticationToken && auth.getCredentials() != null) { + + final CharSequence clearTextPass = (CharSequence) auth.getCredentials(); // 1 + final String newPasswordHash = encoder.encode(clearTextPass); // 2 + + LOG.info("New password hash {} for user {}", newPasswordHash, auth.getName()); + + ((UsernamePasswordAuthenticationToken) auth).eraseCredentials(); // 3 + } + }; + } +} diff --git a/spring-security-modules/spring-security-web-rest-basic-auth/src/main/java/com/baeldung/passwordstorage/PasswordStorageApplication.java b/spring-security-modules/spring-security-web-rest-basic-auth/src/main/java/com/baeldung/passwordstorage/PasswordStorageApplication.java new file mode 100644 index 0000000000..173d979a45 --- /dev/null +++ b/spring-security-modules/spring-security-web-rest-basic-auth/src/main/java/com/baeldung/passwordstorage/PasswordStorageApplication.java @@ -0,0 +1,13 @@ +package com.baeldung.passwordstorage; + +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; + +@SpringBootApplication +public class PasswordStorageApplication { + + public static void main(String[] args) { + SpringApplication.run(PasswordStorageApplication.class, args); + } + +} diff --git a/spring-security-modules/spring-security-web-rest-basic-auth/src/main/java/com/baeldung/passwordstorage/PasswordStorageWebSecurityConfigurer.java b/spring-security-modules/spring-security-web-rest-basic-auth/src/main/java/com/baeldung/passwordstorage/PasswordStorageWebSecurityConfigurer.java new file mode 100644 index 0000000000..59a2ae1dc2 --- /dev/null +++ b/spring-security-modules/spring-security-web-rest-basic-auth/src/main/java/com/baeldung/passwordstorage/PasswordStorageWebSecurityConfigurer.java @@ -0,0 +1,55 @@ +package com.baeldung.passwordstorage; + +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; +import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder; +import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter; +import org.springframework.security.core.userdetails.User; +import org.springframework.security.core.userdetails.UserDetailsService; +import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder; +import org.springframework.security.crypto.password.DelegatingPasswordEncoder; +import org.springframework.security.crypto.password.NoOpPasswordEncoder; +import org.springframework.security.crypto.password.PasswordEncoder; +import org.springframework.security.crypto.password.StandardPasswordEncoder; +import org.springframework.security.crypto.scrypt.SCryptPasswordEncoder; +import org.springframework.security.provisioning.InMemoryUserDetailsManager; + +import java.util.Collections; +import java.util.HashMap; +import java.util.Map; + +@Configuration +public class PasswordStorageWebSecurityConfigurer extends WebSecurityConfigurerAdapter { + + @Override + protected void configure(AuthenticationManagerBuilder auth) throws Exception { + auth.eraseCredentials(false) // 4 + .userDetailsService(getUserDefaultDetailsService()) + .passwordEncoder(passwordEncoder()); + } + + @Bean + public UserDetailsService getUserDefaultDetailsService() { + return new InMemoryUserDetailsManager(User + .withUsername("baeldung") + .password("{noop}SpringSecurity5") + .authorities(Collections.emptyList()) + .build()); + } + + @Bean + public PasswordEncoder passwordEncoder() { + // set up the list of supported encoders and their prefixes + PasswordEncoder defaultEncoder = new StandardPasswordEncoder(); + Map encoders = new HashMap<>(); + encoders.put("bcrypt", new BCryptPasswordEncoder()); + encoders.put("scrypt", new SCryptPasswordEncoder()); + encoders.put("noop", NoOpPasswordEncoder.getInstance()); + + DelegatingPasswordEncoder passwordEncoder = new DelegatingPasswordEncoder("bcrypt", encoders); + passwordEncoder.setDefaultPasswordEncoderForMatches(defaultEncoder); + + return passwordEncoder; + } + +} diff --git a/spring-security-modules/spring-security-web-rest-basic-auth/src/test/java/com/baeldung/inmemory/InMemoryAuthControllerIntegrationTest.java b/spring-security-modules/spring-security-web-rest-basic-auth/src/test/java/com/baeldung/inmemory/InMemoryAuthControllerIntegrationTest.java new file mode 100644 index 0000000000..9d08cb7cfa --- /dev/null +++ b/spring-security-modules/spring-security-web-rest-basic-auth/src/test/java/com/baeldung/inmemory/InMemoryAuthControllerIntegrationTest.java @@ -0,0 +1,48 @@ +package com.baeldung.inmemory; + +import static org.junit.Assert.assertEquals; + +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.context.SpringBootTest.WebEnvironment; +import org.springframework.boot.test.web.client.TestRestTemplate; +import org.springframework.http.HttpStatus; +import org.springframework.http.ResponseEntity; +import org.springframework.test.context.junit4.SpringRunner; + +@RunWith(SpringRunner.class) +@SpringBootTest(classes = InMemoryAuthApplication.class, webEnvironment = WebEnvironment.RANDOM_PORT) +public class InMemoryAuthControllerIntegrationTest { + + @Autowired + private TestRestTemplate template; + + @Test + public void givenRequestOnPublicService_shouldSucceedWith200() throws Exception { + ResponseEntity result = template.getForEntity("/public/hello", String.class); + assertEquals(HttpStatus.OK, result.getStatusCode()); + } + + @Test + public void givenRequestOnPrivateService_shouldFailWith401() throws Exception { + ResponseEntity result = template.getForEntity("/private/hello", String.class); + assertEquals(HttpStatus.UNAUTHORIZED, result.getStatusCode()); + } + + @Test + public void givenAuthRequestOnPrivateService_shouldSucceedWith200() throws Exception { + ResponseEntity result = template.withBasicAuth("spring", "secret") + .getForEntity("/private/hello", String.class); + assertEquals(HttpStatus.OK, result.getStatusCode()); + } + + @Test + public void givenInvalidAuthRequestOnPrivateService_shouldSucceedWith200() throws Exception { + ResponseEntity result = template.withBasicAuth("spring", "wrong") + .getForEntity("/private/hello", String.class); + assertEquals(HttpStatus.UNAUTHORIZED, result.getStatusCode()); + } + +} From 073f099fdc74c01729957a9ba576cac6bf1e7ea2 Mon Sep 17 00:00:00 2001 From: sampadawagde Date: Mon, 18 Jul 2022 20:27:47 +0530 Subject: [PATCH 16/16] JAVA-12754: Add next link to module --- spring-security-modules/spring-security-web-login/README.md | 1 + 1 file changed, 1 insertion(+) diff --git a/spring-security-modules/spring-security-web-login/README.md b/spring-security-modules/spring-security-web-login/README.md index bbef468944..b6cdc8c1e1 100644 --- a/spring-security-modules/spring-security-web-login/README.md +++ b/spring-security-modules/spring-security-web-login/README.md @@ -13,6 +13,7 @@ The "Learn Spring Security" Classes: http://github.learnspringsecurity.com - [Spring Security – Redirect to the Previous URL After Login](https://www.baeldung.com/spring-security-redirect-login) - [Spring Security Custom AuthenticationFailureHandler](https://www.baeldung.com/spring-security-custom-authentication-failure-handler) - [Extra Login Fields with Spring Security](https://www.baeldung.com/spring-security-extra-login-fields) +- More articles: [[next -->]](/spring-security-modules/spring-security-web-login-2) ### Build the Project ```