я - новичок в спринге, нужны ответы на следующие вопросы:
- Как проверять онлайн пользователя, т.е когда он авторизован, а когда нет?
- Через какой класс имеется возможность прерывания сессии юзера по закрытию/логауту с сайта?
Stack Overflow на русском — это сайт вопросов и ответов для программистов. Присоединяйтесь! Регистрация займёт не больше минуты.
Присоединиться к сообществуя - новичок в спринге, нужны ответы на следующие вопросы:
Ответ на 1.(Как проверять онлайн пользователя, т.е когда он авторизован, а когда нет?)
Проверять на авторизацию можно следующим образом
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
...
Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
if (authentication == null) {
return null;
}
Ответ на 2.(Через какой класс имеется возможность прерывания сессии юзера по закрытию/логауту с сайта?)
Spring security специальным образом конфигурируют, вот пример конфигурации
protected void configure(final HttpSecurity http) throws Exception {
// @formatter:off
http
.csrf().disable()
.authorizeRequests()
.antMatchers("/admin/**").hasRole("ADMIN")
.antMatchers("/anonymous*").anonymous()
.antMatchers("/login*").permitAll()
.anyRequest().authenticated()
.and()
.formLogin()
.loginPage("/login.html")
.loginProcessingUrl("/perform_login")
.defaultSuccessUrl("/homepage.html", true)
//.failureUrl("/login.html?error=true")
.failureHandler(authenticationFailureHandler())
.and()
.logout()
.logoutUrl("/perform_logout")
.deleteCookies("JSESSIONID")
.logoutSuccessHandler(logoutSuccessHandler());
//.and()
//.exceptionHandling().accessDeniedPage("/accessDenied");
//.exceptionHandling().accessDeniedHandler(accessDeniedHandler());
// @formatter:on
}
Чтобы пользователь вышел, ему необходимо в данном случае отправить запрос по адресу
/perform_logout
. Параметры конфигурирования для .logoutUrl передаются в класс org.springframework.security.config.annotation.web.configurers.LogoutConfigurer
Первый вопрос решил благодаря Алексею с помощью Authentication, а во втором использовал слушатель LogoutHandler, который позволил описать логику логаута(насколько я понял - действия, исполняющиеся во время процедуры).
Контроллер авторизации
@Component
public class AuthProviderImpl implements AuthenticationProvider {
// Связь с БД юзера
@Autowired
private UserRepository userRepository;
// Задаем правила авторизации
@Override
public Authentication authenticate(Authentication authentication) throws AuthenticationException {
User user = userRepository.findByUsername(authentication.getName());
if(user == null)
throw new UsernameNotFoundException("Пользователь не найден");
if(!user.getPassword().equals(authentication.getCredentials().toString()))
throw new BadCredentialsException("Пароли не совпадают");
user.setActive(true); // Online
userRepository.save(user); // Update
// Если ролей не будет - поставьте null
List<GrantedAuthority> authorities = Arrays.asList(Role.values());
return new UsernamePasswordAuthenticationToken(user, null, authorities);
}
@Override // Вспомогательный метод
public boolean supports(Class<?> aClass) {
return aClass.equals(UsernamePasswordAuthenticationToken.class);
}
}
Контроллер логаута
@Component
public class CustomLogoutHandler implements LogoutHandler {
// Связь с БД юзера
@Autowired
private UserRepository userRepository;
// Задаем действия при логауте
@Override
public void logout(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Authentication authentication) {
User user = userRepository.findByUsername(authentication.getName());
user.setActive(false); // Offline
userRepository.save(user); // Update
}
}
SecurityConfig
@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
private final AuthProviderImpl authProvider;
private final CustomLogoutHandler customLogoutHandler;
public SecurityConfig(AuthProviderImpl authProvider, CustomLogoutHandler customLogoutHandler) {
this.authProvider = authProvider;
this.customLogoutHandler = customLogoutHandler;
}
@Override
protected void configure(HttpSecurity http) throws Exception {
http
.authorizeRequests()
.antMatchers("/login", "/reg").anonymous()
.anyRequest().authenticated()
.and()
.formLogin()
.loginPage("/login")
.and()
.logout()
.addLogoutHandler(customLogoutHandler) // Здесь наш логаут
.logoutSuccessUrl("/home");
}
@Override
protected void configure(AuthenticationManagerBuilder auth) {
auth.authenticationProvider(authProvider); // Здесь наша авторизация
}
}