Skip to content

Commit bff1f7b

Browse files
chrisoberlepivovarit
authored andcommitted
BAEL-1418 - spring security with extra login fields (eugenp#3413)
* BAEL-1418 - spring security with extra login fields * change delimeter for username/domain concatenation * remove unnecessary class * move source to spring-5-security module * finish moving example code to spring-5-security module * fix formatting in pom * adjust spacing
1 parent aa0785c commit bff1f7b

15 files changed

Lines changed: 472 additions & 0 deletions

File tree

‎spring-5-security/pom.xml‎

Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -30,6 +30,10 @@
3030
<groupId>org.springframework.boot</groupId>
3131
<artifactId>spring-boot-starter-thymeleaf</artifactId>
3232
</dependency>
33+
<dependency>
34+
<groupId>org.thymeleaf.extras</groupId>
35+
<artifactId>thymeleaf-extras-springsecurity4</artifactId>
36+
</dependency>
3337

3438
<!-- oauth2 -->
3539
<dependency>
@@ -40,6 +44,21 @@
4044
<groupId>org.springframework.security</groupId>
4145
<artifactId>spring-security-oauth2-jose</artifactId>
4246
</dependency>
47+
48+
<dependency>
49+
<groupId>org.springframework</groupId>
50+
<artifactId>spring-test</artifactId>
51+
</dependency>
52+
<dependency>
53+
<groupId>org.springframework.boot</groupId>
54+
<artifactId>spring-boot-starter-test</artifactId>
55+
<scope>test</scope>
56+
</dependency>
57+
<dependency>
58+
<groupId>org.springframework.security</groupId>
59+
<artifactId>spring-security-test</artifactId>
60+
<scope>test</scope>
61+
</dependency>
4362
</dependencies>
4463

4564
<build>
Lines changed: 54 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,54 @@
1+
package com.baeldung.securityextrafields;
2+
3+
import javax.servlet.http.HttpServletRequest;
4+
import javax.servlet.http.HttpServletResponse;
5+
6+
import org.springframework.security.authentication.AuthenticationServiceException;
7+
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
8+
import org.springframework.security.core.Authentication;
9+
import org.springframework.security.core.AuthenticationException;
10+
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;
11+
12+
public class CustomAuthenticationFilter extends UsernamePasswordAuthenticationFilter {
13+
14+
public static final String SPRING_SECURITY_FORM_DOMAIN_KEY = "domain";
15+
16+
@Override
17+
public Authentication attemptAuthentication(HttpServletRequest request, HttpServletResponse response)
18+
throws AuthenticationException {
19+
20+
if (!request.getMethod()
21+
.equals("POST")) {
22+
throw new AuthenticationServiceException("Authentication method not supported: " + request.getMethod());
23+
}
24+
25+
UsernamePasswordAuthenticationToken authRequest = getAuthRequest(request);
26+
setDetails(request, authRequest);
27+
return this.getAuthenticationManager()
28+
.authenticate(authRequest);
29+
}
30+
31+
private UsernamePasswordAuthenticationToken getAuthRequest(HttpServletRequest request) {
32+
String username = obtainUsername(request);
33+
String password = obtainPassword(request);
34+
String domain = obtainDomain(request);
35+
36+
if (username == null) {
37+
username = "";
38+
}
39+
if (password == null) {
40+
password = "";
41+
}
42+
if (domain == null) {
43+
domain = "";
44+
}
45+
46+
String usernameDomain = String.format("%s%s%s", username.trim(),
47+
String.valueOf(Character.LINE_SEPARATOR), domain);
48+
return new UsernamePasswordAuthenticationToken(usernameDomain, password);
49+
}
50+
51+
private String obtainDomain(HttpServletRequest request) {
52+
return request.getParameter(SPRING_SECURITY_FORM_DOMAIN_KEY);
53+
}
54+
}
Lines changed: 32 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,32 @@
1+
package com.baeldung.securityextrafields;
2+
3+
import org.apache.commons.lang3.StringUtils;
4+
import org.springframework.security.core.userdetails.UserDetails;
5+
import org.springframework.security.core.userdetails.UserDetailsService;
6+
import org.springframework.security.core.userdetails.UsernameNotFoundException;
7+
import org.springframework.stereotype.Service;
8+
9+
@Service("userDetailsService")
10+
public class CustomUserDetailsService implements UserDetailsService {
11+
12+
private final UserRepository userRepository;
13+
14+
public CustomUserDetailsService(UserRepository userRepository) {
15+
this.userRepository = userRepository;
16+
}
17+
18+
@Override
19+
public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
20+
String[] usernameAndDomain = StringUtils.split(username, String.valueOf(Character.LINE_SEPARATOR));
21+
if (usernameAndDomain == null || usernameAndDomain.length != 2) {
22+
throw new UsernameNotFoundException("Username and domain must be provided");
23+
}
24+
User user = userRepository.findUser(usernameAndDomain[0], usernameAndDomain[1]);
25+
if (user == null) {
26+
throw new UsernameNotFoundException(
27+
String.format("Username not found for domain, username=%s, domain=%s",
28+
usernameAndDomain[0], usernameAndDomain[1]));
29+
}
30+
return user;
31+
}
32+
}
Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,26 @@
1+
package com.baeldung.securityextrafields;
2+
3+
import java.util.ArrayList;
4+
import java.util.Collection;
5+
6+
import org.apache.commons.lang3.StringUtils;
7+
import org.springframework.security.core.GrantedAuthority;
8+
import org.springframework.stereotype.Repository;
9+
10+
@Repository("userRepository")
11+
public class CustomUserRepository implements UserRepository {
12+
13+
@Override
14+
public User findUser(String username, String domain) {
15+
if (StringUtils.isAnyBlank(username, domain)) {
16+
return null;
17+
} else {
18+
Collection<? extends GrantedAuthority> authorities = new ArrayList<>();
19+
User user = new User(username, domain,
20+
"$2a$10$U3GhSMpsMSOE8Kqsbn58/edxDBKlVuYMh7qk/7ErApYFjJzi2VG5K", true,
21+
true, true, true, authorities);
22+
return user;
23+
}
24+
}
25+
26+
}
Lines changed: 65 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,65 @@
1+
package com.baeldung.securityextrafields;
2+
3+
import org.springframework.beans.factory.annotation.Autowired;
4+
import org.springframework.context.annotation.PropertySource;
5+
import org.springframework.security.authentication.AuthenticationProvider;
6+
import org.springframework.security.authentication.dao.DaoAuthenticationProvider;
7+
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
8+
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
9+
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
10+
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
11+
import org.springframework.security.core.userdetails.UserDetailsService;
12+
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
13+
import org.springframework.security.crypto.password.PasswordEncoder;
14+
import org.springframework.security.web.authentication.SimpleUrlAuthenticationFailureHandler;
15+
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;
16+
17+
@EnableWebSecurity
18+
@PropertySource("classpath:/application-extrafields.properties")
19+
public class SecurityConfig extends WebSecurityConfigurerAdapter {
20+
21+
@Autowired
22+
private UserDetailsService userDetailsService;
23+
24+
@Override
25+
protected void configure(HttpSecurity http) throws Exception {
26+
27+
http
28+
.addFilterBefore(authenticationFilter(), UsernamePasswordAuthenticationFilter.class)
29+
.authorizeRequests()
30+
.antMatchers("/css/**", "/index").permitAll()
31+
.antMatchers("/user/**").authenticated()
32+
.and()
33+
.formLogin().loginPage("/login")
34+
.and()
35+
.logout()
36+
.logoutUrl("/logout");
37+
}
38+
39+
public CustomAuthenticationFilter authenticationFilter() throws Exception {
40+
CustomAuthenticationFilter filter = new CustomAuthenticationFilter();
41+
filter.setAuthenticationManager(authenticationManagerBean());
42+
filter.setAuthenticationFailureHandler(failureHandler());
43+
return filter;
44+
}
45+
46+
@Autowired
47+
public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
48+
auth.authenticationProvider(authProvider());
49+
}
50+
51+
public AuthenticationProvider authProvider() {
52+
DaoAuthenticationProvider provider = new DaoAuthenticationProvider();
53+
provider.setUserDetailsService(userDetailsService);
54+
provider.setPasswordEncoder(passwordEncoder());
55+
return provider;
56+
}
57+
58+
public SimpleUrlAuthenticationFailureHandler failureHandler() {
59+
return new SimpleUrlAuthenticationFailureHandler("/login?error=true");
60+
}
61+
62+
public PasswordEncoder passwordEncoder() {
63+
return new BCryptPasswordEncoder();
64+
}
65+
}
Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,13 @@
1+
package com.baeldung.securityextrafields;
2+
3+
import org.springframework.boot.SpringApplication;
4+
import org.springframework.boot.autoconfigure.SpringBootApplication;
5+
6+
@SpringBootApplication
7+
public class SpringExtraLoginFieldsApplication {
8+
9+
public static void main(String[] args) {
10+
SpringApplication.run(SpringExtraLoginFieldsApplication.class, args);
11+
}
12+
13+
}
Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,23 @@
1+
package com.baeldung.securityextrafields;
2+
3+
import java.util.Collection;
4+
5+
import org.springframework.security.core.GrantedAuthority;
6+
7+
public class User extends org.springframework.security.core.userdetails.User {
8+
9+
private static final long serialVersionUID = 1L;
10+
11+
private final String domain;
12+
13+
public User(String username, String domain, String password, boolean enabled,
14+
boolean accountNonExpired, boolean credentialsNonExpired,
15+
boolean accountNonLocked, Collection<? extends GrantedAuthority> authorities) {
16+
super(username, password, enabled, accountNonExpired, credentialsNonExpired, accountNonLocked, authorities);
17+
this.domain = domain;
18+
}
19+
20+
public String getDomain() {
21+
return domain;
22+
}
23+
}
Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,7 @@
1+
package com.baeldung.securityextrafields;
2+
3+
public interface UserRepository {
4+
5+
public User findUser(String username, String domain);
6+
7+
}
Lines changed: 51 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,51 @@
1+
package com.baeldung.securityextrafields;
2+
3+
import java.util.Optional;
4+
5+
import org.springframework.security.authentication.AnonymousAuthenticationToken;
6+
import org.springframework.security.core.Authentication;
7+
import org.springframework.security.core.context.SecurityContextHolder;
8+
import org.springframework.stereotype.Controller;
9+
import org.springframework.ui.Model;
10+
import org.springframework.web.bind.annotation.RequestMapping;
11+
12+
@Controller
13+
public class WebController {
14+
15+
@RequestMapping("/")
16+
public String root() {
17+
return "redirect:/index";
18+
}
19+
20+
@RequestMapping("/index")
21+
public String index(Model model) {
22+
getDomain().ifPresent(d -> {
23+
model.addAttribute("domain", d);
24+
});
25+
return "index";
26+
}
27+
28+
@RequestMapping("/user/index")
29+
public String userIndex(Model model) {
30+
getDomain().ifPresent(d -> {
31+
model.addAttribute("domain", d);
32+
});
33+
return "user/index";
34+
}
35+
36+
@RequestMapping("/login")
37+
public String login() {
38+
return "login";
39+
}
40+
41+
private Optional<String> getDomain() {
42+
Authentication auth = SecurityContextHolder.getContext()
43+
.getAuthentication();
44+
String domain = null;
45+
if (auth != null && !auth.getClass().equals(AnonymousAuthenticationToken.class)) {
46+
User user = (User) auth.getPrincipal();
47+
domain = user.getDomain();
48+
}
49+
return Optional.ofNullable(domain);
50+
}
51+
}
Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
spring.thymeleaf.prefix = classpath:/templatesextrafields/

0 commit comments

Comments
 (0)