我有一个使用Spring Security 5.0的Spring Boot应用程序,为此我无法在没有持久性的情况下正确设置记住我功能。
这是安全配置:
@Configuration
@EnableWebSecurity public class SecurityConfig extends WebSecurityConfigurerAdapter{
@Override
protected void configure(HttpSecurity http)throws Exception{
http
.authorizeRequests()
.requestMatchers(EndpointRequest.toAnyEndpoint()).hasRole("ADMIN")
.requestMatchers(PathRequest.toStaticResources().atCommonLocations()).permitAll()
.antMatchers("/").permitAll()
.antMatchers("/admin/**").hasRole("USER")
.antMatchers("/backstage").hasRole("ADMIN")
.and()
.formLogin()
.loginPage("/login")
.defaultSuccessUrl("/admin")
.and()
.logout()
.and()
.rememberMe()
.key("TopSecretSentence")
.alwaysRemember(true)
.and()
.exceptionHandling()
.accessDeniedPage("/")
.and()
.csrf()
.csrfTokenRepository(CookieCsrfTokenRepository.withHttpOnlyFalse())
.ignoringAntMatchers("/stripe/webhooks", "/zodomus-booking")
.and()
.httpBasic()
.and()
.sessionManagement()
.invalidSessionUrl("/")
.sessionAuthenticationErrorUrl("/login?logout");
}
@Autowired
private UserServiceImpl userDetailsService;
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
auth.userDetailsService(userDetailsService);
}
浏览器已关闭该字段:仅保留本地数据,直到您退出浏览器
最后,这是UserDetailsService
的实现:
@Service
public class UserServiceImpl implements UserDetailsService {
@Autowired
UserRepository userRepository;
@Autowired
RoleRepository roleRepository;
public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
RentalWebsUser userInfo = userRepository.getUserByUsername(username);
List<GrantedAuthority> authorities = roleRepository.getRolesByUsername(username);
if(userInfo != null && !authorities.isEmpty()){
PasswordEncoder passwordEncoder = PasswordEncoderFactories.createDelegatingPasswordEncoder();
String encodedPassword = passwordEncoder.encode(userInfo.getPassword());
User user = new User(userInfo.getUsername(), encodedPassword, authorities);
return user;
} else throw new UsernameNotFoundException("Wrong user/password");}
}