在Spring Security中检索特定用户的jsession ID

时间:2019-01-23 07:55:13

标签: java spring authentication spring-security jsessionid

我有一个Web应用程序,用户可以在其中使用登录页面登录,并使用此配置设置了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 ID的Web服务,因为如果我尝试从另一个域使用AJAX,则登录服务响应会为该会话ID设置cookie,但由于它是不允许获取Cookie。你怎么看?有可能吗?

0 个答案:

没有答案