私はOAuth 2.0でスプリングブート1.5.6を使用しています。問題は、私が以下のテストケースを実行すると、認証オブジェクトの下にNullポインター例外が発生することです。スプリングテストケースで認証を渡す方法
System.out.println(authentication.getName());
テストクラス
@RunWith(SpringRunner.class)
@SpringBootTest(classes = WebApp.class, webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
@TestPropertySource(locations = "classpath:test-application.properties")
public class ProfileControllerTest {
......
......
@Before
public void setup() {
this.mockMvc = MockMvcBuilders.standaloneSetup(userController).build();
...........
.........
}
@Test
public void profileTest() throws Exception {
String userId = "12345678";
mockMvc.perform(get("user/" + userId + "/profile"))
.andExpect(status().isOk())
.andExpect(content().contentType(MediaType.APPLICATION_JSON_UTF8));
}
}
休憩コントローラー
@RequestMapping(value = "user/{userId}/profile",
method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
public ResponseEntity<Map<String, Object>> getProfile(
@PathVariable(value = "userId", required = true) String userId,
HttpServletRequest request, Authentication authentication) {
System.out.println(authentication.getName());
}
セキュリティ設定
@Configuration
@EnableOAuth2Sso
@EnableGlobalMethodSecurity(securedEnabled = true)
public class WebAppSecurityConfig extends WebSecurityConfigurerAdapter {
private static final String OAUTH_COOKIE = "OAUTH-ACCESS-TOKEN";
private UserService userService;
private OAuth2TokenAuthenticationFilter ssoFilter;
private JwtAccessTokenConverter accessTokenConverter;
/**
* WebAppSecurity overloaded constructor.
*/
public WebAppSecurityConfig(UserService userService,
OAuth2TokenAuthenticationFilter ssoFilter,
JwtAccessTokenConverter accessTokenConverter) {
this.userService = userService;
this.ssoFilter = ssoFilter;
this.accessTokenConverter = accessTokenConverter;
}
@Override
protected void configure(HttpSecurity http) throws Exception {
http.anonymous()
.disable()
.authorizeRequests()
.antMatchers("/logout-success")
.permitAll()
.anyRequest()
.authenticated()
.and()
.csrf()
.csrfTokenRepository(CookieCsrfTokenRepository.withHttpOnlyFalse())
.and()
.addFilterAfter(ssoFilter,
AbstractPreAuthenticatedProcessingFilter.class).logout()
.logoutUrl("/logout").logoutSuccessUrl("/logout-success").permitAll()
.deleteCookies(OAUTH_COOKIE);
}
@Autowired
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
auth.userDetailsService(userDetailsService());
configure((DefaultAccessTokenConverter) accessTokenConverter
.getAccessTokenConverter());
}
protected void configure(DefaultAccessTokenConverter accessTokenConverter) {
DefaultUserAuthenticationConverter userTokenConverter =
new DefaultUserAuthenticationConverter();
userTokenConverter.setUserDetailsService(userDetailsService());
accessTokenConverter.setUserTokenConverter(userTokenConverter);
}
@Override
protected UserDetailsService userDetailsService() {
return userService;
}
上記のテストケースで認証オブジェクトを渡す方法は?
あなたはこれまでの解決策を見つけましたか?私は現在同じ問題で苦労しています。 – AgentBawls