10 - Spring Boot Tutorial : #AdvancedAuthentication using Spring Security | #SpringSecurity

preview_player
Показать описание
#SpringSecurity #SpringBoot #UserDetailsService #GrantedAuthorities #WebSecurityConfigurerAdapter #EnableWebSecurity #EnableGlobalMethodSecurity #PasswordEncoder #HttpSecurity #PreAuthorize

================================
1 - need a spring security dependency
spring-boot-starter-security
================================
2 - need to create a class which must be implement user details service interface then need to override loadUserByUsername method. and annotate this class as Service.

Here is the syntax
@Service
public class MyUserDetailsService implements UserDetailsService {

@Autowired
private UserRepository userRepository;

@Override
public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
if(user == null) {
throw new UsernameNotFoundException("User name "+username+" not found");
}
}

private Collection getGrantedAuthorities(User user) {
Collection grantedAuthorities = new ArrayList();
}
return grantedAuthorities;
}
}
================================
3 - Here is the class which can enable spring security so for that create class and this class must extends WebSecurityConfigurerAdapter class and override configure method.

Here is the syntax
@Configuration
@EnableWebSecurity
@EnableGlobalMethodSecurity(prePostEnabled = true)
public class SpringSecurityConfiguration extends WebSecurityConfigurerAdapter {

@Autowired
private MyUserDetailsService userDetailsService;

@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
}

@Override
protected void configure(HttpSecurity http) throws Exception {
.anyRequest().authenticated().and()
.formLogin().loginPage("/user/login").permitAll().and()
.logout().deleteCookies("remember-me").permitAll().and()
.rememberMe().tokenValiditySeconds(180);
}

@Bean
public PasswordEncoder passwordEncoder(){
PasswordEncoder encoder = new BCryptPasswordEncoder();
return encoder;
}
}
================================
4 - now where ever you want to add restriction based on role add below code on top of method
@PreAuthorize("hasRole('ROLE_USER') or hasRole('ROLE_ADMIN')")
or
@PreAuthorize("hasRole('ROLE_USER')")
or
@PreAuthorize("hasRole('ROLE_ADMIN')")
================================
Рекомендации по теме
Комментарии
Автор

Really helpful for @PreAuthorize in springboot !!

abhinavkumar
Автор

+Almighty Java, very good! I still have a problem with the browser cache, only Edge performs well, I still have to figure it out. Thank You!!!

axndmathias
Автор

For the error "There is no PasswordEncoder mapped for the id "null" ", use the below code
@Override
public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
User user =
if (user == null) {
throw new Name" + username + "Not found");
}
PasswordEncoder encoder =
return new org.springframework.security.core.userdetails.User(user.getUserName(),
encoder.encode(user.getPassword()), getGrantedAuthorities(user));


}

BVSSRAJ
Автор

Cleared all the cache and restarted the browser several times but still when I reload i get
"Http status 401: Full authentication is required to access this resource" any help?

beckoking
Автор

Hi, i hope you are doing well,
when am trying to authenticate it gives me same login page over and over when its correct,
thanks.

ahmedelhaj
Автор

why came this error "There is no PasswordEncoder mapped for the id "null" ". Thank you.

priyanthasamaraweera