org.springframework.security.test.context.support.WithAnonymousUser Java Examples

The following examples show how to use org.springframework.security.test.context.support.WithAnonymousUser. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: AuditSecurityConfigurationTest.java    From spring-security-samples with MIT License 5 votes vote down vote up
@Test
@Transactional
@WithAnonymousUser
void testSaveAsAnonymousUser() {
	// Create and save a blogpost
	Blogpost blogpost = new Blogpost();
	blogpost.setTitle("Auditing Spring Data Entities");
	Long id = blogpostRepo.save(blogpost).getId();

	// Verify that author was not set by JPA
	Blogpost found = em.find(Blogpost.class, id);
	assertThat(found.getCreatedBy()).isEmpty();
}
 
Example #2
Source File: UserControllerTest.java    From springboot-jwt-starter with MIT License 5 votes vote down vote up
@Test
@WithAnonymousUser
public void shouldGetUnauthorizedWithoutRole() throws Exception {

    this.mvc.perform(get("/user"))
            .andExpect(status().isUnauthorized());
}
 
Example #3
Source File: FullyAuthenticatedFaceletsTagIT.java    From joinfaces with Apache License 2.0 5 votes vote down vote up
@Test
@WithAnonymousUser
void testNotAuthorize() throws IOException {
	FullyAuthenticatedFaceletsTag tag = new FullyAuthenticatedFaceletsTag();
	assertThat(tag.authorize())
		.isFalse();
}
 
Example #4
Source File: UserMvcTests.java    From jakduk-api with MIT License 5 votes vote down vote up
@Test
@WithAnonymousUser
public void findPasswordTest() throws Exception {

    Map<String, Object> form = new HashMap<String, Object>() {{
        put("email", jakdukUser.getEmail());
        put("callbackUrl", "http://dev-wev.jakduk/find/password");
    }};

    UserPasswordFindResponse expectResponse = new UserPasswordFindResponse(form.get("email").toString(),
            JakdukUtils.getMessageSource("user.msg.reset.password.send.email"));

    when(userService.sendEmailToResetPassword(anyString(), anyString()))
            .thenReturn(expectResponse);

    ConstraintDescriptions userConstraints = new ConstraintDescriptions(UserPasswordFindForm.class, new ValidatorConstraintResolver(),
            new ResourceBundleConstraintDescriptionResolver(ResourceBundle.getBundle("ValidationMessages")));

    mvc.perform(
            post("/api/user/password/find")
                    .contentType(MediaType.APPLICATION_JSON)
                    .with(csrf())
                    .content(ObjectMapperUtils.writeValueAsString(form)))
            .andExpect(status().isOk())
            .andExpect(content().contentTypeCompatibleWith(MediaType.APPLICATION_JSON))
            .andExpect(content().json(ObjectMapperUtils.writeValueAsString(expectResponse)))
            .andDo(
                    document("user-find-password",
                            requestFields(
                                    fieldWithPath("email").type(JsonFieldType.STRING).description("이메일 주소. " +
                                            userConstraints.descriptionsForProperty("email")),
                                    fieldWithPath("callbackUrl").type(JsonFieldType.STRING).description("콜백 받을 URL. " +
                                            userConstraints.descriptionsForProperty("callbackUrl"))
                            ),
                            responseFields(this.getPasswordFindDescriptor())
                    ));
}
 
Example #5
Source File: AuthenticatedFaceletsTagIT.java    From joinfaces with Apache License 2.0 5 votes vote down vote up
@Test
@WithAnonymousUser
void testNotAuthorize() throws IOException {
	AuthenticatedFaceletsTag tag = new AuthenticatedFaceletsTag();
	assertThat(tag.authorize())
		.isFalse();
}
 
Example #6
Source File: FullyAuthenticatedFaceletsTagHandlerIT.java    From joinfaces with Apache License 2.0 5 votes vote down vote up
@Test
@WithAnonymousUser
void testNotAuthorize() throws IOException {
	FullyAuthenticatedFaceletsTagHandler tag = new FullyAuthenticatedFaceletsTagHandler(
		getJsfMock().getMockTagConfig());

	tag.apply(null, null);

	assertThat(getJsfMock().getMockFaceletHandler().isApplied())
		.isFalse();
}
 
Example #7
Source File: AuthenticatedFaceletsTagHandlerIT.java    From joinfaces with Apache License 2.0 5 votes vote down vote up
@Test
@WithAnonymousUser
void testNotAuthorize() throws IOException {
	AuthenticatedFaceletsTagHandler tag = new AuthenticatedFaceletsTagHandler(
		getJsfMock().getMockTagConfig());

	tag.apply(null, null);

	assertThat(getJsfMock().getMockFaceletHandler().isApplied())
		.isFalse();
}
 
Example #8
Source File: AnonymousFaceletsTagHandlerIT.java    From joinfaces with Apache License 2.0 5 votes vote down vote up
@Test
@WithAnonymousUser
void testAuthorize() throws IOException {

	AnonymousFaceletsTagHandler tag = new AnonymousFaceletsTagHandler(
		getJsfMock().getMockTagConfig());

	tag.apply(null, null);

	assertThat(getJsfMock().getMockFaceletHandler().isApplied())
		.isTrue();
}
 
Example #9
Source File: AnonymousFaceletsTagIT.java    From joinfaces with Apache License 2.0 5 votes vote down vote up
@Test
@WithAnonymousUser
void testAuthorize() throws IOException {
	AnonymousFaceletsTag tag = new AnonymousFaceletsTag();
	assertThat(tag.authorize())
		.isTrue();
}
 
Example #10
Source File: CalendarApplicationTests.java    From Spring-Security-Third-Edition with MIT License 5 votes vote down vote up
@Test
@WithAnonymousUser
public void securityEnabled() throws Exception {
    mockMvc
            .perform(get("/admin/h2")
                    .header("X-Requested-With", "XMLHttpRequest")
            )
            .andExpect(status().isUnauthorized());
}
 
Example #11
Source File: CalendarApplicationTests.java    From Spring-Security-Third-Edition with MIT License 5 votes vote down vote up
@Test
@WithAnonymousUser
public void test_events_WithAnonymousUser() throws Exception {
    mvc.perform(get("/events/"))
            .andExpect(status().is4xxClientError())
    ;
}
 
Example #12
Source File: CalendarApplicationTests.java    From Spring-Security-Third-Edition with MIT License 5 votes vote down vote up
@Test
@WithAnonymousUser
public void securityEnabled() throws Exception {
    mvc
            .perform(get("/admin/h2")
                    .header("X-Requested-With", "XMLHttpRequest")
            )
            .andExpect(status().isUnauthorized());
}
 
Example #13
Source File: CalendarApplicationTests.java    From Spring-Security-Third-Edition with MIT License 5 votes vote down vote up
@Test
    @WithAnonymousUser
    public void test_events_WithAnonymousUser() throws Exception {
        mvc.perform(get("/events/"))
                .andExpect(status().is3xxRedirection())
                .andExpect(redirectedUrl("http://localhost/login/form"))
//                .andExpect(redirectedUrlPattern("/login/form"))
        ;
    }
 
Example #14
Source File: CalendarApplicationTests.java    From Spring-Security-Third-Edition with MIT License 5 votes vote down vote up
@Test
@WithAnonymousUser
public void securityEnabled() throws Exception {
    mvc
            .perform(get("/admin/h2")
                    .header("X-Requested-With", "XMLHttpRequest")
            )
            .andExpect(status().isUnauthorized());
}
 
Example #15
Source File: WelcomeControllerTests.java    From Spring-Security-Third-Edition with MIT License 5 votes vote down vote up
@Test
@WithAnonymousUser
public void test_welcome_WithAnonymousUser() throws Exception {
    mockMvc
            .perform(get("/"))
            .andExpect(status().isOk())
            .andExpect(view().name("index"))
            .andDo(print())
    ;
}
 
Example #16
Source File: OverAnnotatedServiceTest.java    From Spring-Boot-2-Fundamentals with MIT License 5 votes vote down vote up
@Test
@WithAnonymousUser
public void getMessage() {
    try {
        overAnnotatedService.sec1a();
        fail();
    } catch (AccessDeniedException e) {
        // succeed
    }
}
 
Example #17
Source File: AuthenticationRestControllerTest.java    From spring-react-boilerplate with MIT License 5 votes vote down vote up
@Test
@WithAnonymousUser
public void shouldGetUnauthorizedWithAnonymousUser() throws Exception {

    mvc.perform(get("/refresh"))
        .andExpect(status().isUnauthorized());
}
 
Example #18
Source File: AuthenticationRestControllerTest.java    From spring-react-boilerplate with MIT License 5 votes vote down vote up
@Test
@WithAnonymousUser
public void successfulAuthenticationWithAnonymousUser() throws Exception {

    JwtAuthenticationRequest jwtAuthenticationRequest = new JwtAuthenticationRequest("user", "password");

    mvc.perform(post("/auth")
        .contentType(MediaType.APPLICATION_JSON)
        .content(new ObjectMapper().writeValueAsString(jwtAuthenticationRequest)))
        .andExpect(status().is2xxSuccessful());
}
 
Example #19
Source File: AuthMvcTests.java    From jakduk-api with MIT License 4 votes vote down vote up
@Test
@WithAnonymousUser
public void getAttemptSocialUserTest() throws Exception {

    AttemptSocialUser expectAttemptSocialUser = new AttemptSocialUser();
    expectAttemptSocialUser.setEmail(socialProfile.getEmail());
    expectAttemptSocialUser.setUsername(socialProfile.getNickname());
    expectAttemptSocialUser.setProviderId(providerId);
    expectAttemptSocialUser.setProviderUserId(socialProfile.getId());
    expectAttemptSocialUser.setExternalLargePictureUrl(socialProfile.getPictureUrl());

    Map<String, Object> sessionAttributes = new HashMap<>();
    sessionAttributes.put(Constants.PROVIDER_SIGNIN_ATTEMPT_SESSION_ATTRIBUTE, expectAttemptSocialUser);

    mvc.perform(
            get("/api/auth/user/attempt")
                    .header("Cookie", "JSESSIONID=3F0E029648484BEAEF6B5C3578164E99")
                    .sessionAttrs(sessionAttributes)
                    .accept(MediaType.APPLICATION_JSON))
            .andExpect(status().isOk())
            .andExpect(content().contentTypeCompatibleWith(MediaType.APPLICATION_JSON))
            .andExpect(content().json(ObjectMapperUtils.writeValueAsString(expectAttemptSocialUser)))
            .andDo(
                    document("get-attempt-social-session-user",
                            requestHeaders(
                                    headerWithName("Cookie").description("인증 쿠키. value는 JSESSIONID=키값")
                            ),
                            responseFields(
                                    fieldWithPath("email").type(JsonFieldType.STRING).description("Provider에서 제공한 이메일 주소"),
                                    fieldWithPath("username").type(JsonFieldType.STRING).description("Provider에서 제공한 별명"),
                                    fieldWithPath("providerId").type(JsonFieldType.STRING).description("SNS 분류 " +
                                                    Stream.of(Constants.ACCOUNT_TYPE.values())
                                                            .filter(accountType -> ! accountType.equals(Constants.ACCOUNT_TYPE.JAKDUK))
                                                            .map(Enum::name)
                                                            .collect(Collectors.toList())
                                            ),
                                    fieldWithPath("providerUserId").type(JsonFieldType.STRING).description("Provider에서 제공한 사용자 ID"),
                                    fieldWithPath("externalLargePictureUrl").type(JsonFieldType.STRING).description("Provider에서 제공한 큰 사진 URL")
                            )
                    ));
}
 
Example #20
Source File: MethodSecurityIntegrationTest.java    From tutorials with MIT License 4 votes vote down vote up
@Test(expected = AccessDeniedException.class)
@WithAnonymousUser
public void givenAnomynousUser_whenCallGetUsername_thenAccessDenied() {
    userRoleService.getUsername();
}
 
Example #21
Source File: CustomUserDetailsServiceIntegrationTest.java    From tutorials with MIT License 4 votes vote down vote up
@Test
@WithAnonymousUser
public void givenAnonymous_whenRequestFoo_thenRetrieveUnauthorized() throws Exception {
    this.mvc.perform(get("/foos/1").with(csrf()))
            .andExpect(status().isFound());
}
 
Example #22
Source File: UserMvcTests.java    From jakduk-api with MIT License 4 votes vote down vote up
@Test
@WithAnonymousUser
public void createJakdukUserTest() throws Exception {

    this.whenCustomValdation();

    UserForm form = new UserForm();
    form.setEmail(jakdukUser.getEmail());
    form.setUsername(jakdukUser.getUsername());
    form.setPassword("1111");
    form.setPasswordConfirm("1111");
    form.setAbout(jakdukUser.getAbout());
    form.setFootballClub(footballClub.getId());
    form.setUserPictureId(userPicture.getId());

    when(userService.createJakdukUser(anyString(), anyString(), anyString(), anyString(), anyString(), anyString()))
            .thenReturn(jakdukUser);

    ConstraintDescriptions userConstraints = new ConstraintDescriptions(UserForm.class, new ValidatorConstraintResolver(),
            new ResourceBundleConstraintDescriptionResolver(ResourceBundle.getBundle("ValidationMessages")));

    mvc.perform(
            post("/api/user")
                    .contentType(MediaType.APPLICATION_JSON)
                    .accept(MediaType.APPLICATION_JSON)
                    .with(csrf())
                    .content(ObjectMapperUtils.writeValueAsString(form)))
            .andExpect(status().isOk())
            .andExpect(content().contentTypeCompatibleWith(MediaType.APPLICATION_JSON))
            .andExpect(content().json(ObjectMapperUtils.writeValueAsString(EmptyJsonResponse.newInstance())))
            .andDo(
                    document("create-jakduk-user",
                            requestFields(
                                    fieldWithPath("email").type(JsonFieldType.STRING).description("이메일 주소. " +
                                            userConstraints.descriptionsForProperty("email")),
                                    fieldWithPath("username").type(JsonFieldType.STRING).description("별명. " +
                                            userConstraints.descriptionsForProperty("username")),
                                    fieldWithPath("password").type(JsonFieldType.STRING).description("비밀번호. " +
                                            userConstraints.descriptionsForProperty("password")),
                                    fieldWithPath("passwordConfirm").type(JsonFieldType.STRING).description("확인 비밀번호. " +
                                            userConstraints.descriptionsForProperty("passwordConfirm")),
                                    fieldWithPath("footballClub").type(JsonFieldType.STRING).description("(optional) 축구단 ID"),
                                    fieldWithPath("about").type(JsonFieldType.STRING).description("(optional) 자기 소개"),
                                    fieldWithPath("userPictureId").type(JsonFieldType.STRING).description("(optional) 프로필 사진 ID")
                            ),
                            responseHeaders(
                                    headerWithName("Set-Cookie").description("인증 쿠키. value는 JSESSIONID=키값").optional()
                            )
                    ));
}
 
Example #23
Source File: UserControllerTest.java    From springboot-jwt-starter with MIT License 4 votes vote down vote up
@Test
@WithAnonymousUser
public void getPersonsFailWithAnonymousUser() throws Exception {
    this.mvc.perform(get("/api/whoami"))
            .andExpect(status().is4xxClientError());
}
 
Example #24
Source File: FaceletsAuthorizeTagUtilsIT.java    From joinfaces with Apache License 2.0 4 votes vote down vote up
@Test
@WithAnonymousUser
void testIsAllowedFalse() throws IOException {
	assertThat(FaceletsAuthorizeTagUtils.isAllowed("myurl", "mymethod"))
		.isFalse();
}
 
Example #25
Source File: AnnotatedClassMessageServiceTests.java    From Spring with Apache License 2.0 4 votes vote down vote up
@Test
@WithAnonymousUser
public void anonymous() {
	assertThatCode(() -> this.messageService.getMessage())
			.isInstanceOf(AccessDeniedException.class);
}
 
Example #26
Source File: AnnotatedClassMessageServiceTests.java    From Spring with Apache License 2.0 4 votes vote down vote up
@Test
@WithAnonymousUser
public void getMessageWhenNotAuthenticatedThenAuthenticationCredentialsNotFoundException() {
	assertThatCode(() -> this.messageService.getMessage())
			.isInstanceOf(AccessDeniedException.class);
}
 
Example #27
Source File: ProfileControllerTest.java    From webauthn4j-spring-security with Apache License 2.0 4 votes vote down vote up
@Test
@WithAnonymousUser
public void create_test() throws Exception {

    ProfileCreateForm userCreateForm = new ProfileCreateForm();
    userCreateForm.setUserHandle("ORZClsZpTvWrYGl7mXL5Wg");
    userCreateForm.setFirstName("John");
    userCreateForm.setLastName("Doe");
    userCreateForm.setEmailAddress("[email protected]");
    userCreateForm.setPassword("password");
    userCreateForm.setAuthenticators(Collections.emptyList());
    userCreateForm.setSingleFactorAuthenticationAllowed(true);

    UserEntity userEntity = new UserEntity();
    userEntity.setId(1);
    userEntity.setUserHandle(Base64UrlUtil.decode("ORZClsZpTvWrYGl7mXL5Wg"));
    userEntity.setFirstName("John");
    userEntity.setLastName("Doe");
    userEntity.setEmailAddress("[email protected]");
    userEntity.setAuthenticators(Collections.emptyList());
    userEntity.setSingleFactorAuthenticationAllowed(true);

    when(profileAppService.create(any())).thenReturn(userEntity);

    //When
    mvc.perform(
            post("/api/profile")
                    .contentType(MediaType.APPLICATION_JSON)
                    .content(objectMapper.writeValueAsString(userCreateForm))
                    .with(SecurityMockMvcRequestPostProcessors.csrf())
    )
            //Then
            .andExpect(status().isOk())
            .andExpect(jsonPath("$.id", is(1)))
            .andExpect(jsonPath("$.userHandle", is("ORZClsZpTvWrYGl7mXL5Wg")))
            .andExpect(jsonPath("$.firstName", is("John")))
            .andExpect(jsonPath("$.lastName", is("Doe")))
            .andExpect(jsonPath("$.emailAddress", is("[email protected]")))
            .andExpect(jsonPath("$.authenticators", is(empty())))
            .andExpect(jsonPath("$.singleFactorAuthenticationAllowed", is(true)))
    ;
    verify(profileAppService).create(any());
}