动态获取用户的认证信息
@Configuration
public class SpringSecurityConfig extends WebSecurityConfigurerAdapter {
@Bean
public PasswordEncoder passwordEncoder() {
return new BCryptPasswordEncoder();
}
@Override
protected void configure(HttpSecurity http) throws Exception {
http.formLogin()
.loginPage("/login/page") //自定义登录页面
.loginProcessingUrl("/login")
.and()
.authorizeRequests()
.antMatchers("/login/page").permitAll() // 放行跳转认证请求
.anyRequest().authenticated();
//关闭CSRF(Cross-site request forgery) 跨站请求伪造
http.csrf().disable();
}
}
重要的两个接口UserDetailsService
和 UserDetails
package org.springframework.security.core.userdetails;
public interface UserDetailsService {
UserDetails loadUserByUsername(String username) throws UsernameNotFoundException;
}
package org.springframework.security.core.userdetails;
import java.io.Serializable;
import java.util.Collection;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.GrantedAuthority;
public interface UserDetails extends Serializable {
Collection<? extends GrantedAuthority> getAuthorities();
String getPassword();
String getUsername();
boolean isAccountNonExpired();
boolean isAccountNonLocked();
boolean isCredentialsNonExpired();
boolean isEnabled();
}
实现接口UserDetailsService
获取用户信息,具体实现由我们自己决定,就是根据username获取存储的用户信息,这样就动态获取了用户的信息。
@Slf4j
@Component
public class CustomUserDetailService implements UserDetailsService {
@Autowired
public PasswordEncoder passwordEncoder;
@Override
public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
//通过传入的用户名最终获取到UserDetails对象,这个获取过程省略了
//这个过程其实就是根据用户名去数据库查询获取密码和权限列表,最终组成User对象
//Spring Security会用这个User和登录输入和密码比较,判断是否登录成功
//模拟用户可以在数据库查询到
if ("devin".equals(username)) {
return new User("devin", passwordEncoder.encode("1234"),
AuthorityUtils.commaSeparatedStringToAuthorityList("ADMIN"));
}
throw new UsernameNotFoundException("用户名输入错误");
}
}