Revert "BAEL-4134"

This commit is contained in:
Loredana Crusoveanu
2020-07-07 14:18:10 +03:00
committed by GitHub
parent 4a35b97bad
commit 7ab2f437ee
2466 changed files with 9477 additions and 479200 deletions
+1
View File
@@ -40,6 +40,7 @@
<module>spring-security-stormpath</module>
<module>spring-security-thymeleaf</module>
<module>spring-security-x509</module>
<module>spring-security-kotlin-dsl</module>
</modules>
</project>
@@ -0,0 +1,3 @@
### Relevant Articles:
- [Spring Security With Auth0](https://www.baeldung.com/spring-security-auth0)
@@ -0,0 +1,3 @@
### Relevant Articles:
- [Spring Security with Kotlin DSL](https://www.baeldung.com/kotlin/spring-security-dsl)
@@ -0,0 +1,87 @@
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>com.baeldung</groupId>
<artifactId>parent-boot-2</artifactId>
<version>0.0.1-SNAPSHOT</version>
<relativePath>../../parent-boot-2</relativePath>
</parent>
<groupId>com.baeldung.spring.security.dsl</groupId>
<artifactId>spring-security-kotlin-dsl</artifactId>
<version>1.0</version>
<name>spring-security-kotlin-dsl</name>
<description>Spring Security Kotlin DSL</description>
<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>com.fasterxml.jackson.module</groupId>
<artifactId>jackson-module-kotlin</artifactId>
</dependency>
<dependency>
<groupId>org.jetbrains.kotlin</groupId>
<artifactId>kotlin-reflect</artifactId>
</dependency>
<dependency>
<groupId>org.jetbrains.kotlin</groupId>
<artifactId>kotlin-stdlib-jdk8</artifactId>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<optional>true</optional>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<sourceDirectory>${project.basedir}/src/main/kotlin</sourceDirectory>
<testSourceDirectory>${project.basedir}/src/test/kotlin</testSourceDirectory>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
<plugin>
<groupId>org.jetbrains.kotlin</groupId>
<artifactId>kotlin-maven-plugin</artifactId>
<configuration>
<args>
<arg>-Xjsr305=strict</arg>
</args>
<compilerPlugins>
<plugin>spring</plugin>
</compilerPlugins>
</configuration>
<dependencies>
<dependency>
<groupId>org.jetbrains.kotlin</groupId>
<artifactId>kotlin-maven-allopen</artifactId>
<version>${kotlin.version}</version>
</dependency>
</dependencies>
</plugin>
</plugins>
</build>
<properties>
<java.version>11</java.version>
<kotlin.version>1.3.72</kotlin.version>
</properties>
</project>
@@ -0,0 +1,71 @@
package com.baeldung.security.kotlin.dsl
import org.springframework.boot.autoconfigure.SpringBootApplication
import org.springframework.boot.runApplication
import org.springframework.context.annotation.Configuration
import org.springframework.context.support.beans
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.config.web.servlet.invoke
import org.springframework.security.core.userdetails.User
import org.springframework.security.provisioning.InMemoryUserDetailsManager
import org.springframework.web.servlet.function.ServerResponse
import org.springframework.web.servlet.function.router
@EnableWebSecurity
@SpringBootApplication
class SpringSecurityKotlinApplication
@Order(1)
@Configuration
class AdminSecurityConfiguration : WebSecurityConfigurerAdapter() {
override fun configure(http: HttpSecurity?) {
http {
authorizeRequests {
authorize("/greetings/**", hasAuthority("ROLE_ADMIN"))
}
httpBasic {}
}
}
}
@Configuration
class BasicSecurityConfiguration : WebSecurityConfigurerAdapter() {
override fun configure(http: HttpSecurity?) {
http {
authorizeRequests {
authorize("/**", permitAll)
}
httpBasic {}
}
}
}
fun main(args: Array<String>) {
runApplication<SpringSecurityKotlinApplication>(*args) {
addInitializers( beans {
bean {
fun user(user: String, password: String, vararg roles: String) =
User
.withDefaultPasswordEncoder()
.username(user)
.password(password)
.roles(*roles)
.build()
InMemoryUserDetailsManager(user("user", "password", "USER")
, user("admin", "password", "USER", "ADMIN"))
}
bean {
router {
GET("/greetings") {
request -> request.principal().map { it.name }.map { ServerResponse.ok().body(mapOf("greeting" to "Hello $it")) }.orElseGet { ServerResponse.badRequest().build() }
}
}
}
})
}
}
@@ -0,0 +1,35 @@
package com.spring.security.kotlin.dsl
import org.junit.jupiter.api.Test
import org.junit.runner.RunWith
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc
import org.springframework.boot.test.context.SpringBootTest
import org.springframework.security.test.context.support.WithMockUser
import org.springframework.test.context.junit4.SpringRunner
import org.springframework.test.web.servlet.MockMvc
import org.springframework.security.test.web.servlet.request.SecurityMockMvcRequestBuilders.*
import org.springframework.security.test.web.servlet.request.SecurityMockMvcRequestPostProcessors.user
import org.springframework.security.test.web.servlet.request.SecurityMockMvcRequestPostProcessors.httpBasic
import org.springframework.security.test.web.servlet.response.SecurityMockMvcResultMatchers.authenticated
import org.springframework.security.test.web.servlet.response.SecurityMockMvcResultMatchers.unauthenticated
import org.springframework.test.web.servlet.get
import org.springframework.test.web.servlet.request.MockMvcRequestBuilders.*
import org.springframework.test.web.servlet.result.MockMvcResultMatchers.status
@RunWith(SpringRunner::class)
@SpringBootTest
@AutoConfigureMockMvc
class SpringSecurityKotlinApplicationTests {
@Autowired
private lateinit var mockMvc: MockMvc
@Test
fun `ordinary user not permitted to access the endpoint`() {
this.mockMvc
.perform(get("/greetings")
.with(httpBasic("user", "password")))
.andExpect(unauthenticated())
}
}
@@ -0,0 +1,43 @@
package com.baeldung.loginredirect;
import org.apache.http.HttpStatus;
import org.springframework.security.authentication.AnonymousAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.web.filter.GenericFilterBean;
import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
class LoginPageFilter extends GenericFilterBean {
@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
HttpServletRequest servletRequest = (HttpServletRequest) request;
HttpServletResponse servletResponse = (HttpServletResponse) response;
if (isAuthenticated() && "/loginUser".equals(servletRequest.getRequestURI())) {
String encodedRedirectURL = ((HttpServletResponse) response).encodeRedirectURL(
servletRequest.getContextPath() + "/userMainPage");
servletResponse.setStatus(HttpStatus.SC_TEMPORARY_REDIRECT);
servletResponse.setHeader("Location", encodedRedirectURL);
}
chain.doFilter(servletRequest, servletResponse);
}
private boolean isAuthenticated() {
Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
if (authentication == null || AnonymousAuthenticationToken.class.isAssignableFrom(authentication.getClass())) {
return false;
}
return authentication.isAuthenticated();
}
}
@@ -0,0 +1,39 @@
package com.baeldung.loginredirect;
import org.apache.http.HttpStatus;
import org.springframework.security.authentication.AnonymousAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;
import org.springframework.web.util.UrlPathHelper;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
class LoginPageInterceptor extends HandlerInterceptorAdapter {
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) {
UrlPathHelper urlPathHelper = new UrlPathHelper();
if ("/loginUser".equals(urlPathHelper.getLookupPathForRequest(request)) && isAuthenticated()) {
String encodedRedirectURL = response.encodeRedirectURL(
request.getContextPath() + "/userMainPage");
response.setStatus(HttpStatus.SC_TEMPORARY_REDIRECT);
response.setHeader("Location", encodedRedirectURL);
return false;
} else {
return true;
}
}
private boolean isAuthenticated() {
Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
if (authentication == null || AnonymousAuthenticationToken.class.isAssignableFrom(authentication.getClass())) {
return false;
}
return authentication.isAuthenticated();
}
}
@@ -0,0 +1,13 @@
package com.baeldung.loginredirect;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.ImportResource;
@SpringBootApplication
@ImportResource({"classpath*:spring-security-login-redirect.xml"})
class LoginRedirectApplication {
public static void main(String[] args) {
SpringApplication.run(LoginRedirectApplication.class, args);
}
}
@@ -0,0 +1,14 @@
package com.baeldung.loginredirect;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
@Configuration
class LoginRedirectMvcConfig implements WebMvcConfigurer {
@Override
public void addInterceptors(InterceptorRegistry registry) {
registry.addInterceptor(new LoginPageInterceptor());
}
}
@@ -0,0 +1,43 @@
package com.baeldung.loginredirect;
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.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;
@Configuration
@EnableWebSecurity
class LoginRedirectSecurityConfig extends WebSecurityConfigurerAdapter {
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
auth.inMemoryAuthentication().withUser("user").password(encoder().encode("user")).roles("USER");
}
@Override
protected void configure(HttpSecurity http) throws Exception {
http
.addFilterAfter(new LoginPageFilter(), UsernamePasswordAuthenticationFilter.class)
.authorizeRequests()
.antMatchers("/loginUser").permitAll()
.antMatchers("/user*").hasRole("USER")
.and().formLogin().loginPage("/loginUser").loginProcessingUrl("/user_login")
.failureUrl("/loginUser?error=loginError").defaultSuccessUrl("/userMainPage").permitAll()
.and().logout().logoutUrl("/user_logout").logoutSuccessUrl("/loginUser").deleteCookies("JSESSIONID")
.and().csrf().disable();
}
@Bean
public static PasswordEncoder encoder() {
return new BCryptPasswordEncoder();
}
}
@@ -0,0 +1,32 @@
package com.baeldung.loginredirect;
import org.springframework.security.authentication.AnonymousAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
@Controller
class UsersController {
@GetMapping("/userMainPage")
public String getUserPage() {
return "userMainPage";
}
@GetMapping("/loginUser")
public String getUserLoginPage() {
if (isAuthenticated()) {
return "redirect:userMainPage";
}
return "loginUser";
}
private boolean isAuthenticated() {
Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
if (authentication == null || AnonymousAuthenticationToken.class.isAssignableFrom(authentication.getClass())) {
return false;
}
return authentication.isAuthenticated();
}
}
@@ -1,9 +1,8 @@
http.port=8080
server.port=8443
security.require-ssl=true
server.ssl.enabled=true
# The format used for the keystore
server.ssl.key-store-type=PKCS12
@@ -0,0 +1,46 @@
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xmlns:beans="http://www.springframework.org/schema/beans"
xmlns:security="http://www.springframework.org/schema/security"
xsi:schemaLocation="
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc-4.3.xsd
http://www.springframework.org/schema/security
http://www.springframework.org/schema/security/spring-security-5.2.xsd
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd">
<security:authentication-manager>
<security:authentication-provider>
<security:user-service>
<security:user name="user" password="{noop}user" authorities="ROLE_USER"/>
</security:user-service>
</security:authentication-provider>
</security:authentication-manager>
<security:http pattern="/**" use-expressions="true" auto-config="true">
<security:intercept-url pattern="/loginUser" access="permitAll"/>
<security:intercept-url pattern="/user*" access="hasRole('ROLE_USER')"/>
<security:form-login login-page="/loginUser"
login-processing-url="/user_login"
authentication-failure-url="/loginUser?error=loginError"
default-target-url="/userMainPage"/>
<security:csrf disabled="true"/>
<security:logout logout-url="/user_logout" delete-cookies="JSESSIONID" logout-success-url="/loginUser"/>
<security:custom-filter after="BASIC_AUTH_FILTER" ref="loginPageFilter"/>
</security:http>
<beans:bean id="loginPageFilter" class="com.baeldung.loginredirect.LoginPageFilter"/>
<mvc:interceptors>
<mvc:interceptor>
<mvc:mapping path="/loginUser"/>
<bean class="com.baeldung.loginredirect.LoginPageInterceptor"/>
</mvc:interceptor>
</mvc:interceptors>
</beans>
@@ -0,0 +1,10 @@
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1" />
<title>Baeldung Login Redirect</title>
</head>
<body>
Welcome user! <a th:href="@{/user_logout}" >Logout</a>
</body>
</html>
@@ -152,7 +152,7 @@
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<version>1.5.10.RELEASE</version>
<version>${spring-boot-starter-test.version}</version>
<scope>test</scope>
</dependency>
</dependencies>
@@ -185,6 +185,7 @@
<spring-security.version>4.2.3.RELEASE</spring-security.version>
<spring-data-jpa.version>1.11.3.RELEASE</spring-data-jpa.version>
<logback-classic.version>1.2.3</logback-classic.version>
<spring-boot-starter-test.version>1.5.10.RELEASE</spring-boot-starter-test.version>
</properties>
</project>
@@ -89,11 +89,6 @@
</dependency>
</dependencies>
<properties>
<spring.mvc.version>5.2.2.RELEASE</spring.mvc.version>
<javax.version>4.0.1</javax.version>
</properties>
<build>
<plugins>
@@ -108,4 +103,9 @@
</plugins>
</build>
<properties>
<spring.mvc.version>5.2.2.RELEASE</spring.mvc.version>
<javax.version>4.0.1</javax.version>
</properties>
</project>
@@ -33,6 +33,8 @@
class="com.baeldung.security.MySavedRequestAwareAuthenticationSuccessHandler" />
<beans:bean id="myFailureHandler"
class="org.springframework.security.web.authentication.SimpleUrlAuthenticationFailureHandler" />
<bean name="encoder"
class="org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder"/>
<authentication-manager alias="authenticationManager">
<authentication-provider>
@@ -1,4 +1,4 @@
## Relevant articles:
- [Spring Security Kerberos Integration](https://www.baeldung.com/spring-security-kerberos-integration)
- [Spring Security Kerberos Integration With MiniKdc](https://www.baeldung.com/spring-security-kerberos-integration)
- [Introduction to SPNEGO/Kerberos Authentication in Spring](https://www.baeldung.com/spring-security-kerberos)
@@ -11,31 +11,6 @@
<version>1.0.0-SNAPSHOT</version>
</parent>
<build>
<resources>
<resource>
<directory>${basedir}/src/main/resources</directory>
<filtering>true</filtering>
<includes>
<include>**/*</include>
</includes>
</resource>
</resources>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-resources-plugin</artifactId>
<version>2.7</version>
<configuration>
<delimiters>
<delimiter>@</delimiter>
</delimiters>
<useDefaultDelimiters>false</useDefaultDelimiters>
</configuration>
</plugin>
</plugins>
</build>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
@@ -92,4 +67,29 @@
</dependency>
</dependencies>
<build>
<resources>
<resource>
<directory>${basedir}/src/main/resources</directory>
<filtering>true</filtering>
<includes>
<include>**/*</include>
</includes>
</resource>
</resources>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-resources-plugin</artifactId>
<version>2.7</version>
<configuration>
<delimiters>
<delimiter>@</delimiter>
</delimiters>
<useDefaultDelimiters>false</useDefaultDelimiters>
</configuration>
</plugin>
</plugins>
</build>
</project>