英文:
How to authenticate user with specific role in spring boot?
问题
SecurityConfiguration
@Configuration
@EnableWebSecurity
public class SecurityConfiguration extends WebSecurityConfigurerAdapter {
@Autowired
CustomUserDetailService customUserDetailService;
@Autowired
CustomSuccessHandler successHandler;
@Autowired
CustomFailureHandler failureHandler;
@Autowired
private BCryptPasswordEncoder bCryptPasswordEncoder;
@Autowired
CustomBeanDefinition customBeanDefinition;
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
UserDetailsService userDetailsService = customBeanDefinition.jpaUserDetails();
auth.userDetailsService(userDetailsService).passwordEncoder(bCryptPasswordEncoder);
}
@Override
protected void configure(HttpSecurity http) throws Exception {
http
.authorizeRequests()
.antMatchers("/").permitAll()
.antMatchers("/login").permitAll()
.antMatchers("/signup").permitAll()
.antMatchers("/register").permitAll()
.antMatchers("/book/index").hasAuthority("ADMIN")
.anyRequest().authenticated()
.and()
.csrf().disable()
.formLogin()
.successHandler(successHandler)
.loginPage("/login")
.failureHandler(failureHandler)
.usernameParameter("username")
.passwordParameter("password")
.and().logout().permitAll();
}
@Override
public void configure(WebSecurity web) throws Exception {
web
.ignoring()
.antMatchers("/resources/**", "/static/**", "/css/**", "/js/**", "/img/**", "/icon/**");
}
}
CustomUserDetailService
@Service
public class CustomUserDetailService implements UserDetailsService {
@Autowired
UserRepository userRepository;
@Override
public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
User user = userRepository.findByUsername(username);
if (user == null) {
throw new UsernameNotFoundException("User not found");
}
List<GrantedAuthority> authorities = getUserAuthority(user.getRoles());
UserDetails userDetails = buildUserForAuthentication(user, authorities);
return userDetails;
}
private List<GrantedAuthority> getUserAuthority(Set<Role> userRoles) {
Set<GrantedAuthority> roles = new HashSet<>();
for (Role role : userRoles) {
roles.add(new SimpleGrantedAuthority(role.getAuthority()));
}
return new ArrayList<>(roles);
}
private UserDetails buildUserForAuthentication(User user, List<GrantedAuthority> authorities) {
return new org.springframework.security.core.userdetails.User(
user.getUsername(), user.getPassword(), authorities);
}
}
CustomBeanDefinition
@Configuration
public class CustomBeanDefinition {
@Bean
public UserDetailsService jpaUserDetails() {
return new CustomUserDetailService();
}
@Bean
public BCryptPasswordEncoder passwordEncoder() {
return new BCryptPasswordEncoder();
}
}
UserService
@Service
public class UserService {
private UserRepository userRepository;
private RoleRepository roleRepository;
private BCryptPasswordEncoder passwordEncoder;
@Autowired
public UserService(UserRepository userRepository,
RoleRepository roleRepository, BCryptPasswordEncoder passwordEncoder) {
this.userRepository = userRepository;
this.roleRepository = roleRepository;
this.passwordEncoder = passwordEncoder;
}
public void save(String username, String email, String password, String name) {
User user = userRepository.findByUsername(username);
if (user == null) {
user = new User();
user.setName(name);
user.setUsername(username);
user.setEmail(email);
user.setPassword(passwordEncoder.encode(password));
user.setActive(true);
Role role = roleRepository.findByAuthority("ADMIN");
user.setRoles(new HashSet<>(Collections.singletonList(role)));
userRepository.save(user);
System.out.println("...user saved with ADMIN role");
}
}
}
在我的应用程序中,用户目前可以成功保存并绑定到特定角色。
但是,当我尝试使用已保存的用户进行身份验证时,它永远不会进入成功处理程序,而是重定向到失败处理程序。看起来身份验证不起作用。
任何帮助将不胜感激。
英文:
SecurityConfiguration
@Configuration
@EnableWebSecurity
public class SecurityConfiguration extends WebSecurityConfigurerAdapter {
@Autowired
CustomUserDetailService customUserDetailService;
@Autowired
CustomSuccessHandler successHandler;
@Autowired
CustomFailureHandler failureHandler;
@Autowired
private BCryptPasswordEncoder bCryptPasswordEncoder;
@Autowired
CustomBeanDefinition customBeanDefinition;
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
UserDetailsService userDetailsService = customBeanDefinition.jpaUserDetails();
auth.userDetailsService(userDetailsService).passwordEncoder(bCryptPasswordEncoder);
}
@Override
protected void configure(HttpSecurity http) throws Exception {
http
.authorizeRequests()
.antMatchers("/").permitAll()
.antMatchers("/login").permitAll()
.antMatchers("/signup").permitAll()
.antMatchers("/register").permitAll()
.antMatchers("/book/index").hasAuthority("ADMIN")
.anyRequest().authenticated()
.and()
.csrf().disable()
.formLogin()
.successHandler(successHandler)
.loginPage("/login")
.failureHandler(failureHandler)
.usernameParameter("username")
.passwordParameter("password")
.and().logout().permitAll();
}
@Override
public void configure(WebSecurity web) throws Exception {
web
.ignoring()
.antMatchers("/resources/**", "/static/**", "/css/**", "/js/**", "/img/**", "/icon/**");
}
}
CustomUserDetailService
@Service
public class CustomUserDetailService implements UserDetailsService {
@Autowired
UserRepository userRepository;
@Override
public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
User user = userRepository.findByUsername(username);
if (user == null) {
throw new UsernameNotFoundException("User not found");
}
List<GrantedAuthority> authorities = getUserAuthority(user.getRoles());
UserDetails userDetails = buildUserForAuthentication(user, authorities);
return userDetails;
}
private List<GrantedAuthority> getUserAuthority(Set<Role> userRoles) {
Set<GrantedAuthority> roles = new HashSet<>();
for (Role role : userRoles) {
roles.add(new SimpleGrantedAuthority(role.getAuthority()));
}
return new ArrayList<>(roles);
}
private UserDetails buildUserForAuthentication(User user, List<GrantedAuthority> authorities) {
return new org.springframework.security.core.userdetails.User(
user.getUsername(), user.getPassword(), authorities);
}
}
CustomBeanDefinition
@Configuration
public class CustomBeanDefinition {
@Bean
public UserDetailsService jpaUserDetails() {
return new CustomUserDetailService();
}
@Bean
public BCryptPasswordEncoder passwordEncoder() {
return new BCryptPasswordEncoder();
}
}
UserService
@Service
public class UserService {
private UserRepository userRepository;
private RoleRepository roleRepository;
private BCryptPasswordEncoder passwordEncoder;
@Autowired
public UserService(UserRepository userRepository,
RoleRepository roleRepository, BCryptPasswordEncoder passwordEncoder) {
this.userRepository = userRepository;
this.roleRepository = roleRepository;
this.passwordEncoder = passwordEncoder;
}
public void save(String username, String email, String password, String name) {
User user = userRepository.findByUsername(username);
if (user == null) {
user = new User();
user.setName(name);
user.setUsername(username);
user.setEmail(email);
user.setPassword(passwordEncoder.encode(password));
user.setActive(true);
Role role = roleRepository.findByAuthority("ADMIN");
user.setRoles(new HashSet<>(Collections.singletonList(role)));
userRepository.save(user);
System.out.println("...user saved with ADMIN role");
}
}
}
In my application user is currently being saved successfully and binding with specific role.
However, when i try to authenticate my application with saved user, it never goes on success handler, it redirects me on failure handler.
It looks like authentication is not working.
Any help would be appreciated.
答案1
得分: -1
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
auth.userDetailsService(customUserDetailService)
.passwordEncoder(bCryptPasswordEncoder);
}
英文:
Change your Security Configuration, configure() method like below,
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
auth.userDetailsService(customUserDetailService).
passwordEncoder(bCryptPasswordEncoder);
}
专注分享java语言的经验与见解,让所有开发者获益!
评论