我目前正在将Azure广告与com.microsoft.azure:azure-active-directory-spring-boot-starter
库一起使用。致电
authentication = SecurityContextHolder.getContext()
.authentication
val principal = authentication?.principal
这将返回com.microsoft.azure.spring.autoconfigure.aad.UserPrincipal
但是在我的测试中,它返回org.springframework.security.core.userdetails.UserDetails
我的测试中是否有办法知道如何返回UserPrincipal
?
我已经在控制器中创建了解决方法,以通过测试,但是我认为这不是正确的方法。
final var authentication: Authentication? = null
final val user = User()
init {
authentication = SecurityContextHolder.getContext()
.authentication
if (authentication?.principal is UserPrincipal ) {
val principal = authentication?.principal as UserPrincipal
user.email = principal.upn
user.firstName = principal.claims["given_name"].toString()
user.lastName = principal.claims["family_name"].toString()
user.userId = principal.claims["oid"].toString()
} else {
val principal = authentication?.principal as UserDetails
user.email = principal?.username
}
}
这是我的测试课
@ExtendWith(SpringExtension::class)
@TestPropertySource(locations=["classpath:application-jenkins.properties"])
@WebAppConfiguration
@ContextConfiguration
@SpringBootTest
@Import(MongoTestConfig::class, WebSecurityConfig::class)
class UserControllerTest {
var mockMvc: MockMvc? = null
@Autowired
private val objectMapper: ObjectMapper? = null
@Autowired
private val webApplicationContext: WebApplicationContext? = null
@BeforeAll
fun setup() {
mockMvc = MockMvcBuilders
.webAppContextSetup(webApplicationContext!!)
.apply<DefaultMockMvcBuilder>(SecurityMockMvcConfigurers.springSecurity())
.build()
objectMapper?.propertyNamingStrategy = PropertyNamingStrategy.SNAKE_CASE
}
@Test
@WithMockUser("Bob", roles = ["dl-wifiengineering"])
fun getAUser() {
mockMvc?.perform(get("/api/user/user-info")
.accept(MediaType.APPLICATION_JSON))
?.andExpect(MockMvcResultMatchers.status().is2xxSuccessful)
?.andExpect(MockMvcResultMatchers.content().contentType(MediaType.APPLICATION_JSON_UTF8))
?.andExpect(MockMvcResultMatchers.jsonPath("\$.change_types").value("emergency"))
?.andDo(MockMvcResultHandlers.print())
}
}
这是我的WebSecurityConfig
@EnableGlobalMethodSecurity(securedEnabled = true, prePostEnabled = true)
class WebSecurityConfig : WebSecurityConfigurerAdapter() {
@Autowired
private val aadAuthFilter: AADAuthenticationFilter? = null
@Throws(Exception::class)
override fun configure(http: HttpSecurity) {
//allow all request access this url
http.csrf().disable().cors().and().authorizeRequests().antMatchers("/").permitAll()
//spring actuator
http.authorizeRequests().antMatchers("/actuator/**").permitAll()
//access to this url requires authentication
http.authorizeRequests().antMatchers("/api/**").authenticated()
//logout logic
http.logout().logoutRequestMatcher(AntPathRequestMatcher("/logout"))
.logoutSuccessUrl("/")
.deleteCookies("JSESSIONID")
.invalidateHttpSession(true)
http.authorizeRequests().anyRequest().permitAll()
// //set up the csfr token
// http.csrf().csrfTokenRepository(CookieCsrfTokenRepository.withHttpOnlyFalse())
http.addFilterBefore(aadAuthFilter, UsernamePasswordAuthenticationFilter::class.java)
}
}