Add CustomUser example

This commit is contained in:
Rob Winch
2020-12-08 16:16:56 -06:00
parent 491c6148d2
commit 49757eb6ea
21 changed files with 920 additions and 3 deletions

View File

@@ -0,0 +1,44 @@
/*
* Copyright 2002-2018 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package example;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.boot.test.web.client.TestRestTemplate;
import static org.assertj.core.api.Assertions.assertThat;
/**
* Integration tests.
*
* @author Michael Simons
*/
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
public class HelloSecurityExplicitITests {
@Autowired
private TestRestTemplate rest;
@Test
void login() {
CustomUser result = this.rest.withBasicAuth("user@example.com", "password").getForObject("/user",
CustomUser.class);
assertThat(result.getEmail()).isEqualTo("user@example.com");
}
}

View File

@@ -0,0 +1,28 @@
/*
* Copyright 2020 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package example;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import org.springframework.security.core.annotation.AuthenticationPrincipal;
@AuthenticationPrincipal
@Retention(RetentionPolicy.RUNTIME)
public @interface CurrentUser {
}

View File

@@ -0,0 +1,55 @@
/*
* Copyright 2020 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package example;
import com.fasterxml.jackson.annotation.JsonCreator;
import com.fasterxml.jackson.annotation.JsonIgnore;
/**
* A custom user representation.
*
* @author Rob Winch
*/
public class CustomUser {
private final long id;
private final String email;
@JsonIgnore
private final String password;
@JsonCreator
public CustomUser(long id, String email, String password) {
this.id = id;
this.email = email;
this.password = password;
}
public long getId() {
return this.id;
}
public String getEmail() {
return this.email;
}
public String getPassword() {
return this.password;
}
}

View File

@@ -0,0 +1,23 @@
/*
* Copyright 2020 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package example;
public interface CustomUserRepository {
CustomUser findCustomUserByEmail(String email);
}

View File

@@ -0,0 +1,89 @@
/*
* Copyright 2020 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package example;
import java.util.Collection;
import java.util.Collections;
import java.util.List;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;
@Service
public class CustomUserRepositoryUserDetailsService implements UserDetailsService {
private final CustomUserRepository userRepository;
public CustomUserRepositoryUserDetailsService(CustomUserRepository userRepository) {
this.userRepository = userRepository;
}
@Override
public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
CustomUser customUser = this.userRepository.findCustomUserByEmail(username);
if (customUser == null) {
throw new UsernameNotFoundException("username " + username + " is not found");
}
return new CustomUserDetails(customUser);
}
static final class CustomUserDetails extends CustomUser implements UserDetails {
private static final List<GrantedAuthority> ROLE_USER = Collections
.unmodifiableList(AuthorityUtils.createAuthorityList("ROLE_USER"));
CustomUserDetails(CustomUser customUser) {
super(customUser.getId(), customUser.getEmail(), customUser.getPassword());
}
@Override
public Collection<? extends GrantedAuthority> getAuthorities() {
return ROLE_USER;
}
@Override
public String getUsername() {
return getEmail();
}
@Override
public boolean isAccountNonExpired() {
return true;
}
@Override
public boolean isAccountNonLocked() {
return true;
}
@Override
public boolean isCredentialsNonExpired() {
return true;
}
@Override
public boolean isEnabled() {
return true;
}
}
}

View File

@@ -0,0 +1,34 @@
/*
* Copyright 2020 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package example;
import java.util.Map;
public class MapCustomUserRepository implements CustomUserRepository {
private final Map<String, CustomUser> emailToCustomUser;
public MapCustomUserRepository(Map<String, CustomUser> emailToCustomUser) {
this.emailToCustomUser = emailToCustomUser;
}
@Override
public CustomUser findCustomUserByEmail(String email) {
return this.emailToCustomUser.get(email);
}
}

View File

@@ -0,0 +1,34 @@
/*
* Copyright 2002-2016 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package example;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
/**
* Controller for exposing User information.
*
* @author Rob Winch
*/
@RestController
public class UserController {
@GetMapping("/user")
public CustomUser user(@CurrentUser CustomUser currentUser) {
return currentUser;
}
}

View File

@@ -0,0 +1,55 @@
/*
* Copyright 2012-2016 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package example;
import java.util.HashMap;
import java.util.Map;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.Bean;
/**
* Hello Security application.
*
* @author Joe Grandja
*/
@SpringBootApplication
public class UserDetailsServiceApplication {
public static void main(String[] args) {
SpringApplication.run(UserDetailsServiceApplication.class, args);
}
@Bean
MapCustomUserRepository userRepository() {
// the hashed password was calculated using the following code
// the hash should be done up front, so malicious users cannot discover the
// password
// PasswordEncoder encoder =
// PasswordEncoderFactories.createDelegatingPasswordEncoder();
// String encodedPassword = encoder.encode("password");
// the raw password is "password"
String encodedPassword = "{bcrypt}$2a$10$h/AJueu7Xt9yh3qYuAXtk.WZJ544Uc2kdOKlHu2qQzCh/A3rq46qm";
CustomUser customUser = new CustomUser(1L, "user@example.com", encodedPassword);
Map<String, CustomUser> emailToCustomUser = new HashMap<>();
emailToCustomUser.put(customUser.getEmail(), customUser);
return new MapCustomUserRepository(emailToCustomUser);
}
}

View File

@@ -0,0 +1,111 @@
/*
* Copyright 2012-2016 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package example;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.security.test.context.support.WithUserDetails;
import org.springframework.test.web.servlet.MockMvc;
import static org.hamcrest.Matchers.equalTo;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
/**
* @author Rob Winch
*/
@SpringBootTest
@AutoConfigureMockMvc
public class UserDetailsServiceApplicationTests {
@Autowired
private MockMvc mockMvc;
@Test
void userWhenNotAuthenticated() throws Exception {
// @formatter:off
this.mockMvc.perform(get("/user"))
.andExpect(status().isUnauthorized());
// @formatter:on
}
/**
* WithUserDetails looks up the user from the UserDetailsService. The advantage is
* this is easy to use. The disadvantage, is that the user must exist so it relies our
* our data being set up properly. Alternatively, consider using a custom annotation
* like {@link #userWhenWithMockCustomUserThenOk()}.
*/
@Test
@WithUserDetails("user@example.com")
void userWhenWithUserDetailsThenOk() throws Exception {
// @formatter:off
this.mockMvc.perform(get("/user"))
.andExpect(status().isOk())
.andExpect(jsonPath("$.id", equalTo(1)));
// @formatter:on
}
/**
* WithUser is annotated with WithUserDetails to create a concrete persona for our
* testing. It is a little extra code, but makes it less error prone.
*/
@Test
@WithUser
void userWhenWithUserThenOk() throws Exception {
// @formatter:off
this.mockMvc.perform(get("/user"))
.andExpect(status().isOk())
.andExpect(jsonPath("$.id", equalTo(1)));
// @formatter:on
}
/**
* WithMockCustomUser is a little more code then using {@link WithUserDetails}, but we
* don't need to ensure that the
* {@link org.springframework.security.core.userdetails.UserDetails} is defined. The
* {@link CustomUser} with email "admin@example.com" is not setup, but we can still
* use it for testing here.
*/
@Test
@WithMockCustomUser(email = "admin@example.com")
void userWhenWithMockCustomUserThenOk() throws Exception {
// @formatter:off
this.mockMvc.perform(get("/user"))
.andExpect(status().isOk())
.andExpect(jsonPath("$.email", equalTo("admin@example.com")));
// @formatter:on
}
/**
* {@link WithMockCustomAdmin} is annotated with {@link WithMockCustomUser} to create
* a concrete persona for our testing. This is a little extra code, but it is less
* error prone.
*/
@Test
@WithMockCustomUser(email = "admin@example.com")
void userWhenWithMockCustomAdminThenOk() throws Exception {
// @formatter:off
this.mockMvc.perform(get("/user"))
.andExpect(status().isOk())
.andExpect(jsonPath("$.email", equalTo("admin@example.com")));
// @formatter:on
}
}

View File

@@ -0,0 +1,22 @@
/*
* Copyright 2020 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package example;
@WithMockCustomUser(email = "admin@example.com")
public @interface WithMockCustomAdmin {
}

View File

@@ -0,0 +1,32 @@
/*
* Copyright 2020 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package example;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import org.springframework.security.test.context.support.WithSecurityContext;
@Retention(RetentionPolicy.RUNTIME)
@WithSecurityContext(factory = WithMockCustomUserSecurityContextFactory.class)
public @interface WithMockCustomUser {
String email() default "user@example.com";
int id() default 1;
}

View File

@@ -0,0 +1,43 @@
/*
* Copyright 2020 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package example;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContext;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.test.context.support.WithSecurityContextFactory;
public class WithMockCustomUserSecurityContextFactory implements WithSecurityContextFactory<WithMockCustomUser> {
@Override
public SecurityContext createSecurityContext(WithMockCustomUser mockCustomUser) {
String username = mockCustomUser.email();
// a stub CustomUserRepository that returns the user defined in the annotation
CustomUserRepository userRepository = (email) -> new CustomUser(mockCustomUser.id(), username, "");
// CustomUserRepositoryUserDetailsService ensures our UserDetails is consistent
// with our production application
CustomUserRepositoryUserDetailsService userDetailsService = new CustomUserRepositoryUserDetailsService(
userRepository);
UserDetails userDetails = userDetailsService.loadUserByUsername(username);
SecurityContext securityContext = SecurityContextHolder.createEmptyContext();
securityContext.setAuthentication(new UsernamePasswordAuthenticationToken(userDetails,
userDetails.getPassword(), userDetails.getAuthorities()));
return securityContext;
}
}

View File

@@ -0,0 +1,28 @@
/*
* Copyright 2020 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package example;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import org.springframework.security.test.context.support.WithUserDetails;
@WithUserDetails("user@example.com")
@Retention(RetentionPolicy.RUNTIME)
public @interface WithUser {
}