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

The following examples show how to use org.springframework.security.test.context.support.WithAnonymousUser. These examples are extracted from open source projects. 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
@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
@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 3
@Test
@WithAnonymousUser
public void shouldGetUnauthorizedWithAnonymousUser() throws Exception {

    mvc.perform(get("/refresh"))
        .andExpect(status().isUnauthorized());
}
 
Example 4
@Test
@WithAnonymousUser
public void getMessage() {
    try {
        overAnnotatedService.sec1a();
        fail();
    } catch (AccessDeniedException e) {
        // succeed
    }
}
 
Example 5
@Test
@WithAnonymousUser
public void test_welcome_WithAnonymousUser() throws Exception {
    mockMvc
            .perform(get("/"))
            .andExpect(status().isOk())
            .andExpect(view().name("index"))
            .andDo(print())
    ;
}
 
Example 6
@Test
@WithAnonymousUser
public void securityEnabled() throws Exception {
    mvc
            .perform(get("/admin/h2")
                    .header("X-Requested-With", "XMLHttpRequest")
            )
            .andExpect(status().isUnauthorized());
}
 
Example 7
@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 8
@Test
@WithAnonymousUser
public void securityEnabled() throws Exception {
    mvc
            .perform(get("/admin/h2")
                    .header("X-Requested-With", "XMLHttpRequest")
            )
            .andExpect(status().isUnauthorized());
}
 
Example 9
@Test
@WithAnonymousUser
public void test_events_WithAnonymousUser() throws Exception {
    mvc.perform(get("/events/"))
            .andExpect(status().is4xxClientError())
    ;
}
 
Example 10
@Test
@WithAnonymousUser
public void securityEnabled() throws Exception {
    mockMvc
            .perform(get("/admin/h2")
                    .header("X-Requested-With", "XMLHttpRequest")
            )
            .andExpect(status().isUnauthorized());
}
 
Example 11
Source Project: joinfaces   Source File: AnonymousFaceletsTagIT.java    License: 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 12
Source Project: joinfaces   Source File: AnonymousFaceletsTagHandlerIT.java    License: 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 13
@Test
@WithAnonymousUser
void testNotAuthorize() throws IOException {
	AuthenticatedFaceletsTagHandler tag = new AuthenticatedFaceletsTagHandler(
		getJsfMock().getMockTagConfig());

	tag.apply(null, null);

	assertThat(getJsfMock().getMockFaceletHandler().isApplied())
		.isFalse();
}
 
Example 14
@Test
@WithAnonymousUser
void testNotAuthorize() throws IOException {
	FullyAuthenticatedFaceletsTagHandler tag = new FullyAuthenticatedFaceletsTagHandler(
		getJsfMock().getMockTagConfig());

	tag.apply(null, null);

	assertThat(getJsfMock().getMockFaceletHandler().isApplied())
		.isFalse();
}
 
Example 15
Source Project: joinfaces   Source File: AuthenticatedFaceletsTagIT.java    License: 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 16
Source Project: joinfaces   Source File: FullyAuthenticatedFaceletsTagIT.java    License: 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 17
Source Project: springboot-jwt-starter   Source File: UserControllerTest.java    License: MIT License 5 votes vote down vote up
@Test
@WithAnonymousUser
public void shouldGetUnauthorizedWithoutRole() throws Exception {

    this.mvc.perform(get("/user"))
            .andExpect(status().isUnauthorized());
}
 
Example 18
Source Project: jakduk-api   Source File: UserMvcTests.java    License: 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 19
@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());
}
 
Example 20
Source Project: Spring   Source File: AnnotatedClassMessageServiceTests.java    License: Apache License 2.0 4 votes vote down vote up
@Test
@WithAnonymousUser
public void getMessageWhenNotAuthenticatedThenAuthenticationCredentialsNotFoundException() {
	assertThatCode(() -> this.messageService.getMessage())
			.isInstanceOf(AccessDeniedException.class);
}
 
Example 21
Source Project: Spring   Source File: AnnotatedClassMessageServiceTests.java    License: Apache License 2.0 4 votes vote down vote up
@Test
@WithAnonymousUser
public void anonymous() {
	assertThatCode(() -> this.messageService.getMessage())
			.isInstanceOf(AccessDeniedException.class);
}
 
Example 22
Source Project: joinfaces   Source File: FaceletsAuthorizeTagUtilsIT.java    License: Apache License 2.0 4 votes vote down vote up
@Test
@WithAnonymousUser
void testIsAllowedFalse() throws IOException {
	assertThat(FaceletsAuthorizeTagUtils.isAllowed("myurl", "mymethod"))
		.isFalse();
}
 
Example 23
Source Project: springboot-jwt-starter   Source File: UserControllerTest.java    License: 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 Project: jakduk-api   Source File: UserMvcTests.java    License: 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 25
Source Project: jakduk-api   Source File: AuthMvcTests.java    License: 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 26
Source Project: tutorials   Source File: MethodSecurityIntegrationTest.java    License: MIT License 4 votes vote down vote up
@Test(expected = AccessDeniedException.class)
@WithAnonymousUser
public void givenAnomynousUser_whenCallGetUsername_thenAccessDenied() {
    userRoleService.getUsername();
}
 
Example 27
@Test
@WithAnonymousUser
public void givenAnonymous_whenRequestFoo_thenRetrieveUnauthorized() throws Exception {
    this.mvc.perform(get("/foos/1").with(csrf()))
            .andExpect(status().isFound());
}