My linux world » Java Spring Security – Database User

Java Spring Security - Database User


Contents

Configuration

SpringSecurityInitializer

To enable spring security, you must create SpringSecurityInitializer.java :

public class SpringSecurityInitializer extends AbstractSecurityWebApplicationInitializer {
   //do nothing
}

UserDetailsService

To check if the user is allowed to connect, create UserDetailsServiceImpl.java :

@Service("userDetailsService")
public class UserDetailsServiceImpl implements UserService, UserDetailsService {	
 
	@Autowired
	private MyUserService myUserService = null;	
 
	public Contact loadUserByUsername(String username) {
                // get User from database :
		User user = myUserService .getUser(username);		
 
		if(user == null) {
			// User not found, throw UsernameNotFoundException.
			throw new UsernameNotFoundException("UsernameNotFoundException");
		}
 
                // user found :
		return user;
	}
}

SecurityConfiguration

@Configuration
@EnableWebSecurity
@EnableGlobalMethodSecurity(prePostEnabled = true)
public class SecurityConfiguration extends WebSecurityConfigurerAdapter {
 
    @Autowired
    private UserDetailsService userDetailService;
 
    @Autowired
    public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
        // use BCrypt algorithm to encode passwords :
        auth.userDetailsService(userDetailService).passwordEncoder(new BCryptPasswordEncoder());
    }
 
    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http    
            .csrf()
            .formLogin()
                .loginPage("/login.html")
                .loginProcessingUrl("/j_spring_security_check")
                .failureUrl("/login-failed.html")
                .usernameParameter("j_username")
                .passwordParameter("j_password")
                .defaultSuccessUrl("/login-success.html")
                .permitAll()
        .and()
            .logout()
                .logoutUrl("/j_spring_security_logout")
                .logoutSuccessUrl("/logout-success.html")
                .deleteCookies("JSESSIONID")
        .and()
            .authorizeRequests();                
    }
}

Copyright © 2023 My linux world - by Marc RABAHI
Design by Marc RABAHI and encelades.

Fork me on GitHub