JAVA-29330: Migrate spring-security-web-rest-custom to parent-boot-3. (#15932)

This commit is contained in:
Harry9656 2024-02-21 20:37:27 +01:00 committed by GitHub
parent 63399a9560
commit 6aff5d5c66
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
20 changed files with 111 additions and 179 deletions

View File

@ -10,8 +10,9 @@
<parent>
<groupId>com.baeldung</groupId>
<artifactId>spring-security-modules</artifactId>
<artifactId>parent-boot-3</artifactId>
<version>0.0.1-SNAPSHOT</version>
<relativePath>../../parent-boot-3</relativePath>
</parent>
<dependencies>
@ -26,11 +27,11 @@
</dependency>
<dependency>
<groupId>org.thymeleaf.extras</groupId>
<artifactId>thymeleaf-extras-springsecurity5</artifactId>
<artifactId>thymeleaf-extras-springsecurity6</artifactId>
</dependency>
<dependency>
<groupId>org.thymeleaf</groupId>
<artifactId>thymeleaf-spring5</artifactId>
<artifactId>thymeleaf-spring6</artifactId>
</dependency>
<!-- Spring -->
<dependency>
@ -85,23 +86,24 @@
</dependency>
<!-- web -->
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<groupId>jakarta.servlet</groupId>
<artifactId>jakarta.servlet-api</artifactId>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>jstl</artifactId>
<groupId>jakarta.servlet.jsp.jstl</groupId>
<artifactId>jakarta.servlet.jsp.jstl-api</artifactId>
<scope>runtime</scope>
</dependency>
<!-- http -->
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpcore</artifactId>
<groupId>org.apache.httpcomponents.core5</groupId>
<artifactId>httpcore5</artifactId>
</dependency>
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpclient</artifactId>
<groupId>org.apache.httpcomponents.client5</groupId>
<artifactId>httpclient5</artifactId>
</dependency>
<!-- util -->
<dependency>

View File

@ -2,36 +2,28 @@ package com.baeldung.config;
import java.util.Set;
import javax.servlet.FilterRegistration.Dynamic;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.ServletRegistration;
import org.springframework.web.WebApplicationInitializer;
import org.springframework.web.context.ContextLoaderListener;
import org.springframework.web.context.support.AnnotationConfigWebApplicationContext;
import org.springframework.web.filter.DelegatingFilterProxy;
import org.springframework.web.servlet.DispatcherServlet;
import jakarta.servlet.FilterRegistration.Dynamic;
import jakarta.servlet.ServletContext;
import jakarta.servlet.ServletRegistration;
public class MainWebAppInitializer implements WebApplicationInitializer {
public MainWebAppInitializer() {
super();
}
//
/**
* Register and configure all Servlet container components necessary to power the web application.
*/
@Override
public void onStartup(final ServletContext sc) throws ServletException {
public void onStartup(final ServletContext sc) {
System.out.println("MyWebAppInitializer.onStartup()");
// Create the 'root' Spring application context
final AnnotationConfigWebApplicationContext root = new AnnotationConfigWebApplicationContext();
root.scan("com.baeldung.config.parent");
// root.getEnvironment().setDefaultProfiles("embedded");
// Manages the lifecycle of the root application context
sc.addListener(new ContextLoaderListener(root));

View File

@ -8,15 +8,14 @@ import org.springframework.security.access.intercept.RunAsManager;
import org.springframework.security.access.intercept.RunAsManagerImpl;
import org.springframework.security.authentication.AuthenticationProvider;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.config.annotation.method.configuration.GlobalMethodSecurityConfiguration;
import org.springframework.security.config.annotation.method.configuration.EnableMethodSecurity;
@Configuration
@EnableGlobalMethodSecurity(securedEnabled = true)
public class MethodSecurityConfig extends GlobalMethodSecurityConfiguration {
@EnableMethodSecurity(securedEnabled = true)
public class MethodSecurityConfig {
@Override
@Bean
protected RunAsManager runAsManager() {
RunAsManagerImpl runAsManager = new RunAsManagerImpl();
runAsManager.setKey("MyRunAsKey");
@ -24,7 +23,7 @@ public class MethodSecurityConfig extends GlobalMethodSecurityConfiguration {
}
@Autowired
public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
public void configureGlobal(AuthenticationManagerBuilder auth) {
auth.authenticationProvider(runAsAuthenticationProvider());
}

View File

@ -2,7 +2,6 @@ package com.baeldung.config.child;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
@ -13,37 +12,31 @@ import org.springframework.http.converter.json.MappingJackson2HttpMessageConvert
import org.springframework.web.servlet.ViewResolver;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
import org.thymeleaf.extras.springsecurity5.dialect.SpringSecurityDialect;
import org.thymeleaf.spring5.ISpringTemplateEngine;
import org.thymeleaf.spring5.SpringTemplateEngine;
import org.thymeleaf.spring5.templateresolver.SpringResourceTemplateResolver;
import org.thymeleaf.spring5.view.ThymeleafViewResolver;
import org.thymeleaf.extras.springsecurity6.dialect.SpringSecurityDialect;
import org.thymeleaf.spring6.ISpringTemplateEngine;
import org.thymeleaf.spring6.SpringTemplateEngine;
import org.thymeleaf.spring6.templateresolver.SpringResourceTemplateResolver;
import org.thymeleaf.spring6.view.ThymeleafViewResolver;
import org.thymeleaf.templatemode.TemplateMode;
import org.thymeleaf.templateresolver.ITemplateResolver;
@Configuration
@EnableWebMvc
@ComponentScan("com.baeldung.web")
//@ImportResource({ "classpath:prop.xml" })
//@PropertySource("classpath:foo.properties")
public class WebConfig implements WebMvcConfigurer {
@Autowired
private ApplicationContext applicationContext;
public WebConfig() {
private final ApplicationContext applicationContext;
public WebConfig(ApplicationContext applicationContext) {
super();
this.applicationContext = applicationContext;
}
// beans
@Override
public void configureMessageConverters(final List<HttpMessageConverter<?>> converters) {
converters.add(new MappingJackson2HttpMessageConverter());
}
// beans
@Bean
public static PropertySourcesPlaceholderConfigurer propertySourcesPlaceholderConfigurer() {
final PropertySourcesPlaceholderConfigurer ppc = new PropertySourcesPlaceholderConfigurer();

View File

@ -1,10 +1,10 @@
package com.baeldung.config.parent;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.config.Customizer;
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;
@ -18,8 +18,11 @@ import com.baeldung.security.CustomAuthenticationProvider;
@ComponentScan("com.baeldung.security")
public class SecurityConfig {
@Autowired
private CustomAuthenticationProvider authProvider;
private final CustomAuthenticationProvider authProvider;
public SecurityConfig(CustomAuthenticationProvider authProvider) {
this.authProvider = authProvider;
}
@Bean
public AuthenticationManager authManager(HttpSecurity http) throws Exception {
@ -30,12 +33,9 @@ public class SecurityConfig {
@Bean
public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
http.authorizeRequests()
.anyRequest()
.authenticated()
.and()
.httpBasic();
return http.build();
return http.authorizeHttpRequests(request -> request.anyRequest()
.authenticated())
.httpBasic(Customizer.withDefaults())
.build();
}
}

View File

@ -12,12 +12,6 @@ import org.springframework.context.support.PropertySourcesPlaceholderConfigurer;
@PropertySource("classpath:foo.properties")
public class ServiceConfig {
public ServiceConfig() {
super();
}
// beans
@Bean
public static PropertySourcesPlaceholderConfigurer propertySourcesPlaceholderConfigurer() {
final PropertySourcesPlaceholderConfigurer ppc = new PropertySourcesPlaceholderConfigurer();

View File

@ -11,8 +11,6 @@ public class AuthenticationFacade implements IAuthenticationFacade {
super();
}
// API
@Override
public final Authentication getAuthentication() {
return SecurityContextHolder.getContext().getAuthentication();

View File

@ -20,21 +20,21 @@ public class CustomAuthenticationProvider implements AuthenticationProvider {
super();
}
// API
@Override
public Authentication authenticate(final Authentication authentication) throws AuthenticationException {
final String name = authentication.getName();
final String password = authentication.getCredentials().toString();
if (name.equals("admin") && password.equals("system")) {
final List<GrantedAuthority> grantedAuths = new ArrayList<>();
grantedAuths.add(new SimpleGrantedAuthority("ROLE_USER"));
final UserDetails principal = new User(name, password, grantedAuths);
final Authentication auth = new UsernamePasswordAuthenticationToken(principal, password, grantedAuths);
return auth;
} else {
if (!"admin".equals(name) || !"system".equals(password)) {
return null;
}
return authenticateAgainstThirdPartyAndGetAuthentication(name, password);
}
private static UsernamePasswordAuthenticationToken authenticateAgainstThirdPartyAndGetAuthentication(String name, String password) {
final List<GrantedAuthority> grantedAuths = new ArrayList<>();
grantedAuths.add(new SimpleGrantedAuthority("ROLE_USER"));
final UserDetails principal = new User(name, password, grantedAuths);
return new UsernamePasswordAuthenticationToken(principal, password, grantedAuths);
}
@Override

View File

@ -2,10 +2,6 @@ package com.baeldung.security;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.authentication.SimpleUrlAuthenticationSuccessHandler;
import org.springframework.security.web.savedrequest.HttpSessionRequestCache;
@ -13,6 +9,10 @@ import org.springframework.security.web.savedrequest.RequestCache;
import org.springframework.security.web.savedrequest.SavedRequest;
import org.springframework.util.StringUtils;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
public class MySavedRequestAwareAuthenticationSuccessHandler extends SimpleUrlAuthenticationSuccessHandler {
private RequestCache requestCache = new HttpSessionRequestCache();

View File

@ -2,13 +2,13 @@ package com.baeldung.security;
import java.io.IOException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.AuthenticationEntryPoint;
import org.springframework.stereotype.Component;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
/**
* The Entry Point will not redirect to any sort of Login - it will return the 401
*/

View File

@ -1,27 +1,25 @@
package com.baeldung.service;
import com.baeldung.web.dto.Foo;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.env.Environment;
import org.springframework.stereotype.Service;
import com.baeldung.web.dto.Foo;
@Service
public class FooService implements IFooService, InitializingBean {
@Value("${foo1}")
private String foo1;
@Autowired
private Environment env;
private final Environment env;
public FooService() {
public FooService(Environment env) {
super();
this.env = env;
}
// API
@Override
public Foo findOne(final Long id) {
return new Foo();

View File

@ -10,8 +10,7 @@ public class RunAsService {
@Secured({ "ROLE_RUN_AS_REPORTER" })
public Authentication getCurrentUser() {
Authentication authentication =
SecurityContextHolder.getContext().getAuthentication();
return authentication;
return SecurityContextHolder.getContext()
.getAuthentication();
}
}

View File

@ -1,39 +1,34 @@
package com.baeldung.web.controller;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.env.Environment;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.baeldung.service.IFooService;
import com.baeldung.web.dto.Foo;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.env.Environment;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
@Controller
@RestController
@RequestMapping(value = "/foos")
public class FooController implements InitializingBean {
@Value("${foo1}")
private String foo1;
@Autowired
private Environment env;
private final Environment env;
private final IFooService service;
@Autowired
private IFooService service;
public FooController() {
public FooController(Environment env, IFooService service) {
super();
this.env = env;
this.service = service;
}
// API
@RequestMapping(value = "/{id}", method = RequestMethod.GET)
@ResponseBody
public Foo findOne(@PathVariable("id") final Long id) {
@GetMapping(value = "/{id}")
public Foo findOne(@PathVariable(name = "id") final Long id) {
return service.findOne(id);
}

View File

@ -2,22 +2,17 @@ package com.baeldung.web.controller;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
@Controller
@RestController
public class GetUserWithAuthenticationController {
public GetUserWithAuthenticationController() {
super();
}
// API
@RequestMapping(value = "/username3", method = RequestMethod.GET)
@ResponseBody
@GetMapping(value = "/username3")
public String currentUserNameSimple(final Authentication authentication) {
UserDetails userDetails = (UserDetails) authentication.getPrincipal();
System.out.println("Retrieved user with authorities: " + userDetails.getAuthorities());

View File

@ -1,27 +1,22 @@
package com.baeldung.web.controller;
import com.baeldung.security.IAuthenticationFacade;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
@Controller
import com.baeldung.security.IAuthenticationFacade;
@RestController
public class GetUserWithCustomInterfaceController {
@Autowired
private IAuthenticationFacade authenticationFacade;
private final IAuthenticationFacade authenticationFacade;
public GetUserWithCustomInterfaceController() {
public GetUserWithCustomInterfaceController(IAuthenticationFacade authenticationFacade) {
super();
this.authenticationFacade = authenticationFacade;
}
// API
@RequestMapping(value = "/username5", method = RequestMethod.GET)
@ResponseBody
@GetMapping(value = "/username5")
public String currentUserNameSimple() {
final Authentication authentication = authenticationFacade.getAuthentication();
return authentication.getName();

View File

@ -2,24 +2,19 @@ package com.baeldung.web.controller;
import java.security.Principal;
import javax.servlet.http.HttpServletRequest;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import jakarta.servlet.http.HttpServletRequest;
@Controller
@RestController
public class GetUserWithHTTPServletRequestController {
public GetUserWithHTTPServletRequestController() {
super();
}
// API
@RequestMapping(value = "/username4", method = RequestMethod.GET)
@ResponseBody
@GetMapping(value = "/username4")
public String currentUserNameSimple(final HttpServletRequest request) {
final Principal principal = request.getUserPrincipal();
return principal.getName();

View File

@ -2,22 +2,17 @@ package com.baeldung.web.controller;
import java.security.Principal;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
@Controller
@RestController
public class GetUserWithPrincipalController {
public GetUserWithPrincipalController() {
super();
}
// API
@RequestMapping(value = "/username2", method = RequestMethod.GET)
@ResponseBody
@GetMapping(value = "/username2")
public String currentUserName(final Principal principal) {
return principal.getName();
}

View File

@ -1,29 +1,15 @@
package com.baeldung.web.controller;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationEventPublisher;
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.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
@Controller
@RestController
public class GetUserWithSecurityContextHolderController {
@Autowired
private ApplicationEventPublisher eventPublisher;
public GetUserWithSecurityContextHolderController() {
super();
}
// API
@RequestMapping(value = "/username1", method = RequestMethod.GET)
@ResponseBody
@GetMapping(value = "/username1")
public String currentUserName() {
final Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
if (!(authentication instanceof AnonymousAuthenticationToken)) {

View File

@ -3,18 +3,15 @@ package com.baeldung.web.controller;
import org.springframework.security.access.annotation.Secured;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
@Controller
@RestController
@RequestMapping("/runas")
public class RunAsController {
@Secured({ "ROLE_USER", "RUN_AS_REPORTER" })
@RequestMapping
@ResponseBody
public String tryRunAs() {
Authentication auth = SecurityContextHolder.getContext().getAuthentication();
return "Current User Authorities inside this RunAS method only " +

View File

@ -1,6 +1,5 @@
<!DOCTYPE html>
<html xmlns:th="https://www.thymeleaf.org"
xmlns:sec="https://www.thymeleaf.org/thymeleaf-extras-springsecurity5">
<html xmlns:sec="https://www.thymeleaf.org">
<body>
Current user authorities:
<span sec:authentication="principal.authorities">user</span>
@ -9,7 +8,7 @@
<a href="#" onclick="tryRunAs()">Generate Report As Super User</a>
<script
src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script>
src="https://ajax.googleapis.com/ajax/libs/jquery/3.7.1/jquery.min.js"></script>
<script type="text/javascript">
function tryRunAs(){