Skip to content

Commit 5597bf6

Browse files
authored
Merge pull request eugenp#5473 from dkapil/task/BAEL-9467
Task/bael 9467
2 parents 10b4252 + d72429a commit 5597bf6

File tree

14 files changed

+84
-99
lines changed

14 files changed

+84
-99
lines changed

spring-security-rest/pom.xml

Lines changed: 6 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -2,17 +2,16 @@
22
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
33
<modelVersion>4.0.0</modelVersion>
44

5-
<groupId>com.baeldung</groupId>
65
<artifactId>spring-security-rest</artifactId>
76
<version>0.1-SNAPSHOT</version>
87
<name>spring-security-rest</name>
98
<packaging>war</packaging>
109

1110
<parent>
1211
<groupId>com.baeldung</groupId>
13-
<artifactId>parent-spring-4</artifactId>
12+
<artifactId>parent-spring-5</artifactId>
1413
<version>0.0.1-SNAPSHOT</version>
15-
<relativePath>../parent-spring-4</relativePath>
14+
<relativePath>../parent-spring-5</relativePath>
1615
</parent>
1716

1817
<dependencies>
@@ -195,13 +194,6 @@
195194
</resources>
196195

197196
<plugins>
198-
199-
<plugin>
200-
<groupId>org.apache.maven.plugins</groupId>
201-
<artifactId>maven-war-plugin</artifactId>
202-
<version>${maven-war-plugin.version}</version>
203-
</plugin>
204-
205197
<plugin>
206198
<groupId>org.codehaus.cargo</groupId>
207199
<artifactId>cargo-maven2-plugin</artifactId>
@@ -282,17 +274,17 @@
282274

283275
<properties>
284276
<!-- Spring -->
285-
<org.springframework.security.version>4.2.6.RELEASE</org.springframework.security.version>
286-
<org.springframework.hateoas.version>0.21.0.RELEASE</org.springframework.hateoas.version>
277+
<org.springframework.security.version>5.1.0.RELEASE</org.springframework.security.version>
278+
<org.springframework.hateoas.version>0.25.0.RELEASE</org.springframework.hateoas.version>
287279

288280
<!-- various -->
289281
<javax.servlet-api.version>3.1.0</javax.servlet-api.version>
290282
<javax.validation.version>1.1.0.Final</javax.validation.version>
291283
<jstl.version>1.2</jstl.version>
292-
<jackson.version>2.8.5</jackson.version>
284+
<jackson.version>2.9.2</jackson.version>
293285

294286
<!-- util -->
295-
<guava.version>19.0</guava.version>
287+
<guava.version>26.0-jre</guava.version>
296288
<commons-lang3.version>3.5</commons-lang3.version>
297289
<commons-fileupload.version>1.3.2</commons-fileupload.version>
298290

@@ -303,8 +295,6 @@
303295
<springfox-swagger.version>2.9.2</springfox-swagger.version>
304296

305297
<!-- Maven plugins -->
306-
<maven-war-plugin.version>2.6</maven-war-plugin.version>
307298
<cargo-maven2-plugin.version>1.6.1</cargo-maven2-plugin.version>
308299
</properties>
309-
310300
</project>

spring-security-rest/src/main/java/org/baeldung/persistence/model/Foo.java

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,8 @@
66

77
public class Foo implements Serializable {
88

9+
private static final long serialVersionUID = -5422285893276747592L;
10+
911
private long id;
1012

1113
@Size(min = 5, max = 14)

spring-security-rest/src/main/java/org/baeldung/security/MySavedRequestAwareAuthenticationSuccessHandler.java

Lines changed: 2 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -11,8 +11,10 @@
1111
import org.springframework.security.web.savedrequest.HttpSessionRequestCache;
1212
import org.springframework.security.web.savedrequest.RequestCache;
1313
import org.springframework.security.web.savedrequest.SavedRequest;
14+
import org.springframework.stereotype.Component;
1415
import org.springframework.util.StringUtils;
1516

17+
@Component
1618
public class MySavedRequestAwareAuthenticationSuccessHandler extends SimpleUrlAuthenticationSuccessHandler {
1719

1820
private RequestCache requestCache = new HttpSessionRequestCache();
@@ -33,11 +35,6 @@ public void onAuthenticationSuccess(final HttpServletRequest request, final Http
3335
}
3436

3537
clearAuthenticationAttributes(request);
36-
37-
// Use the DefaultSavedRequest URL
38-
// final String targetUrl = savedRequest.getRedirectUrl();
39-
// logger.debug("Redirecting to DefaultSavedRequest Url: " + targetUrl);
40-
// getRedirectStrategy().sendRedirect(request, response, targetUrl);
4138
}
4239

4340
public void setRequestCache(final RequestCache requestCache) {

spring-security-rest/src/main/java/org/baeldung/security/RestAuthenticationEntryPoint.java

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -16,7 +16,11 @@
1616
public final class RestAuthenticationEntryPoint implements AuthenticationEntryPoint {
1717

1818
@Override
19-
public void commence(final HttpServletRequest request, final HttpServletResponse response, final AuthenticationException authException) throws IOException {
19+
public void commence(
20+
final HttpServletRequest request,
21+
final HttpServletResponse response,
22+
final AuthenticationException authException) throws IOException {
23+
2024
response.sendError(HttpServletResponse.SC_UNAUTHORIZED, "Unauthorized");
2125
}
2226

spring-security-rest/src/main/java/org/baeldung/spring/ClientWebConfig.java

Lines changed: 2 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -2,16 +2,9 @@
22

33
import org.springframework.context.annotation.Configuration;
44
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
5-
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;
5+
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
66

77
@EnableWebMvc
88
@Configuration
9-
public class ClientWebConfig extends WebMvcConfigurerAdapter {
10-
11-
public ClientWebConfig() {
12-
super();
13-
}
14-
15-
// API
16-
9+
public class ClientWebConfig implements WebMvcConfigurer {
1710
}
Lines changed: 38 additions & 36 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
11
package org.baeldung.spring;
22

33
import org.baeldung.security.MySavedRequestAwareAuthenticationSuccessHandler;
4+
import org.baeldung.security.RestAuthenticationEntryPoint;
45
import org.baeldung.web.error.CustomAccessDeniedHandler;
56
import org.springframework.beans.factory.annotation.Autowired;
67
import org.springframework.context.annotation.Bean;
@@ -12,6 +13,8 @@
1213
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
1314
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
1415
import org.springframework.security.core.context.SecurityContextHolder;
16+
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
17+
import org.springframework.security.crypto.password.PasswordEncoder;
1518
import org.springframework.security.web.authentication.SimpleUrlAuthenticationFailureHandler;
1619

1720
@Configuration
@@ -23,56 +26,55 @@ public class SecurityJavaConfig extends WebSecurityConfigurerAdapter {
2326
@Autowired
2427
private CustomAccessDeniedHandler accessDeniedHandler;
2528

26-
// @Autowired
27-
// private RestAuthenticationEntryPoint restAuthenticationEntryPoint;
29+
@Autowired
30+
private RestAuthenticationEntryPoint restAuthenticationEntryPoint;
31+
32+
@Autowired
33+
private MySavedRequestAwareAuthenticationSuccessHandler mySuccessHandler;
2834

29-
// @Autowired
30-
// private MySavedRequestAwareAuthenticationSuccessHandler authenticationSuccessHandler;
35+
private SimpleUrlAuthenticationFailureHandler myFailureHandler = new SimpleUrlAuthenticationFailureHandler();
3136

3237
public SecurityJavaConfig() {
3338
super();
3439
SecurityContextHolder.setStrategyName(SecurityContextHolder.MODE_INHERITABLETHREADLOCAL);
3540
}
3641

37-
//
38-
3942
@Override
4043
protected void configure(final AuthenticationManagerBuilder auth) throws Exception {
41-
auth.inMemoryAuthentication().withUser("temporary").password("temporary").roles("ADMIN").and().withUser("user").password("userPass").roles("USER");
44+
auth.inMemoryAuthentication()
45+
.withUser("admin").password(encoder().encode("adminPass")).roles("ADMIN")
46+
.and()
47+
.withUser("user").password(encoder().encode("userPass")).roles("USER");
4248
}
4349

4450
@Override
45-
protected void configure(final HttpSecurity http) throws Exception {// @formatter:off
46-
http
47-
.csrf().disable()
48-
.authorizeRequests()
49-
.and()
50-
.exceptionHandling().accessDeniedHandler(accessDeniedHandler)
51-
// .authenticationEntryPoint(restAuthenticationEntryPoint)
52-
.and()
53-
.authorizeRequests()
54-
.antMatchers("/api/csrfAttacker*").permitAll()
55-
.antMatchers("/api/customer/**").permitAll()
56-
.antMatchers("/api/foos/**").authenticated()
57-
.antMatchers("/api/async/**").permitAll()
58-
.antMatchers("/api/admin/**").hasRole("ADMIN")
59-
.and()
60-
.httpBasic()
61-
// .and()
62-
// .successHandler(authenticationSuccessHandler)
63-
// .failureHandler(new SimpleUrlAuthenticationFailureHandler())
64-
.and()
65-
.logout();
66-
} // @formatter:on
67-
68-
@Bean
69-
public MySavedRequestAwareAuthenticationSuccessHandler mySuccessHandler() {
70-
return new MySavedRequestAwareAuthenticationSuccessHandler();
51+
protected void configure(final HttpSecurity http) throws Exception {
52+
http.csrf().disable()
53+
.authorizeRequests()
54+
.and()
55+
.exceptionHandling()
56+
.accessDeniedHandler(accessDeniedHandler)
57+
.authenticationEntryPoint(restAuthenticationEntryPoint)
58+
.and()
59+
.authorizeRequests()
60+
.antMatchers("/api/csrfAttacker*").permitAll()
61+
.antMatchers("/api/customer/**").permitAll()
62+
.antMatchers("/api/foos/**").authenticated()
63+
.antMatchers("/api/async/**").permitAll()
64+
.antMatchers("/api/admin/**").hasRole("ADMIN")
65+
.and()
66+
.formLogin()
67+
.successHandler(mySuccessHandler)
68+
.failureHandler(myFailureHandler)
69+
.and()
70+
.httpBasic()
71+
.and()
72+
.logout();
7173
}
72-
74+
7375
@Bean
74-
public SimpleUrlAuthenticationFailureHandler myFailureHandler() {
75-
return new SimpleUrlAuthenticationFailureHandler();
76+
public PasswordEncoder encoder() {
77+
return new BCryptPasswordEncoder();
7678
}
7779

7880
}

spring-security-rest/src/main/java/org/baeldung/spring/SwaggerConfig.java

Lines changed: 13 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -24,8 +24,19 @@ public class SwaggerConfig {
2424

2525
@Bean
2626
public Docket api() {
27-
return new Docket(DocumentationType.SWAGGER_2).select().apis(RequestHandlerSelectors.basePackage("org.baeldung.web.controller")).paths(PathSelectors.ant("/foos/*")).build().apiInfo(apiInfo()).useDefaultResponseMessages(false)
28-
.globalResponseMessage(RequestMethod.GET, newArrayList(new ResponseMessageBuilder().code(500).message("500 message").responseModel(new ModelRef("Error")).build(), new ResponseMessageBuilder().code(403).message("Forbidden!!!!!").build()));
27+
return new Docket(DocumentationType.SWAGGER_2).select()
28+
.apis(RequestHandlerSelectors.basePackage("org.baeldung.web.controller"))
29+
.paths(PathSelectors.ant("/foos/*"))
30+
.build()
31+
.apiInfo(apiInfo())
32+
.useDefaultResponseMessages(false)
33+
.globalResponseMessage(RequestMethod.GET, newArrayList(new ResponseMessageBuilder().code(500)
34+
.message("500 message")
35+
.responseModel(new ModelRef("Error"))
36+
.build(),
37+
new ResponseMessageBuilder().code(403)
38+
.message("Forbidden!!!!!")
39+
.build()));
2940
}
3041

3142
private ApiInfo apiInfo() {

spring-security-rest/src/main/java/org/baeldung/spring/WebConfig.java

Lines changed: 2 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -8,18 +8,14 @@
88
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
99
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
1010
import org.springframework.web.servlet.config.annotation.ViewControllerRegistry;
11-
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;
11+
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
1212
import org.springframework.web.servlet.view.InternalResourceViewResolver;
1313

1414
@Configuration
1515
@ComponentScan("org.baeldung.web")
1616
@EnableWebMvc
1717
@EnableAsync
18-
public class WebConfig extends WebMvcConfigurerAdapter {
19-
20-
public WebConfig() {
21-
super();
22-
}
18+
public class WebConfig implements WebMvcConfigurer {
2319

2420
@Override
2521
public void addResourceHandlers(final ResourceHandlerRegistry registry) {
@@ -38,7 +34,6 @@ public ViewResolver viewResolver() {
3834

3935
@Override
4036
public void addViewControllers(final ViewControllerRegistry registry) {
41-
super.addViewControllers(registry);
4237
registry.addViewController("/csrfAttacker.html");
4338
}
4439

spring-security-rest/src/main/java/org/baeldung/web/controller/AsyncController.java

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -24,9 +24,9 @@ public class AsyncController {
2424
@RequestMapping(method = RequestMethod.GET, value = "/async")
2525
@ResponseBody
2626
public Object standardProcessing() throws Exception {
27-
log.info("Outside the @Async logic - before the async call: " + SecurityContextHolder.getContext().getAuthentication().getPrincipal());
27+
log.info("Outside the @Async logic - before the async call: {}", SecurityContextHolder.getContext().getAuthentication().getPrincipal());
2828
asyncService.asyncCall();
29-
log.info("Inside the @Async logic - after the async call: " + SecurityContextHolder.getContext().getAuthentication().getPrincipal());
29+
log.info("Inside the @Async logic - after the async call: {}", SecurityContextHolder.getContext().getAuthentication().getPrincipal());
3030
return SecurityContextHolder.getContext().getAuthentication().getPrincipal();
3131
}
3232

spring-security-rest/src/main/java/org/baeldung/web/controller/CustomerController.java

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -48,7 +48,7 @@ public Resources<Order> getOrdersForCustomer(@PathVariable final String customer
4848
}
4949

5050
Link link =linkTo(methodOn(CustomerController.class).getOrdersForCustomer(customerId)).withSelfRel();
51-
Resources<Order> result = new Resources<Order>(orders,link);
51+
Resources<Order> result = new Resources<>(orders,link);
5252
return result;
5353
}
5454

@@ -67,7 +67,7 @@ public Resources<Customer> getAllCustomers() {
6767
}
6868

6969
Link link =linkTo(CustomerController.class).withSelfRel();
70-
Resources<Customer> result = new Resources<Customer>(allCustomers,link);
70+
Resources<Customer> result = new Resources<>(allCustomers,link);
7171
return result;
7272
}
7373

0 commit comments

Comments
 (0)