Получить идентификатор Jsession для конкретного пользователя в Spring Security - PullRequest
0 голосов
/ 23 января 2019

У меня есть веб-приложение, в котором пользователь может войти с помощью страницы входа, и я установил безопасность Spring с этой конфигурацией (разрешите запомнить меня и мультитенант)

@Override
public Authentication authenticate(Authentication authentication) throws AuthenticationException {
    String name = authentication.getName();
    String password = authentication.getCredentials().toString();
    if (name == null || name.isEmpty() || password == null || password.isEmpty())
        return null;

    UserDetails user = userDetailsService.loadUserByUsername(name);
    if (user != null){
        Boolean authenticationSuccess = new BCryptPasswordEncoder().matches(password, user.getPassword());
        if (authenticationSuccess){
            return new UsernamePasswordAuthenticationToken(user, password, user.getAuthorities());
        }else
            return null;
    }else
        return null;
}

@Override
protected void configure(HttpSecurity http) throws Exception {
    List<Role> roles=roleServices.getRoles();
    //Retrieve array of roles(only string field without id)
    String[] rolesArray = new String[roles.size()];
    int i=0;
    for (Role role:roles){
        rolesArray[i++] = role.getRole();
    }

    http
    .addFilterBefore(new MultiTenancyFilter(), UsernamePasswordAuthenticationFilter.class)
    .authorizeRequests() //Authorize Request Configuration
    //the /acquisition/** need admin role
    //.antMatchers("/acquisition/**").hasRole("ADMIN")
    //.and().exceptionHandling().accessDeniedPage("/Access_Denied");
    //all the path need authentication
    .anyRequest().hasAnyRole(rolesArray)//.authenticated()
    .and()//Login Form configuration for all others
    .formLogin()
    .loginPage("/login").successHandler(customSuccessHandler)
    //important because otherwise it goes in a loop because login page require authentication and authentication require login page
    .permitAll()
    //start - remember me
    .and()
    .rememberMe()
    .and().rememberMe().key("uniqueAndSecret").userDetailsService(userDetailsService)
    .tokenRepository(persistentTokenRepository())
    //deve avere lo stesso nome della checkbox..
    .rememberMeParameter("remember-me")
    //il nome del cookie che sarà salvato su browser
    .rememberMeCookieName("remember-me")
    //secondi di validità del token
    .tokenValiditySeconds(7*86400)
    //end - remember me
    .and()
    .exceptionHandling().accessDeniedPage("/403")
    .and()
    .logout()
    .logoutSuccessUrl("/login?logout")
    .deleteCookies("JSESSIONID", "JSESSIONID")
    .invalidateHttpSession(true)
    .permitAll()
    .and()
    .sessionManagement().invalidSessionUrl("/login");//maximumSessions(1).maxSessionsPreventsLogin(true).expiredUrl("/expired.html");
}

Теперь я должен разрешить вход через API без особых усилий (то есть без аутентификации изменений или чего-то еще, что требует больше дней), в другом проекте у меня была и аутентификация httpBasic и loginPage.
Моя идея состояла в том, чтобы создать веб-сервисы, которые возвращают идентификатор jsession для конкретного пользователя, потому что, если я попытаюсь использовать AJAX из другого домена, ответ службы входа в систему задает cookie для идентификатора сеанса, но я не могу получить его, потому что он не разрешен чтобы получить печенье. Как вы думаете? Возможно ли это?

...