Skip to content

Instantly share code, notes, and snippets.

@dotkebi
Last active November 15, 2021 21:53
Show Gist options
  • Save dotkebi/28049abd7d1f581245a1d2a9eba18b92 to your computer and use it in GitHub Desktop.
Save dotkebi/28049abd7d1f581245a1d2a9eba18b92 to your computer and use it in GitHub Desktop.
SpringSecurity Authentication
@Component
public class CustomAuthenticationProvider implements AuthenticationProvider {
@Autowired
private AuthServiceImpl authService;
@Override
public Authentication authenticate(Authentication authentication) throws AuthenticationException {
String username = authentication.getName();
String password = (String) authentication.getCredentials();
AdminUser user = (AdminUser) authService.loadUserByUsername(username);
if (user == null || !user.getUsername().equalsIgnoreCase(username)) {
throw new BadCredentialsException("Username not found.");
}
BCryptPasswordEncoder passwordEncoder = new BCryptPasswordEncoder();
if (!passwordEncoder.matches(password, user.getPassword())) {
throw new BadCredentialsException("Wrong password.");
}
Collection<? extends GrantedAuthority> authorities = user.getAuthorities();
return new UsernamePasswordAuthenticationToken(user, password, authorities);
}
@Override
public boolean supports(Class<?> aClass) {
return true;
}
}
@Configuration
@EnableWebSecurity
public class WebMvcConfig extends WebSecurityConfigurerAdapter {
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
auth.inMemoryAuthentication()
.withUser("userName")
.password("password")
.roles("ADMIN")
;
}
}
@Configuration
@EnableWebSecurity
public class WebMvcConfig extends WebSecurityConfigurerAdapter {
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
auth.jdbcAuthentication().dataSource(dataSource)
.usersByUsernameQuery(
"select username, password, enabled from admin_users where username=?")
.authoritiesByUsernameQuery(
"select username, role from user_roles where username=?")
;
}
}
@Configuration
@EnableWebSecurity
public class WebMvcConfig extends WebSecurityConfigurerAdapter {
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
auth.userDetailsService(adminService)
;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment