AuthenticationFailureBadCredentialsEvent never called - spring-boot

I use spring-boot 2.6.8 with spring security
When user don't enter correct information, i would like to do an operation.
So I created this class.
#Component
public class AuthenticationFailureEventListener implements ApplicationListener<AuthenticationFailureBadCredentialsEvent {
private LoginAttemptService loginAttemptService;
#Override
public void onApplicationEvent(AuthenticationFailureBadCredentialsEvent e) {
WebAuthenticationDetails auth = (WebAuthenticationDetails) e.getAuthentication().getDetails();
loginAttemptService.loginFailed(e.getAuthentication().getName(), auth.getRemoteAddress());
}
}
If a user enter a bad password, this event is never called
Edit
For the security, I have this
#EnableWebSecurity
#EnableGlobalMethodSecurity(prePostEnabled = true)
public class SecurityConfig extends WebSecurityConfigurerAdapter {
#Autowired
private UserDetailsService userDetailsService;
#Autowired
private AuthenticationEventPublisher authenticationEventPublisher;
#Autowired
private PasswordEncoder passwordEncoder;
#Autowired
private CustomAuthenticationSuccessHandler customAuthenticationSuccessHandler;
#Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
auth.authenticationEventPublisher(authenticationEventPublisher).userDetailsService(userDetailsService)
.passwordEncoder(passwordEncoder);
}
...
}

The events are not published out of the box. You need to also declare an AuthenticationEventPublisher with code like this:
#Bean
public AuthenticationEventPublisher authenticationEventPublisher(
ApplicationEventPublisher applicationEventPublisher
) {
return new DefaultAuthenticationEventPublisher(applicationEventPublisher);
}
Please also have a look at this part of the reference documentation: https://docs.spring.io/spring-security/reference/servlet/authentication/events.html

Related

configure spring security and test api postman

Iam working in springboot application and iam trying to save the data in database, code is executing properly and not getting any error during execution but when iam trying to post the url in postman iam getting status: 401 unauthorized
any quick suggestion
public class SecurityConfiguration extends WebSecurityConfigurerAdapter{
#Autowired
UsersService userService;
#Autowired
PasswordEncoder passwordEncoder;
#Override
protected void configure(HttpSecurity http) throws Exception {
// TODO Auto-generated method stub
http.csrf().disable() //TODO implementer csrf
.cors().and().authorizeRequests().antMatchers("/").permitAll()
.antMatchers("/login").permitAll()
.antMatchers(HttpMethod.POST,"/ add-users").permitAll()
.and().authorizeRequests().anyRequest().authenticated();
}
#Service
public class UsersService implements UserDetailsService{
#Autowired
UsersRepository repo;
// #Autowired
// private PasswordEncoder passwordEncoder;
public Users save(Users u) {
String encodpass=new BCryptPasswordEncoder().encode(u.getPassword());
String confpass=new BCryptPasswordEncoder().encode(u.getConfirmepass());
u.setConfirmepass(confpass);
u.setPassword(encodpass);
u.setLock(false);
u.setEnable(true);
return repo.save(u);
}
#RestController
public class UsersController {
#Autowired
private UsersService service;
#PostMapping("/add-users")
public Users add(#RequestBody Users u) {
return service.save(u);
}`
First of all
remove this space and retest :
.antMatchers(HttpMethod.POST,"/ add-users").permitAll()
to
.antMatchers(HttpMethod.POST,"/add-users").permitAll()

Test spring boot controllers with JUnit5+Spring Security

I have a spring boot application and want to write integration tests for controllers. It is my SecurityConfig:
#Configuration
#EnableWebSecurity
#RequiredArgsConstructor
public class SecurityConfig extends WebSecurityConfigurerAdapter {
private final MyUserDetailsService userDetailsService;
private final SessionAuthenticationProvider authenticationProvider;
private final SessionAuthenticationFilter sessionAuthenticationFilter;
#Override
public void configure(WebSecurity web) {
//...
}
#Override
protected void configure(HttpSecurity http) throws Exception {
/...
}
#Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
auth.authenticationProvider(authenticationProvider);
auth.userDetailsService(userDetailsService);
}
}
It is my controller:
#RestController
public class MyController {
//...
#GetMapping("/test")
public List<TestDto> getAll(){
List<TestDto> tests= testService.findAll(authService.getLoggedUser().getId());
return mapper.toTestDtos(tests);
}
}
I Created a test(JUnit 5):
#WebMvcTest(TestController.class)
class TestControllerTest {
#Autowired
private MockMvc mockMvc;
#MockBean(name = "mockTestService")
private TestService testService;
#Autowired
private TestMapper mapper;
#MockBean(name = "mockAuthService")
private AuthService authService;
private Test test;
#BeforeEach
void setUp() {
User user = new Test();
user.setId("userId");
when(authService.getLoggedUser()).thenReturn(user);
test = new Facility();
test.setId("id");
test.setName("name");
when(testService.findAll("userId")).thenReturn(singletonList(test));
}
#Test
void shouldReturnAllIpaFacilitiesForCurrentTenant() throws Exception {
mockMvc.perform(get("/test").contentType(MediaType.APPLICATION_JSON))
.andDo(print())
.andExpect(status().isOk())
.andExpect(jsonPath("$..id").value(test.getId()))
.andExpect(jsonPath("$..timeOut").value(test.getName()));
}
}
When I start the test I get an exception: Consider defining a bean of type 'com.auth.MyUserDetailsService' in your configuration.
It happens because I have not UserDetailsService bean in the test. What should I do:
Add 3 beans are required for SecurityConfig, like:
#MockBean
MyUserDetailsService userDetailsService;
#MockBean
SessionAuthenticationProvider authenticationProvider;
#MockBean
SessionAuthenticationFilter sessionAuthenticationFilter;
Add test implementation of SecurityConfig
something else
Which approach is better?
For writing tests for your controller endpoints using #WebMvcTest I would use the great integration from MockMvc and Spring Security.
Make sure you have the following dependency:
<dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-test</artifactId>
<scope>test</scope>
</dependency>
Next, you can mock the authenticated user for your MockMvc requests and also set the username, roles, etc.
Either use an annotation to populate the authenticated user inside the SecurityContext for the test:
#Test
#WithMockUser("youruser")
public void shouldReturnAllIpaFacilitiesForCurrentTenant() throws Exception {
// ...
}
Or use one of the SecurityMockMvcRequestPostProcessors:
this.mockMvc
.perform(
post("/api/tasks")
.contentType(MediaType.APPLICATION_JSON)
.content("{\"taskTitle\": \"Learn MockMvc\"}")
.with(csrf())
.with(SecurityMockMvcRequestPostProcessors.user("duke"))
)
.andExpect(status().isCreated());
You can find more information on this here.

spring boot oauth2 ResourceServerConfigurerAdapter not protecting resources

spring boot oauth2 ResourceServerConfigurerAdapter not protecting resourcs
/oauth/token working fine.
.antMatchers("/api/waiter/**") in resourceserver is accessible by public.
.antMatchers("/api/waiter/").hasAnyRole(RESTRWAITER).antMatchers("/api/waiter/").authenticated()
i have clearly defined role for api.
seem like problem in resource server configuration.
My Codes Are
#Configuration
#EnableResourceServer
#Order(2)
public class ResourceServerConfig extends ResourceServerConfigurerAdapter {
#Value("${spring.datasource.driver-class-name}")
private String oauthClass;
#Value("${spring.datasource.url}")
private String oauthUrl;
#Value("${spring.datasource.username}")
private String username;
#Value("${spring.datasource.password}")
private String password;
private static final String RESTRWAITER = "WAITER";
#Bean
public TokenStore tokenStore() {
DataSource tokenDataSource = DataSourceBuilder.create().driverClassName(oauthClass).username(username)
.password(password).url(oauthUrl).build();
return new JdbcTokenStore(tokenDataSource);
}
#Override
public void configure(ResourceServerSecurityConfigurer resources) throws Exception {
resources.resourceId("scout").tokenStore(tokenStore());
}
#Override
public void configure(HttpSecurity http) throws Exception {
http.anonymous().disable().requestMatchers().antMatchers("/api/waiter/**").and().authorizeRequests()
.antMatchers("/api/waiter/**").hasAnyRole(RESTRWAITER).antMatchers("/api/waiter/**").authenticated().and().exceptionHandling()
.accessDeniedHandler(new OAuth2AccessDeniedHandler());
}
}
And
AuthorizationServerConfig
#Configuration
#EnableAuthorizationServer
public class AuthorizationServerConfig extends AuthorizationServerConfigurerAdapter {
#Autowired
private AuthenticationManager authenticationManager;
#Value("${spring.datasource.driver-class-name}")
private String oauthClass;
#Value("${spring.datasource.url}")
private String oauthUrl;
#Value("${spring.datasource.username}")
private String username;
#Value("${spring.datasource.password}")
private String password;
#Bean
public TokenStore tokenStore() {
System.out.println(username);
DataSource tokenDataSource = DataSourceBuilder.create().driverClassName(oauthClass).username(username)
.password(password).url(oauthUrl).build();
return new JdbcTokenStore(tokenDataSource);
}
#Override
public void configure(AuthorizationServerEndpointsConfigurer endpoints) {
endpoints.authenticationManager(authenticationManager);
endpoints.tokenStore(tokenStore());
}
#Override
public void configure(AuthorizationServerSecurityConfigurer security) throws Exception {
security.tokenKeyAccess("permitAll()").checkTokenAccess("isAuthenticated()")
.allowFormAuthenticationForClients();
}
#Bean
public PasswordEncoder getPasswordEncoder() {
return new BCryptPasswordEncoder();
}
#Override
public void configure(ClientDetailsServiceConfigurer clients) throws Exception {
clients.inMemory().withClient("clientapp").secret(getPasswordEncoder().encode("123456"))
.authorizedGrantTypes("password", "authorization_code", "refresh_token").authorities("READ_ONLY_CLIENT")
.scopes("read_profile_info").resourceIds("oauth2-resource").redirectUris("http://localhost:8081/login")
.accessTokenValiditySeconds(120000).refreshTokenValiditySeconds(240000);
}
}
and
SecurityConfiguration
#Configuration
#EnableWebSecurity
#Order(1)
#EnableGlobalMethodSecurity(prePostEnabled = true, securedEnabled = true, proxyTargetClass = true)
#EnableAspectJAutoProxy(proxyTargetClass = true)
public class SecurityConfiguration extends WebSecurityConfigurerAdapter {
private static final String SYSTEM = "SYSTEM";
private static final String RESTRUSER = "RESTRO";
private static final String RESTRWAITER = "WAITER";
#Autowired
private UserDetailsService userDetailsService;
#Autowired
private DataSource dataSource;
#Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
auth.userDetailsService(userDetailsService).passwordEncoder(getPasswordEncoder());
}
#Bean
public AuthenticationFailureHandler customAuthenticationFailureHandler() {
return new CustomAuthenticationFailureHandler();
}
#Override
#Bean
public AuthenticationManager authenticationManagerBean() throws Exception {
return super.authenticationManagerBean();
}
#Override
public void configure(WebSecurity web) throws Exception {
web
.ignoring()
.antMatchers("/api/waiter/**");
}
#Override
protected void configure(HttpSecurity http) throws Exception {
http.authorizeRequests().antMatchers("/admin/**").hasRole(SYSTEM).antMatchers("/restro/**")
.hasAnyRole(RESTRUSER).antMatchers("/waiter/**").hasAnyRole(RESTRWAITER).antMatchers("/", "/pub/**")
.permitAll().and().formLogin().loginPage("/login").defaultSuccessUrl("/dashboard")
.failureHandler(customAuthenticationFailureHandler()).permitAll().and().logout()
.logoutRequestMatcher(new AntPathRequestMatcher("/logout")).logoutSuccessUrl("/?logout")
.deleteCookies("my-remember-me-cookie").permitAll().and().rememberMe()
// .key("my-secure-key")
.rememberMeCookieName("my-remember-me-cookie").tokenRepository(persistentTokenRepository())
.tokenValiditySeconds(24 * 60 * 60).and().exceptionHandling();
}
PersistentTokenRepository persistentTokenRepository() {
JdbcTokenRepositoryImpl tokenRepositoryImpl = new JdbcTokenRepositoryImpl();
tokenRepositoryImpl.setDataSource(dataSource);
return tokenRepositoryImpl;
}
#Bean
public PasswordEncoder getPasswordEncoder() {
return new BCryptPasswordEncoder();
}
}
The problem is resource server .antMatchers("/api/waiter/**") is accessible without access_token.
Resource server configuration not working.
Got found solution
just replaced #Order(1) with #Order(SecurityProperties.BASIC_AUTH_ORDER) on SecurityConfiguration . And its worked.
#Configuration
#EnableWebSecurity
#Order(SecurityProperties.BASIC_AUTH_ORDER)
#EnableGlobalMethodSecurity(prePostEnabled = true, securedEnabled = true, proxyTargetClass = true)
#EnableAspectJAutoProxy(proxyTargetClass = true)
public class SecurityConfiguration extends WebSecurityConfigurerAdapter {

Wiring ClientRegistrationService with jdbc datasource

I could successfully set the jdbc datasource to Spring OAuth2 using the following configuration. However I am struggling to wire ClientRegistrationService while it was easy to wire ClientDetailsService.
#Configuration
#EnableAuthorizationServer
protected static class OAuth2AuthorizationConfig extends AuthorizationServerConfigurerAdapter {
#Autowired
private AuthenticationManager authenticationManager;
#Autowired
private DataSource dataSource;
#Override
public void configure(ClientDetailsServiceConfigurer clients) throws Exception {
clients.jdbc(dataSource);
}
.....
}
Here is what I tried
Below code fails to find the ClientDetailsService is not instanceof or of assignableFrom JdbcClientDetailsService or ClientRegistrationService
#Controller
public class ClientPortalApplication {
private ClientRegistrationService clientService;
#Autowired
public void setClientDetailsService(ClientDetailsService clientDetailsService) {
if (clientDetailsService instanceof JdbcClientDetailsService)) {
clientService = (ClientRegistrationService) clientDetailsService;
}
}
......
}
Below code wiring fails on finding a bean of type ClientRegistrationService
:
#Controller
public class ClientPortalApplication {
#Autowired
private ClientRegistrationService clientService;
......
}
The ClientDetailsService created in yout AuthorizationServerConfigurerAdapter is not a bean therefore can't be injected. A solution is to create a bean JdbcClientDetailsService inject it in the AuthorizationServerConfigurerAdapter and you will be able to inject it anywhere else:
#Configuration
public class MyConfiguration {
#Autowired
private DataSource dataSource;
#Bean
public JdbcClientDetailsService jdbcClientDetailsService() {
return new JdbcClientDetailsService(dataSource);
}
#Configuration
#EnableAuthorizationServer
protected class OAuth2AuthorizationConfig extends AuthorizationServerConfigurerAdapter {
#Autowired
private JdbcClientDetailsService jdbcClientDetailsService;
public void configure(ClientDetailsServiceConfigurer clients) throws Exception {
clients.withClientDetails(jdbcClientDetailsService);
}
}
}

In Spring Security OAuth, how do you use a passwordEncoder for client secrets?

I'm trying to BCrypt the client secrets I'm storing in the database when using Spring Security Oauth2. I can see that JdbcClientDetailsService has a setPasswordEncoder method (as mentioned in this question). However, the ClientDetailsServiceConfigurer on AuthorizationServerConfigurerAdapter does not show any obvious way of setting the password encoder. Does anyone know how to do this? I've included the authorization server configuration:
#Configuration
#EnableAuthorizationServer
public static class AuthorizationServerConfiguration extends AuthorizationServerConfigurerAdapter {
#Autowired
private DataSource dataSource;
#Autowired
private PasswordEncoder passwordEncoder;
#Autowired
private TokenStore tokenStore;
#Autowired
private UserApprovalHandler userApprovalHandler;
#Autowired
private ClientDetailsService clientDetailsService;
#Autowired
private AuthenticationManager authenticationManager;
#Override
public void configure(ClientDetailsServiceConfigurer clients) throws Exception {
clients.jdbc(dataSource);
}
#Bean
public TokenStore tokenStore() {
return new JdbcTokenStore(dataSource);
}
#Bean
public TokenApprovalStore tokenApprovalStore() {
TokenApprovalStore tokenApprovalStore = new TokenApprovalStore();
tokenApprovalStore.setTokenStore(tokenStore);
return tokenApprovalStore;
}
#Bean
public UserApprovalHandler userApprovalHandler() {
LocalUserApprovalHandler handler = new LocalUserApprovalHandler();
handler.setApprovalStore(tokenApprovalStore());
handler.setRequestFactory(new DefaultOAuth2RequestFactory(clientDetailsService));
handler.setClientDetailsService(clientDetailsService);
handler.setUseApprovalStore(true);
return handler;
}
#Override
public void configure(AuthorizationServerEndpointsConfigurer endpoints) {
endpoints.tokenStore(tokenStore)
.userApprovalHandler(userApprovalHandler)
.authenticationManager(authenticationManager);
}
#Override
public void configure(AuthorizationServerSecurityConfigurer oauthServer) {
oauthServer.realm("abcdefgh/client");
}
}
As of release 2.0.5, passwordEncoder(...) methods are now available on both ClientDetailsServiceConfigurer and AuthorizationServerSecurityConfigurer, which are made available when extending AuthorizationServerConfigurerAdapter. Use the same PasswordEncoder implementation on both and the configuration is relatively easy.
ClientDetailsServiceConfigurer doesn't really need to encode passwords if they are already in the database. If you use a backend store you should just inject it into the configurer, and deal with creating the data in the back end as a separate problem.

Resources