Skip to content

Commit 3459d3a

Browse files
chrisoberlepivovarit
authored andcommitted
BAEL-1418 Spring Security with Extra Login Fields (eugenp#3476)
* 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 * BAEL-1418 Spring Security with Extra Login Fields * added additional custom example * refactored and added tests * remove final keywords and serialVersionUID constants
1 parent db90361 commit 3459d3a

26 files changed

Lines changed: 597 additions & 102 deletions
Lines changed: 50 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,50 @@
1+
package com.baeldung.loginextrafieldscustom;
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.core.Authentication;
8+
import org.springframework.security.core.AuthenticationException;
9+
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;
10+
11+
public class CustomAuthenticationFilter extends UsernamePasswordAuthenticationFilter {
12+
13+
public static final String SPRING_SECURITY_FORM_DOMAIN_KEY = "domain";
14+
15+
@Override
16+
public Authentication attemptAuthentication(HttpServletRequest request, HttpServletResponse response)
17+
throws AuthenticationException {
18+
19+
if (!request.getMethod().equals("POST")) {
20+
throw new AuthenticationServiceException("Authentication method not supported: "
21+
+ request.getMethod());
22+
}
23+
24+
CustomAuthenticationToken authRequest = getAuthRequest(request);
25+
setDetails(request, authRequest);
26+
return this.getAuthenticationManager().authenticate(authRequest);
27+
}
28+
29+
private CustomAuthenticationToken getAuthRequest(HttpServletRequest request) {
30+
String username = obtainUsername(request);
31+
String password = obtainPassword(request);
32+
String domain = obtainDomain(request);
33+
34+
if (username == null) {
35+
username = "";
36+
}
37+
if (password == null) {
38+
password = "";
39+
}
40+
if (domain == null) {
41+
domain = "";
42+
}
43+
44+
return new CustomAuthenticationToken(username, password, domain);
45+
}
46+
47+
private String obtainDomain(HttpServletRequest request) {
48+
return request.getParameter(SPRING_SECURITY_FORM_DOMAIN_KEY);
49+
}
50+
}
Lines changed: 28 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,28 @@
1+
package com.baeldung.loginextrafieldscustom;
2+
3+
import java.util.Collection;
4+
5+
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
6+
import org.springframework.security.core.GrantedAuthority;
7+
8+
public class CustomAuthenticationToken extends UsernamePasswordAuthenticationToken {
9+
10+
private String domain;
11+
12+
public CustomAuthenticationToken(Object principal, Object credentials, String domain) {
13+
super(principal, credentials);
14+
this.domain = domain;
15+
super.setAuthenticated(false);
16+
}
17+
18+
public CustomAuthenticationToken(Object principal, Object credentials, String domain,
19+
Collection<? extends GrantedAuthority> authorities) {
20+
super(principal, credentials, authorities);
21+
this.domain = domain;
22+
super.setAuthenticated(true); // must use super, as we override
23+
}
24+
25+
public String getDomain() {
26+
return this.domain;
27+
}
28+
}
Lines changed: 92 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,92 @@
1+
package com.baeldung.loginextrafieldscustom;
2+
3+
import org.springframework.security.authentication.BadCredentialsException;
4+
import org.springframework.security.authentication.InternalAuthenticationServiceException;
5+
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
6+
import org.springframework.security.authentication.dao.AbstractUserDetailsAuthenticationProvider;
7+
import org.springframework.security.core.AuthenticationException;
8+
import org.springframework.security.core.userdetails.UserDetails;
9+
import org.springframework.security.core.userdetails.UsernameNotFoundException;
10+
import org.springframework.security.crypto.password.PasswordEncoder;
11+
import org.springframework.util.Assert;
12+
13+
public class CustomUserDetailsAuthenticationProvider extends AbstractUserDetailsAuthenticationProvider {
14+
15+
/**
16+
* The plaintext password used to perform
17+
* PasswordEncoder#matches(CharSequence, String)} on when the user is
18+
* not found to avoid SEC-2056.
19+
*/
20+
private static final String USER_NOT_FOUND_PASSWORD = "userNotFoundPassword";
21+
22+
private PasswordEncoder passwordEncoder;
23+
private CustomUserDetailsService userDetailsService;
24+
25+
/**
26+
* The password used to perform
27+
* {@link PasswordEncoder#matches(CharSequence, String)} on when the user is
28+
* not found to avoid SEC-2056. This is necessary, because some
29+
* {@link PasswordEncoder} implementations will short circuit if the password is not
30+
* in a valid format.
31+
*/
32+
private String userNotFoundEncodedPassword;
33+
34+
public CustomUserDetailsAuthenticationProvider(PasswordEncoder passwordEncoder, CustomUserDetailsService userDetailsService) {
35+
this.passwordEncoder = passwordEncoder;
36+
this.userDetailsService = userDetailsService;
37+
}
38+
39+
@Override
40+
protected void additionalAuthenticationChecks(UserDetails userDetails, UsernamePasswordAuthenticationToken authentication)
41+
throws AuthenticationException {
42+
43+
if (authentication.getCredentials() == null) {
44+
logger.debug("Authentication failed: no credentials provided");
45+
throw new BadCredentialsException(
46+
messages.getMessage("AbstractUserDetailsAuthenticationProvider.badCredentials", "Bad credentials"));
47+
}
48+
49+
String presentedPassword = authentication.getCredentials()
50+
.toString();
51+
52+
if (!passwordEncoder.matches(presentedPassword, userDetails.getPassword())) {
53+
logger.debug("Authentication failed: password does not match stored value");
54+
throw new BadCredentialsException(
55+
messages.getMessage("AbstractUserDetailsAuthenticationProvider.badCredentials", "Bad credentials"));
56+
}
57+
}
58+
59+
@Override
60+
protected void doAfterPropertiesSet() throws Exception {
61+
Assert.notNull(this.userDetailsService, "A UserDetailsService must be set");
62+
this.userNotFoundEncodedPassword = this.passwordEncoder.encode(USER_NOT_FOUND_PASSWORD);
63+
}
64+
65+
@Override
66+
protected UserDetails retrieveUser(String username, UsernamePasswordAuthenticationToken authentication)
67+
throws AuthenticationException {
68+
CustomAuthenticationToken auth = (CustomAuthenticationToken) authentication;
69+
UserDetails loadedUser;
70+
71+
try {
72+
loadedUser = this.userDetailsService.loadUserByUsernameAndDomain(auth.getPrincipal()
73+
.toString(), auth.getDomain());
74+
} catch (UsernameNotFoundException notFound) {
75+
if (authentication.getCredentials() != null) {
76+
String presentedPassword = authentication.getCredentials()
77+
.toString();
78+
passwordEncoder.matches(presentedPassword, userNotFoundEncodedPassword);
79+
}
80+
throw notFound;
81+
} catch (Exception repositoryProblem) {
82+
throw new InternalAuthenticationServiceException(repositoryProblem.getMessage(), repositoryProblem);
83+
}
84+
85+
if (loadedUser == null) {
86+
throw new InternalAuthenticationServiceException("UserDetailsService returned null, "
87+
+ "which is an interface contract violation");
88+
}
89+
return loadedUser;
90+
}
91+
92+
}
Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,10 @@
1+
package com.baeldung.loginextrafieldscustom;
2+
3+
import org.springframework.security.core.userdetails.UserDetails;
4+
import org.springframework.security.core.userdetails.UsernameNotFoundException;
5+
6+
public interface CustomUserDetailsService {
7+
8+
UserDetails loadUserByUsernameAndDomain(String username, String domain) throws UsernameNotFoundException;
9+
10+
}
Lines changed: 30 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,30 @@
1+
package com.baeldung.loginextrafieldscustom;
2+
3+
import org.apache.commons.lang3.StringUtils;
4+
import org.springframework.security.core.userdetails.UserDetails;
5+
import org.springframework.security.core.userdetails.UsernameNotFoundException;
6+
import org.springframework.stereotype.Service;
7+
8+
@Service("userDetailsService")
9+
public class CustomUserDetailsServiceImpl implements CustomUserDetailsService {
10+
11+
private UserRepository userRepository;
12+
13+
public CustomUserDetailsServiceImpl(UserRepository userRepository) {
14+
this.userRepository = userRepository;
15+
}
16+
17+
@Override
18+
public UserDetails loadUserByUsernameAndDomain(String username, String domain) throws UsernameNotFoundException {
19+
if (StringUtils.isAnyBlank(username, domain)) {
20+
throw new UsernameNotFoundException("Username and domain must be provided");
21+
}
22+
User user = userRepository.findUser(username, domain);
23+
if (user == null) {
24+
throw new UsernameNotFoundException(
25+
String.format("Username not found for domain, username=%s, domain=%s",
26+
username, domain));
27+
}
28+
return user;
29+
}
30+
}

spring-5-security/src/main/java/com/baeldung/securityextrafields/CustomUserRepository.java renamed to spring-5-security/src/main/java/com/baeldung/loginextrafieldscustom/CustomUserRepository.java

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
package com.baeldung.securityextrafields;
1+
package com.baeldung.loginextrafieldscustom;
22

33
import java.util.ArrayList;
44
import java.util.Collection;

spring-5-security/src/main/java/com/baeldung/securityextrafields/SpringExtraLoginFieldsApplication.java renamed to spring-5-security/src/main/java/com/baeldung/loginextrafieldscustom/ExtraLoginFieldsApplication.java

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,13 +1,13 @@
1-
package com.baeldung.securityextrafields;
1+
package com.baeldung.loginextrafieldscustom;
22

33
import org.springframework.boot.SpringApplication;
44
import org.springframework.boot.autoconfigure.SpringBootApplication;
55

66
@SpringBootApplication
7-
public class SpringExtraLoginFieldsApplication {
7+
public class ExtraLoginFieldsApplication {
88

99
public static void main(String[] args) {
10-
SpringApplication.run(SpringExtraLoginFieldsApplication.class, args);
10+
SpringApplication.run(ExtraLoginFieldsApplication.class, args);
1111
}
1212

1313
}
Lines changed: 62 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,62 @@
1+
package com.baeldung.loginextrafieldscustom;
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.config.annotation.authentication.builders.AuthenticationManagerBuilder;
7+
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
8+
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
9+
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
10+
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
11+
import org.springframework.security.crypto.password.PasswordEncoder;
12+
import org.springframework.security.web.authentication.SimpleUrlAuthenticationFailureHandler;
13+
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;
14+
15+
@EnableWebSecurity
16+
@PropertySource("classpath:/application-extrafields.properties")
17+
public class SecurityConfig extends WebSecurityConfigurerAdapter {
18+
19+
@Autowired
20+
private CustomUserDetailsService userDetailsService;
21+
22+
@Override
23+
protected void configure(HttpSecurity http) throws Exception {
24+
25+
http
26+
.addFilterBefore(authenticationFilter(), UsernamePasswordAuthenticationFilter.class)
27+
.authorizeRequests()
28+
.antMatchers("/css/**", "/index").permitAll()
29+
.antMatchers("/user/**").authenticated()
30+
.and()
31+
.formLogin().loginPage("/login")
32+
.and()
33+
.logout()
34+
.logoutUrl("/logout");
35+
}
36+
37+
public CustomAuthenticationFilter authenticationFilter() throws Exception {
38+
CustomAuthenticationFilter filter = new CustomAuthenticationFilter();
39+
filter.setAuthenticationManager(authenticationManagerBean());
40+
filter.setAuthenticationFailureHandler(failureHandler());
41+
return filter;
42+
}
43+
44+
@Autowired
45+
public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
46+
auth.authenticationProvider(authProvider());
47+
}
48+
49+
public AuthenticationProvider authProvider() {
50+
CustomUserDetailsAuthenticationProvider provider
51+
= new CustomUserDetailsAuthenticationProvider(passwordEncoder(), userDetailsService);
52+
return provider;
53+
}
54+
55+
public SimpleUrlAuthenticationFailureHandler failureHandler() {
56+
return new SimpleUrlAuthenticationFailureHandler("/login?error=true");
57+
}
58+
59+
public PasswordEncoder passwordEncoder() {
60+
return new BCryptPasswordEncoder();
61+
}
62+
}

spring-5-security/src/main/java/com/baeldung/securityextrafields/User.java renamed to spring-5-security/src/main/java/com/baeldung/loginextrafieldscustom/User.java

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
package com.baeldung.securityextrafields;
1+
package com.baeldung.loginextrafieldscustom;
22

33
import java.util.Collection;
44

@@ -8,7 +8,7 @@ public class User extends org.springframework.security.core.userdetails.User {
88

99
private static final long serialVersionUID = 1L;
1010

11-
private final String domain;
11+
private String domain;
1212

1313
public User(String username, String domain, String password, boolean enabled,
1414
boolean accountNonExpired, boolean credentialsNonExpired,

spring-5-security/src/main/java/com/baeldung/securityextrafields/UserRepository.java renamed to spring-5-security/src/main/java/com/baeldung/loginextrafieldscustom/UserRepository.java

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
package com.baeldung.securityextrafields;
1+
package com.baeldung.loginextrafieldscustom;
22

33
public interface UserRepository {
44

0 commit comments

Comments
 (0)