BAEL-3338: A Guide to AuthenticationManagerResolver in Spring Security

Fix indentation problems in code, do some renaming to sync article with code
This commit is contained in:
maryarm 2019-12-02 16:33:37 +02:00
parent 07461f418a
commit 41a8ea19d3
5 changed files with 53 additions and 38 deletions

View File

@ -19,7 +19,7 @@ import reactor.core.publisher.Mono;
@EnableWebFluxSecurity @EnableWebFluxSecurity
@EnableReactiveMethodSecurity @EnableReactiveMethodSecurity
public class AuthResolverSecurityConfig { public class CustomWebSecurityConfig {
@Bean @Bean
public SecurityWebFilterChain securityWebFilterChain(ServerHttpSecurity http) { public SecurityWebFilterChain securityWebFilterChain(ServerHttpSecurity http) {
@ -35,17 +35,17 @@ public class AuthResolverSecurityConfig {
} }
public AuthenticationWebFilter authenticationWebFilter() { public AuthenticationWebFilter authenticationWebFilter() {
AuthenticationWebFilter filter = new AuthenticationWebFilter(authenticationManagerResolver()); return new AuthenticationWebFilter(resolver());
return filter;
} }
public ReactiveAuthenticationManagerResolver<ServerHttpRequest> authenticationManagerResolver() { public ReactiveAuthenticationManagerResolver<ServerHttpRequest> resolver() {
return request -> { return request -> {
if (request if (request
.getPath() .getPath()
.subPath(0) .subPath(0)
.value() .value()
.startsWith("/employee")) return Mono.just(employeesAuthenticationManager()); .startsWith("/employee"))
return Mono.just(employeesAuthenticationManager());
return Mono.just(customersAuthenticationManager()); return Mono.just(customersAuthenticationManager());
}; };
} }
@ -55,7 +55,11 @@ public class AuthResolverSecurityConfig {
.switchIfEmpty(Mono.error(new UsernameNotFoundException(authentication .switchIfEmpty(Mono.error(new UsernameNotFoundException(authentication
.getPrincipal() .getPrincipal()
.toString()))) .toString())))
.map(b -> new UsernamePasswordAuthenticationToken(authentication.getPrincipal(), authentication.getCredentials(), Collections.singletonList(new SimpleGrantedAuthority("ROLE_USER")))); .map(b -> new UsernamePasswordAuthenticationToken(authentication.getPrincipal(),
authentication.getCredentials(),
Collections.singletonList(new SimpleGrantedAuthority("ROLE_USER"))
)
);
} }
public ReactiveAuthenticationManager employeesAuthenticationManager() { public ReactiveAuthenticationManager employeesAuthenticationManager() {
@ -63,7 +67,12 @@ public class AuthResolverSecurityConfig {
.switchIfEmpty(Mono.error(new UsernameNotFoundException(authentication .switchIfEmpty(Mono.error(new UsernameNotFoundException(authentication
.getPrincipal() .getPrincipal()
.toString()))) .toString())))
.map(b -> new UsernamePasswordAuthenticationToken(authentication.getPrincipal(), authentication.getCredentials(), Collections.singletonList(new SimpleGrantedAuthority("ROLE_USER")))); .map(
b -> new UsernamePasswordAuthenticationToken(authentication.getPrincipal(),
authentication.getCredentials(),
Collections.singletonList(new SimpleGrantedAuthority("ROLE_USER"))
)
);
} }
public Mono<String> customer(Authentication authentication) { public Mono<String> customer(Authentication authentication) {

View File

@ -14,7 +14,8 @@ import org.springframework.util.Base64Utils;
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT, classes = AuthResolverApplication.class) @SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT, classes = AuthResolverApplication.class)
@FixMethodOrder(MethodSorters.NAME_ASCENDING) @FixMethodOrder(MethodSorters.NAME_ASCENDING)
public class AuthResolverIntegrationTest { public class AuthResolverIntegrationTest {
@Autowired private WebTestClient testClient; @Autowired
private WebTestClient testClient;
@Test @Test
public void givenCustomerCredential_whenWelcomeCustomer_thenExpectOk() { public void givenCustomerCredential_whenWelcomeCustomer_thenExpectOk() {

View File

@ -1,12 +1,11 @@
package com.baeldung.authresolver; package com.baeldung.authresolver;
import java.util.Arrays; import java.util.Collections;
import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletRequest;
import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.Configuration;
import org.springframework.security.authentication.AuthenticationManager; import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.AuthenticationManagerResolver; import org.springframework.security.authentication.AuthenticationManagerResolver;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken; import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity; import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter; import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.core.Authentication; import org.springframework.security.core.Authentication;
@ -18,17 +17,18 @@ import org.springframework.security.web.authentication.www.BasicAuthenticationCo
import org.springframework.security.web.authentication.www.BasicAuthenticationFilter; import org.springframework.security.web.authentication.www.BasicAuthenticationFilter;
@Configuration @Configuration
public class AuthResolverWebSecurityConfigurer extends WebSecurityConfigurerAdapter { public class CustomWebSecurityConfigurer extends WebSecurityConfigurerAdapter {
public AuthenticationConverter authenticationConverter() { public AuthenticationConverter authenticationConverter() {
return new BasicAuthenticationConverter(); return new BasicAuthenticationConverter();
} }
public AuthenticationManagerResolver<HttpServletRequest> authenticationManagerResolver() { public AuthenticationManagerResolver<HttpServletRequest> resolver() {
return request -> { return request -> {
if (request if (request
.getPathInfo() .getPathInfo()
.startsWith("/employee")) return employeesAuthenticationManager(); .startsWith("/employee"))
return employeesAuthenticationManager();
return customersAuthenticationManager(); return customersAuthenticationManager();
}; };
} }
@ -36,7 +36,11 @@ public class AuthResolverWebSecurityConfigurer extends WebSecurityConfigurerAdap
public AuthenticationManager customersAuthenticationManager() { public AuthenticationManager customersAuthenticationManager() {
return authentication -> { return authentication -> {
if (isCustomer(authentication)) { if (isCustomer(authentication)) {
return new UsernamePasswordAuthenticationToken(authentication.getPrincipal(), authentication.getCredentials(), Arrays.asList(new SimpleGrantedAuthority("ROLE_USER"))); return new UsernamePasswordAuthenticationToken(
authentication.getPrincipal(),
authentication.getCredentials(),
Collections.singletonList(new SimpleGrantedAuthority("ROLE_USER"))
);
} }
throw new UsernameNotFoundException(authentication throw new UsernameNotFoundException(authentication
.getPrincipal() .getPrincipal()
@ -44,31 +48,35 @@ public class AuthResolverWebSecurityConfigurer extends WebSecurityConfigurerAdap
}; };
} }
public boolean isCustomer(Authentication authentication) { private boolean isCustomer(Authentication authentication) {
return (authentication return (authentication
.getPrincipal() .getPrincipal()
.toString() .toString()
.startsWith("customer")); .startsWith("customer"));
} }
public boolean isEmployee(Authentication authentication) { private boolean isEmployee(Authentication authentication) {
return (authentication return (authentication
.getPrincipal() .getPrincipal()
.toString() .toString()
.startsWith("employee")); .startsWith("employee"));
} }
public AuthenticationFilter authenticationFilter(AuthenticationManagerResolver<HttpServletRequest> resolver, AuthenticationConverter converter) { private AuthenticationFilter authenticationFilter() {
AuthenticationFilter ret = new AuthenticationFilter(resolver, converter); AuthenticationFilter ret = new AuthenticationFilter(
ret.setSuccessHandler((httpServletRequest, httpServletResponse, authentication) -> { resolver(), authenticationConverter());
}); ret.setSuccessHandler((request, response, auth) -> {});
return ret; return ret;
} }
public AuthenticationManager employeesAuthenticationManager() { private AuthenticationManager employeesAuthenticationManager() {
return authentication -> { return authentication -> {
if (isEmployee(authentication)) { if (isEmployee(authentication)) {
return new UsernamePasswordAuthenticationToken(authentication.getPrincipal(), authentication.getCredentials(), Arrays.asList(new SimpleGrantedAuthority("ROLE_USER"))); return new UsernamePasswordAuthenticationToken(
authentication.getPrincipal(),
authentication.getCredentials(),
Collections.singletonList(new SimpleGrantedAuthority("ROLE_USER"))
);
} }
throw new UsernameNotFoundException(authentication throw new UsernameNotFoundException(authentication
.getPrincipal() .getPrincipal()
@ -77,16 +85,11 @@ public class AuthResolverWebSecurityConfigurer extends WebSecurityConfigurerAdap
} }
@Override @Override
protected void configure(HttpSecurity http) throws Exception { protected void configure(HttpSecurity http) {
http http.addFilterBefore(
.addFilterBefore( authenticationFilter(),
authenticationFilter( BasicAuthenticationFilter.class
authenticationManagerResolver(), authenticationConverter()), );
BasicAuthenticationFilter.class);
} }
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
super.configure(auth);
}
} }

View File

@ -23,9 +23,11 @@ import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.
@FixMethodOrder(MethodSorters.NAME_ASCENDING) @FixMethodOrder(MethodSorters.NAME_ASCENDING)
public class AuthResolverIntegrationTest { public class AuthResolverIntegrationTest {
@Autowired private FilterChainProxy springSecurityFilterChain; @Autowired
private FilterChainProxy springSecurityFilterChain;
@Autowired private WebApplicationContext wac; @Autowired
private WebApplicationContext wac;
private MockMvc mockMvc; private MockMvc mockMvc;