Skip to content

Commit 8844871

Browse files
authored
@async and SecurityContext (eugenp#872)
* @async and Spring Security * @async with SecurityContext propagated * Spring and @async * Simulated Annealing algorithm * Rebase * Rebase
1 parent 0087a4a commit 8844871

File tree

6 files changed

+126
-31
lines changed

6 files changed

+126
-31
lines changed
Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,13 @@
1+
package com.baeldung.algorithms;
2+
3+
import org.junit.Assert;
4+
import org.junit.Test;
5+
6+
public class SimulatedAnnealingTest {
7+
8+
@Test
9+
public void testSimulateAnnealing() {
10+
Assert.assertTrue(SimulatedAnnealing.simulateAnnealing(10, 1000, 0.9) > 0);
11+
}
12+
13+
}

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

Lines changed: 23 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -1,27 +1,27 @@
11
package org.baeldung.spring;
22

33
import org.baeldung.security.MySavedRequestAwareAuthenticationSuccessHandler;
4-
import org.baeldung.security.RestAuthenticationEntryPoint;
5-
import org.springframework.beans.factory.annotation.Autowired;
4+
import org.springframework.beans.factory.config.MethodInvokingFactoryBean;
65
import org.springframework.context.annotation.Bean;
76
import org.springframework.context.annotation.ComponentScan;
87
import org.springframework.context.annotation.Configuration;
98
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
109
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
1110
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
1211
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
12+
import org.springframework.security.core.context.SecurityContextHolder;
1313
import org.springframework.security.web.authentication.SimpleUrlAuthenticationFailureHandler;
1414

1515
@Configuration
1616
@EnableWebSecurity
1717
@ComponentScan("org.baeldung.security")
1818
public class SecurityJavaConfig extends WebSecurityConfigurerAdapter {
1919

20-
@Autowired
21-
private RestAuthenticationEntryPoint restAuthenticationEntryPoint;
20+
// @Autowired
21+
// private RestAuthenticationEntryPoint restAuthenticationEntryPoint;
2222

23-
@Autowired
24-
private MySavedRequestAwareAuthenticationSuccessHandler authenticationSuccessHandler;
23+
// @Autowired
24+
// private MySavedRequestAwareAuthenticationSuccessHandler authenticationSuccessHandler;
2525

2626
public SecurityJavaConfig() {
2727
super();
@@ -38,17 +38,21 @@ protected void configure(final AuthenticationManagerBuilder auth) throws Excepti
3838
protected void configure(final HttpSecurity http) throws Exception {// @formatter:off
3939
http
4040
.csrf().disable()
41+
.authorizeRequests()
42+
.and()
4143
.exceptionHandling()
42-
.authenticationEntryPoint(restAuthenticationEntryPoint)
44+
// .authenticationEntryPoint(restAuthenticationEntryPoint)
4345
.and()
4446
.authorizeRequests()
4547
.antMatchers("/api/csrfAttacker*").permitAll()
4648
.antMatchers("/api/customer/**").permitAll()
4749
.antMatchers("/api/foos/**").authenticated()
50+
.antMatchers("/api/async/**").authenticated()
4851
.and()
49-
.formLogin()
50-
.successHandler(authenticationSuccessHandler)
51-
.failureHandler(new SimpleUrlAuthenticationFailureHandler())
52+
.httpBasic()
53+
// .and()
54+
// .successHandler(authenticationSuccessHandler)
55+
// .failureHandler(new SimpleUrlAuthenticationFailureHandler())
5256
.and()
5357
.logout();
5458
} // @formatter:on
@@ -62,5 +66,14 @@ public MySavedRequestAwareAuthenticationSuccessHandler mySuccessHandler() {
6266
public SimpleUrlAuthenticationFailureHandler myFailureHandler() {
6367
return new SimpleUrlAuthenticationFailureHandler();
6468
}
69+
70+
@Bean
71+
public MethodInvokingFactoryBean methodInvokingFactoryBean() {
72+
MethodInvokingFactoryBean methodInvokingFactoryBean = new MethodInvokingFactoryBean();
73+
methodInvokingFactoryBean.setTargetClass(SecurityContextHolder.class);
74+
methodInvokingFactoryBean.setTargetMethod("setStrategyName");
75+
methodInvokingFactoryBean.setArguments(new String[]{SecurityContextHolder.MODE_INHERITABLETHREADLOCAL});
76+
return methodInvokingFactoryBean;
77+
}
6578

6679
}

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

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2,13 +2,20 @@
22

33
import java.util.concurrent.Callable;
44

5+
import org.baeldung.web.service.AsyncService;
6+
import org.springframework.beans.factory.annotation.Autowired;
7+
import org.springframework.security.core.context.SecurityContextHolder;
58
import org.springframework.stereotype.Controller;
69
import org.springframework.web.bind.annotation.RequestMapping;
710
import org.springframework.web.bind.annotation.RequestMethod;
11+
import org.springframework.web.bind.annotation.ResponseBody;
812
import org.springframework.web.multipart.MultipartFile;
913

1014
@Controller
1115
public class AsyncController {
16+
17+
@Autowired
18+
private AsyncService asyncService;
1219

1320
@RequestMapping(method = RequestMethod.POST, value = "/upload")
1421
public Callable<Boolean> processUpload(final MultipartFile file) {
@@ -20,5 +27,11 @@ public Boolean call() throws Exception {
2027
}
2128
};
2229
}
30+
31+
@RequestMapping(method = RequestMethod.GET, value = "/async")
32+
@ResponseBody
33+
public Boolean checkIfContextPropagated() throws Exception{
34+
return asyncService.checkIfPrincipalPropagated().call() && asyncService.checkIfContextPropagated(SecurityContextHolder.getContext());
35+
}
2336

2437
}
Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,11 @@
1+
package org.baeldung.web.service;
2+
3+
import java.util.concurrent.Callable;
4+
5+
public interface AsyncService {
6+
7+
Callable<Boolean> checkIfPrincipalPropagated();
8+
9+
Boolean checkIfContextPropagated(Object context);
10+
11+
}
Lines changed: 36 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,36 @@
1+
package org.baeldung.web.service;
2+
3+
import java.util.concurrent.Callable;
4+
5+
import org.apache.log4j.Logger;
6+
import org.springframework.scheduling.annotation.Async;
7+
import org.springframework.security.core.context.SecurityContextHolder;
8+
import org.springframework.stereotype.Service;
9+
10+
@Service
11+
public class AsyncServiceImpl implements AsyncService {
12+
13+
private static final Logger log = Logger.getLogger(AsyncService.class);
14+
15+
@Override
16+
public Callable<Boolean> checkIfPrincipalPropagated() {
17+
Object before = SecurityContextHolder.getContext().getAuthentication().getPrincipal();
18+
log.info("Before new thread: " + before);
19+
return new Callable<Boolean>() {
20+
public Boolean call() throws Exception {
21+
Object after = SecurityContextHolder.getContext().getAuthentication().getPrincipal();
22+
log.info("New thread: " + after);
23+
return before == after;
24+
}
25+
};
26+
}
27+
28+
@Async
29+
@Override
30+
public Boolean checkIfContextPropagated(Object context) {
31+
log.info("Before @Async: " + context);
32+
log.info("Inside @Async: " + SecurityContextHolder.getContext());
33+
return context == SecurityContextHolder.getContext();
34+
}
35+
36+
}
Lines changed: 30 additions & 21 deletions
Original file line numberDiff line numberDiff line change
@@ -1,33 +1,42 @@
11
<?xml version="1.0" encoding="UTF-8"?>
2-
<beans:beans xmlns="http://www.springframework.org/schema/security" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:beans="http://www.springframework.org/schema/beans"
3-
xmlns:sec="http://www.springframework.org/schema/security"
4-
xsi:schemaLocation="
2+
<beans:beans xmlns="http://www.springframework.org/schema/security"
3+
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:beans="http://www.springframework.org/schema/beans"
4+
xmlns:sec="http://www.springframework.org/schema/security"
5+
xmlns:p="http://www.springframework.org/schema/p"
6+
xsi:schemaLocation="
57
http://www.springframework.org/schema/security
68
http://www.springframework.org/schema/security/spring-security-4.2.xsd
79
http://www.springframework.org/schema/beans
8-
http://www.springframework.org/schema/beans/spring-beans-4.3.xsd"
9-
>
10+
http://www.springframework.org/schema/beans/spring-beans-4.2.xsd">
1011

11-
<http use-expressions="true" entry-point-ref="restAuthenticationEntryPoint">
12-
<intercept-url pattern="/api/**" access="isAuthenticated()"/>
12+
<http use-expressions="true" entry-point-ref="restAuthenticationEntryPoint">
13+
<intercept-url pattern="/api/**" access="isAuthenticated()" />
1314

14-
<csrf disabled="true"/>
15+
<csrf disabled="true" />
1516

16-
<form-login authentication-success-handler-ref="mySuccessHandler" authentication-failure-handler-ref="myFailureHandler"/>
17+
<form-login authentication-success-handler-ref="mySuccessHandler"
18+
authentication-failure-handler-ref="myFailureHandler" />
1719

18-
<logout/>
19-
</http>
20+
<logout />
21+
</http>
2022

21-
<beans:bean id="mySuccessHandler" class="org.baeldung.security.MySavedRequestAwareAuthenticationSuccessHandler"/>
22-
<beans:bean id="myFailureHandler" class="org.springframework.security.web.authentication.SimpleUrlAuthenticationFailureHandler"/>
23+
<beans:bean id="mySuccessHandler"
24+
class="org.baeldung.security.MySavedRequestAwareAuthenticationSuccessHandler" />
25+
<beans:bean id="myFailureHandler"
26+
class="org.springframework.security.web.authentication.SimpleUrlAuthenticationFailureHandler" />
2327

24-
<authentication-manager alias="authenticationManager">
25-
<authentication-provider>
26-
<user-service>
27-
<user name="temporary" password="temporary" authorities="ROLE_ADMIN"/>
28-
<user name="user" password="userPass" authorities="ROLE_USER"/>
29-
</user-service>
30-
</authentication-provider>
31-
</authentication-manager>
28+
<authentication-manager alias="authenticationManager">
29+
<authentication-provider>
30+
<user-service>
31+
<user name="temporary" password="temporary" authorities="ROLE_ADMIN" />
32+
<user name="user" password="userPass" authorities="ROLE_USER" />
33+
</user-service>
34+
</authentication-provider>
35+
</authentication-manager>
36+
37+
<beans:bean
38+
class="org.springframework.beans.factory.config.MethodInvoki‌​ngFactoryBean"
39+
p:targetClass="org.springframework.security.core.context.Sec‌​urityContextHolder"
40+
p:targetMethod="setStrategyName" p:arguments="MODE_INHERITABLETHREADLOCAL" />
3241

3342
</beans:beans>

0 commit comments

Comments
 (0)