JAVA-12754: removed module spring-5-security
This commit is contained in:
@@ -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)
|
||||
@@ -1,84 +0,0 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<project xmlns="http://maven.apache.org/POM/4.0.0"
|
||||
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
|
||||
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
|
||||
<modelVersion>4.0.0</modelVersion>
|
||||
<artifactId>spring-5-security</artifactId>
|
||||
<version>0.0.1-SNAPSHOT</version>
|
||||
<name>spring-5-security</name>
|
||||
<packaging>jar</packaging>
|
||||
<description>spring 5 security sample project</description>
|
||||
|
||||
<parent>
|
||||
<groupId>com.baeldung</groupId>
|
||||
<artifactId>parent-boot-2</artifactId>
|
||||
<version>0.0.1-SNAPSHOT</version>
|
||||
<relativePath>../../parent-boot-2</relativePath>
|
||||
</parent>
|
||||
|
||||
<dependencies>
|
||||
<dependency>
|
||||
<groupId>org.springframework.boot</groupId>
|
||||
<artifactId>spring-boot-starter-security</artifactId>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.springframework.boot</groupId>
|
||||
<artifactId>spring-boot-starter-web</artifactId>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.springframework.boot</groupId>
|
||||
<artifactId>spring-boot-starter-thymeleaf</artifactId>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.thymeleaf.extras</groupId>
|
||||
<artifactId>thymeleaf-extras-springsecurity5</artifactId>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.springframework</groupId>
|
||||
<artifactId>spring-test</artifactId>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.springframework.boot</groupId>
|
||||
<artifactId>spring-boot-starter-test</artifactId>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.springframework.security</groupId>
|
||||
<artifactId>spring-security-test</artifactId>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.owasp.esapi</groupId>
|
||||
<artifactId>esapi</artifactId>
|
||||
<version>${esapi.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.jsoup</groupId>
|
||||
<artifactId>jsoup</artifactId>
|
||||
<version>${jsoup.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>commons-io</groupId>
|
||||
<artifactId>commons-io</artifactId>
|
||||
<version>${commons-io.version}</version>
|
||||
</dependency>
|
||||
</dependencies>
|
||||
|
||||
<build>
|
||||
<plugins>
|
||||
<plugin>
|
||||
<groupId>org.springframework.boot</groupId>
|
||||
<artifactId>spring-boot-maven-plugin</artifactId>
|
||||
<configuration>
|
||||
<mainClass>com.baeldung.passwordstorage.PasswordStorageApplication</mainClass>
|
||||
<layout>JAR</layout>
|
||||
</configuration>
|
||||
</plugin>
|
||||
</plugins>
|
||||
</build>
|
||||
|
||||
<properties>
|
||||
<jsoup.version>1.13.1</jsoup.version>
|
||||
</properties>
|
||||
|
||||
</project>
|
||||
-11
@@ -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);
|
||||
}
|
||||
}
|
||||
-18
@@ -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());
|
||||
}
|
||||
}
|
||||
-96
@@ -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<HttpServletRequest> 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
|
||||
);
|
||||
}
|
||||
|
||||
}
|
||||
-32
@@ -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<ClientErrorLoggingConfigurer, HttpSecurity> {
|
||||
|
||||
private List<HttpStatus> errorCodes;
|
||||
|
||||
public ClientErrorLoggingConfigurer(List<HttpStatus> 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);
|
||||
}
|
||||
|
||||
}
|
||||
-57
@@ -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<HttpStatus> errorCodes;
|
||||
|
||||
public ClientErrorLoggingFilter(List<HttpStatus> 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);
|
||||
}
|
||||
|
||||
}
|
||||
-13
@@ -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);
|
||||
}
|
||||
|
||||
}
|
||||
-14
@@ -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";
|
||||
}
|
||||
|
||||
}
|
||||
-50
@@ -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();
|
||||
}
|
||||
|
||||
}
|
||||
-14
@@ -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);
|
||||
}
|
||||
|
||||
|
||||
}
|
||||
-21
@@ -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<String> publicHello() {
|
||||
return Arrays.asList("Hello", "World", "from", "Public");
|
||||
}
|
||||
|
||||
@GetMapping("/private/hello")
|
||||
public List<String> privateHello() {
|
||||
return Arrays.asList("Hello", "World", "from", "Private");
|
||||
}
|
||||
|
||||
}
|
||||
-34
@@ -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();
|
||||
}
|
||||
|
||||
}
|
||||
-29
@@ -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();
|
||||
}
|
||||
}
|
||||
-13
@@ -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);
|
||||
}
|
||||
|
||||
}
|
||||
-27
@@ -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);
|
||||
}));
|
||||
|
||||
}
|
||||
|
||||
}
|
||||
-11
@@ -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);
|
||||
}
|
||||
}
|
||||
-95
@@ -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))));
|
||||
}
|
||||
}
|
||||
}
|
||||
-35
@@ -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<AuthenticationSuccessEvent> 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
|
||||
}
|
||||
};
|
||||
}
|
||||
}
|
||||
-13
@@ -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);
|
||||
}
|
||||
|
||||
}
|
||||
-55
@@ -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<String, PasswordEncoder> 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;
|
||||
}
|
||||
|
||||
}
|
||||
-14
@@ -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);
|
||||
}
|
||||
}
|
||||
-25
@@ -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'");
|
||||
}
|
||||
}
|
||||
File diff suppressed because it is too large
Load Diff
@@ -1,7 +0,0 @@
|
||||
server.port=8081
|
||||
|
||||
logging.level.root=INFO
|
||||
|
||||
logging.level.com.baeldung.dsl.ClientErrorLoggingFilter=DEBUG
|
||||
|
||||
logging.level.org.springframework.security=DEBUG
|
||||
@@ -1,13 +0,0 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<configuration>
|
||||
<appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender">
|
||||
<encoder>
|
||||
<pattern>%d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n
|
||||
</pattern>
|
||||
</encoder>
|
||||
</appender>
|
||||
|
||||
<root level="INFO">
|
||||
<appender-ref ref="STDOUT" />
|
||||
</root>
|
||||
</configuration>
|
||||
@@ -1,11 +0,0 @@
|
||||
<!DOCTYPE HTML>
|
||||
<html>
|
||||
<head>
|
||||
<title>Home</title>
|
||||
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
|
||||
</head>
|
||||
<body>
|
||||
Home
|
||||
Welcome!
|
||||
</body>
|
||||
</html>
|
||||
-17
@@ -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() {
|
||||
}
|
||||
}
|
||||
-82
@@ -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());
|
||||
}
|
||||
}
|
||||
-48
@@ -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<String> result = template.getForEntity("/public/hello", String.class);
|
||||
assertEquals(HttpStatus.OK, result.getStatusCode());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenRequestOnPrivateService_shouldFailWith401() throws Exception {
|
||||
ResponseEntity<String> result = template.getForEntity("/private/hello", String.class);
|
||||
assertEquals(HttpStatus.UNAUTHORIZED, result.getStatusCode());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenAuthRequestOnPrivateService_shouldSucceedWith200() throws Exception {
|
||||
ResponseEntity<String> result = template.withBasicAuth("spring", "secret")
|
||||
.getForEntity("/private/hello", String.class);
|
||||
assertEquals(HttpStatus.OK, result.getStatusCode());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenInvalidAuthRequestOnPrivateService_shouldSucceedWith200() throws Exception {
|
||||
ResponseEntity<String> result = template.withBasicAuth("spring", "wrong")
|
||||
.getForEntity("/private/hello", String.class);
|
||||
assertEquals(HttpStatus.UNAUTHORIZED, result.getStatusCode());
|
||||
}
|
||||
|
||||
}
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user