Bonjour a tous, je suis en train de faire des tests intégrés pour une application, je dois tester les contrôleurs qui sont sécurité par spring-security-oauth2.
Mon app n'est pas sur Spring boot (ca s'est un gros problème car tout les exemples que je vois utilise String boot)
J'ai comme exemple Baeldung\spring-security-oauth(https://github.com/Baeldung/spring-security-oauth.git) qui utilise spring boot

La j'ai un 412 apres avoir recu le token

voici mon code
Code : Sélectionner tout - Visualiser dans une fenêtre à part
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
 
 
@RunWith(SpringRunner.class)
@ContextConfiguration(locations = { "classpath:applicationContextIT.xml" })
@WebAppConfiguration
@TestExecutionListeners({ DependencyInjectionTestExecutionListener.class, DirtiesContextTestExecutionListener.class,
		TransactionalTestExecutionListener.class, DbUnitTestExecutionListener.class })
@OAuth2ContextConfiguration(MyDetails.class)
public abstract class OAuthITTest {
 
	@Autowired
	private WebApplicationContext webApplicationContext;
	public MockMvc mockMvc;
 
	@Autowired
	private UserService userService;
 
	private static final String CLIENT_ID = "CLIENT_ID";
	private static final String CLIENT_SECRET = "CLIENT_SECRET";
 
	private static final String CONTENT_TYPE = "application/json;charset=UTF-8";
 
	@Autowired
	private FilterChainProxy springSecurityFilterChain;
 
 
	public String absoluteFilePath = "D:/json/";
 
	@Before
	public void setUp() throws Exception {
		try {
 
			this.mockMvc = MockMvcBuilders.webAppContextSetup(this.webApplicationContext)
					.addFilter(springSecurityFilterChain).build();
 
		} catch (Exception e) {
			e.printStackTrace(); // TODO: handle exception
		}
 
	}
 
	@WithMockUser(username = "username", password = "pass", roles = "ADMIN")
	protected String obtainAccessToken(String username, String password) throws Exception {
 
		username = "username";
		password = "password";
		JacksonJsonParser jsonParser = null;
		String resultString = null;
		try {
			final MultiValueMap<String, String> params = new LinkedMultiValueMap<>();
			params.add("grant_type", "password");
			params.add("client_id", CLIENT_ID);
			params.add("username", username);
			params.add("password", password);
 
			// @formatter:off
 
			ResultActions result = mockMvc.perform(post("/oauth/token").params(params)
					.header(HttpHeaders.AUTHORIZATION,
							"Basic " + Base64Utils.encodeToString("username:password".getBytes()))
					.accept(CONTENT_TYPE));
 
			result.andExpect(status().isOk()).andExpect(content().contentType(CONTENT_TYPE));
 
			// @formatter:on
 
			resultString = result.andReturn().getResponse().getContentAsString();
 
			jsonParser = new JacksonJsonParser();
		} catch (Exception e) {
			e.printStackTrace();
		}
		return jsonParser.parseMap(resultString).get("access_token").toString();
	}
 
 
 
	@Test
	public void updateTest() throws Exception {
		ObjectMapper mapper = new ObjectMapper();
		try {
 
 
 
			BufferedReader br = new BufferedReader(new FileReader(absoluteFilePath + "user.json"));
			Gson gson = new GsonBuilder().setDateFormat("yyyy-MM-dd").setPrettyPrinting().create();
			User user = gson.fromJson(br, User.class);
			String jsonInString = mapper.writeValueAsString(user);
			System.out.println(jsonInString);
 
			final String accessToken = obtainAccessToken("admin", "nimda");
 
 
 
			  mockMvc.perform(post("/api/v2/users/").header("Authorization", "Bearer " + accessToken)
		                .contentType(CONTENT_TYPE)
		                .content(jsonInString)
		                .accept(CONTENT_TYPE))
		                .andExpect(status().isCreated());
 
 
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
 
	class MyDetails extends ResourceOwnerPasswordResourceDetails {
		public MyDetails(final Object obj) {
			UserControllerITTest it = (UserControllerITTest) obj;
			setAccessTokenUri(it.getHost() + "/oauth/token");
			setClientId("ClientId");
			setUsername("Username");
			setPassword("Password");
		}
	}
}
Code : Sélectionner tout - Visualiser dans une fenêtre à part
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
 
 
@Configuration
@EnableAuthorizationServer
public class AuthorizationServerConfigTest extends AuthorizationServerConfigurerAdapter {
 
    @Autowired
    private Environment env;
 
    @Autowired
    @Qualifier("authenticationManagerBean")
    private AuthenticationManager authenticationManager;
 
    @Value("classpath:schema.sql")
    private Resource schemaScript;
 
    @Override
    public void configure(final AuthorizationServerSecurityConfigurer oauthServer) throws Exception {
        oauthServer.tokenKeyAccess("permitAll()").checkTokenAccess("isAuthenticated()");
        oauthServer.allowFormAuthenticationForClients();
    }
 
    @Override
    public void configure(final ClientDetailsServiceConfigurer clients) throws Exception {// @formatter:off
        clients.inMemory()
          .withClient("Client")
          .secret("secret")
          .authorizedGrantTypes("password","refresh_token", "client_credentials")
          .scopes("foo", "read", "write")
          .accessTokenValiditySeconds(3600) // 1 hour
          .refreshTokenValiditySeconds(2592000); // 30 days;
	  ;
	} // @formatter:on
 
    @Override
    public void configure(final AuthorizationServerEndpointsConfigurer endpoints) throws Exception {
        // @formatter:off
		final TokenEnhancerChain tokenEnhancerChain = new TokenEnhancerChain();
		tokenEnhancerChain.setTokenEnhancers(Arrays.asList(tokenEnhancer()));
		endpoints.tokenStore(tokenStore())
				// .accessTokenConverter(accessTokenConverter())
				.tokenEnhancer(tokenEnhancerChain).authenticationManager(authenticationManager);
		// @formatter:on
    }
 
 
    */
    @Bean
    @Primary
    public DefaultTokenServices tokenServices() {
        final DefaultTokenServices defaultTokenServices = new DefaultTokenServices();
        defaultTokenServices.setTokenStore(tokenStore());
        defaultTokenServices.setSupportRefreshToken(true);
        return defaultTokenServices;
    }
 
    @Bean
    public TokenEnhancer tokenEnhancer() {
        return new CustomTokenEnhancer();
    }
 
    // JDBC token store configuration
 
    @Bean
    public DataSourceInitializer dataSourceInitializer(final DataSource dataSource) {
        final DataSourceInitializer initializer = new DataSourceInitializer();
        initializer.setDataSource(dataSource);
        initializer.setDatabasePopulator(databasePopulator());
        return initializer;
    }
 
    private DatabasePopulator databasePopulator() {
        final ResourceDatabasePopulator populator = new ResourceDatabasePopulator();
        populator.addScript(schemaScript);
        return populator;
    }
 
    @Bean
    public DataSource dataSource() {
        final DriverManagerDataSource dataSource = new DriverManagerDataSource();
        dataSource.setDriverClassName("org.h2.Driver");
        dataSource.setUrl("jdbc:h2:mem:testIntegr");
        dataSource.setUsername("sa");
        dataSource.setPassword("");
        return dataSource;
    }
 
    @Bean
    public TokenStore tokenStore() {
        return new JdbcTokenStore(dataSource());
    }
 
    @Bean
    public BCryptPasswordEncoder passwordEncoder() {
        return new BCryptPasswordEncoder();
    }
 
}
Code : Sélectionner tout - Visualiser dans une fenêtre à part
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
 
import static org.apache.commons.lang3.RandomStringUtils.randomAlphabetic;
import java.util.HashMap;
import java.util.Map;
 
import org.springframework.security.oauth2.common.DefaultOAuth2AccessToken;
import org.springframework.security.oauth2.common.OAuth2AccessToken;
import org.springframework.security.oauth2.provider.OAuth2Authentication;
import org.springframework.security.oauth2.provider.token.TokenEnhancer;
 
public class CustomTokenEnhancer implements TokenEnhancer {
 
    @Override
    public OAuth2AccessToken enhance(OAuth2AccessToken accessToken, OAuth2Authentication authentication) {
        final Map<String, Object> additionalInfo = new HashMap<>();
        additionalInfo.put("organization", authentication.getName() + randomAlphabetic(4));
        ((DefaultOAuth2AccessToken) accessToken).setAdditionalInformation(additionalInfo);
        return accessToken;
    }
}
Code : Sélectionner tout - Visualiser dans une fenêtre à part
1
2
3
4
5
6
7
8
9
10
11
12
 
@Configuration
@EnableResourceServer
public class ResourceServerConfig extends ResourceServerConfigurerAdapter {
 
	@Override
	public void configure(HttpSecurity http) throws Exception {
		http.authorizeRequests().anyRequest().permitAll().and().httpBasic();
		http.csrf().disable();
	}
 
}
Code : Sélectionner tout - Visualiser dans une fenêtre à part
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
 
 
@Configuration
@Order(Ordered.HIGHEST_PRECEDENCE)
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
    @Autowired
    private BCryptPasswordEncoder passwordEncoder;
 
    @Autowired
    public void globalUserDetails(final AuthenticationManagerBuilder auth) throws Exception {
        // @formatter:off
	auth.inMemoryAuthentication()
	  .withUser("user").password("pâss").roles("ADMIN");    }// @formatter:on
 
    @Override
    @Bean
    public AuthenticationManager authenticationManagerBean() throws Exception {
        return super.authenticationManagerBean();
    }
 
    @Override
    protected void configure(final HttpSecurity http) throws Exception {
    	http.authorizeRequests().anyRequest().permitAll().and().httpBasic();
        http.csrf().disable();
    }
 
    @Bean
    AuthorizationServerConfigurer ac() {
        return new AuthorizationServerConfigurerAdapter() {
            @Autowired
            AuthenticationManager authenticationManager;
 
            public void configure(AuthorizationServerEndpointsConfigurer endpoints) throws Exception {
                endpoints.authenticationManager(authenticationManager);
            }
 
            public void configure(ClientDetailsServiceConfigurer clients) throws Exception {
                clients.inMemory()
                        .withClient("client")
                        .authorizedGrantTypes("authorization_code","password")
                        .scopes("read", "write");
            }
 
            public void configure(AuthorizationServerSecurityConfigurer oauthServer) throws Exception {
                oauthServer.allowFormAuthenticationForClients();
            }
        };
    }
}
et mon erreur est
java.lang.AssertionError: Status expected:<201> but was:<412>
at org.springframework.test.util.AssertionErrors.fail(AssertionErrors.java:54)
et dans les log
019-03-15 00:35:39,478 DEBUG (DomainUserDetailsService.java:45) - Authenticating
Hibernate: SELECT U.* FROM User U WHERE UserName = ? limit ?
2019-03-15 00:35:39,707 DEBUG (DomainUserDetailsService.java:45) - Authenticating
Hibernate: SELECT U.* FROM User U WHERE UserName = ? limit ?
2019-03-15 00:35:39,872 INFO (JdbcTokenStore.java:168) - Failed to find access token for token 80760e09-173a-4b9e-b50a-76d2ffe6c698
. Je suis bloque la si on peut m aider merci d avance