HttpSession没有提供SecurityContext

时间:2018-08-18 13:24:20

标签: java spring spring-boot spring-security

奇怪的是,我们面临的客户很少。

这是应用程序的UAT链接 http://app.dcx24.com/

我的请求顺序如下

  1. / login:它重定向到/ auth页面并发送Set-Cookies
  2. / auth:它重定向到/ welcome页面,而不发送Set-Cookies。在一台计算机上时,它正在发送设置的Cookie标头,也不会重定向到欢迎页面。
  3. /欢迎

配置课程

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.core.session.SessionRegistry;
import org.springframework.security.core.session.SessionRegistryImpl;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;
import org.springframework.security.web.authentication.www.BasicAuthenticationFilter;
import org.springframework.security.web.csrf.CsrfFilter;
import org.springframework.security.web.util.matcher.AntPathRequestMatcher;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;

import com.hftsolution.auth.socket.MonitorSocket;

@Configuration
@EnableWebSecurity

public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
    @Autowired
    private UserDetailsService userDetailsService;

    @Value("${csrfEnable}")
    private Boolean csrfEnable;

    @Bean
    public RecaptchaFilter recaptchaFilter() {
        return new RecaptchaFilter();
    }

    @Bean
    public MonitorSocket monitorSocket() {
        return new MonitorSocket();
    }

    @Bean
    public BCryptPasswordEncoder bCryptPasswordEncoder() {
        return new BCryptPasswordEncoder();
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {

        http.authorizeRequests()
                .antMatchers("/resources/**","/favicon.ico", "/registration", "/forgot", "/passwordChange", "/sandMail",
                        "/resetPassword")
                .permitAll().antMatchers("/admin3").hasAnyRole("Level3").antMatchers("/admin2").hasAnyRole("Level2")
                .antMatchers("/").hasAnyRole("user").antMatchers("/admin1").hasAnyRole("Level1").and().formLogin()
                .loginPage("/login").permitAll().defaultSuccessUrl("/auth", true).and().logout()
                .logoutRequestMatcher(new AntPathRequestMatcher("/logoutt")).logoutSuccessUrl("/login?logout").and()
                .sessionManagement().invalidSessionUrl("/login?logout").sessionFixation().none()/*.changeSessionId()
                .maximumSessions(1).expiredUrl("/logoutt")*/;
        http.authorizeRequests().anyRequest().authenticated();
        http.addFilterBefore(recaptchaFilter(), UsernamePasswordAuthenticationFilter.class);
        /*http.addFilterAfter(new UserToMdcFilter(), BasicAuthenticationFilter.class);*/
        http.addFilterBefore(new OtpValidationFilter(), BasicAuthenticationFilter.class);
        http.headers().frameOptions().sameOrigin();
    /*  http
        .sessionManagement()
            .sessionCreationPolicy(SessionCreationPolicy.ALWAYS)
            .enableSessionUrlRewriting(true);
        */
        if (!csrfEnable) {
            http.csrf().disable().authorizeRequests();
        } else {
            http.addFilterAfter(new CsrfHeaderFilter(), CsrfFilter.class);
        }

    /*  
        http.sessionManagement().maximumSessions(1).sessionRegistry(sessionRegistry());*/

    }

    @Bean
    public SessionRegistry sessionRegistry() {
        return new SessionRegistryImpl();
    }

    @Autowired
    public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {

        auth.userDetailsService(userDetailsService).passwordEncoder(bCryptPasswordEncoder());
    }
}

验证码

@RequestMapping(value = "/auth", method = RequestMethod.GET)
public String auth(Model model, HttpServletRequest request, HttpServletResponse resp) throws IOException {
    logger.info("userid  working");
    Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
    String userId = authentication.getName();
    logger.info("userid  "+userId);
    OauthToken oauthToken = LoginRepo.accessTokenMap.get(userId);
    if (oauthToken == null && !userId.equals("anonymousUser") && userId != null) {
        resp.sendRedirect("/logout");
    }


    if (!userId.equals("anonymousUser") && userId != null) {
        User user = userService.findByUsername(userId);

        if (user.getActive()) {
            if (user.getIsSecurity() != null && user.getIsSecurity().equals("1")) {
                GoogleSecret googleS = googleSecretRepo.findByusername(userId);
                if (googleS == null) {
                    model.addAttribute("reAuth", user.getGoogleReauthenticate());
                    return "googleAuth";
                }
            } else {

                grantAuthority();
                model.addAttribute("webSocketUrl", webocket);

                InetAddress currentip = InetAddress.getLocalHost();
         //       String content = String.format("You are successfully login in Stech Exchange with : %s", currentip.toString());
                StringBuffer content=new StringBuffer();
                content.append("Beste ").append(user.getFirstname()).append(" ").append(user.getLastName()).append(",<br/><br/>");
                content.append(loginmail).append(userId).append("<br/><br/>");

                StringBuffer sb=new StringBuffer();
                String html = sb.append("<a href='").append(loginPassLink).append("'>").append(loginlink).append("</a>").toString();

                content.append(loginmail1).append(html);
                content.append(loginmail2).append("<br/><br/>");








                Mail mail = new Mail(userId, loginSubject, content.toString());

                authMail.getMailQueue().add(mail);
                return "redirect:/blockChain/welcome";

            }

            return "auth";
        } else {
            model.addAttribute("error", "User is not Activated.");
            model.addAttribute("recaptchSiteKey", recaptchSiteKey);
            return "login";
        }
    } else {
        model.addAttribute("error", "Please login first");
        model.addAttribute("recaptchSiteKey", recaptchSiteKey);
        return "login";
    }


}

我们无法登录的PC的日志

08-2018-18 17:26:41  - Authentication success. Updating SecurityContextHolder to contain: org.springframework.security.authentication.UsernamePasswordAuthenticationToken@b0b2fa22: Principal: org.springframework.security.core.userdetails.User@f4bdcd82: Username: mayank.bpt@gmail.com; Password: [PROTECTED]; Enabled: true; AccountNonExpired: true; credentialsNonExpired: true; AccountNonLocked: true; Granted Authorities: ROLE_user; Credentials: [PROTECTED]; Authenticated: true; Details: org.springframework.security.web.authentication.WebAuthenticationDetails@2cd90: RemoteIpAddress: 0:0:0:0:0:0:0:1; SessionId: 1FC7BFF2AAC6736DBC7C27B6F478ADF5; Granted Authorities: ROLE_user
08-2018-18 17:26:41  - Redirecting to '/auth'
08-2018-18 17:26:41  - SecurityContext 'org.springframework.security.core.context.SecurityContextImpl@b0b2fa22: Authentication: org.springframework.security.authentication.UsernamePasswordAuthenticationToken@b0b2fa22: Principal: org.springframework.security.core.userdetails.User@f4bdcd82: Username: mayank.bpt@gmail.com; Password: [PROTECTED]; Enabled: true; AccountNonExpired: true; credentialsNonExpired: true; AccountNonLocked: true; Granted Authorities: ROLE_user; Credentials: [PROTECTED]; Authenticated: true; Details: org.springframework.security.web.authentication.WebAuthenticationDetails@2cd90: RemoteIpAddress: 0:0:0:0:0:0:0:1; SessionId: 1FC7BFF2AAC6736DBC7C27B6F478ADF5; Granted Authorities: ROLE_user' stored to HttpSession: 'org.apache.catalina.session.StandardSessionFacade@291245
08-2018-18 17:26:41  - SecurityContextHolder now cleared, as request processing completed
08-2018-18 17:26:41  - /auth at position 1 of 13 in additional filter chain; firing Filter: 'WebAsyncManagerIntegrationFilter'
08-2018-18 17:26:41  - /auth at position 2 of 13 in additional filter chain; firing Filter: 'SecurityContextPersistenceFilter'
08-2018-18 17:26:41  - No HttpSession currently exists
08-2018-18 17:26:41  - No SecurityContext was available from the HttpSession: null. A new one will be created.
08-2018-18 17:26:41  - /auth at position 3 of 13 in additional filter chain; firing Filter: 'HeaderWriterFilter'
08-2018-18 17:26:41  - Not injecting HSTS header since it did not match the requestMatcher org.springframework.security.web.header.writers.HstsHeaderWriter$SecureRequestMatcher@145c77e
08-2018-18 17:26:41  - /auth at position 4 of 13 in additional filter chain; firing Filter: 'LogoutFilter'
08-2018-18 17:26:41  - Checking match of request : '/auth'; against '/logoutt'
08-2018-18 17:26:41  - /auth at position 5 of 13 in additional filter chain; firing Filter: 'RecaptchaFilter'
08-2018-18 17:26:41  - /auth at position 6 of 13 in additional filter chain; firing Filter: 'UsernamePasswordAuthenticationFilter'
08-2018-18 17:26:41  - Request 'GET /auth' doesn't match 'POST /login
08-2018-18 17:26:41  - /auth at position 7 of 13 in additional filter chain; firing Filter: 'OtpValidationFilter'
08-2018-18 17:26:41  - /auth at position 8 of 13 in additional filter chain; firing Filter: 'RequestCacheAwareFilter'
08-2018-18 17:26:41  - /auth at position 9 of 13 in additional filter chain; firing Filter: 'SecurityContextHolderAwareRequestFilter'
08-2018-18 17:26:41  - /auth at position 10 of 13 in additional filter chain; firing Filter: 'AnonymousAuthenticationFilter'
08-2018-18 17:26:41  - Populated SecurityContextHolder with anonymous token: 'org.springframework.security.authentication.AnonymousAuthenticationToken@9055c2bc: Principal: anonymousUser; Credentials: [PROTECTED]; Authenticated: true; Details: org.springframework.security.web.authentication.WebAuthenticationDetails@b364: RemoteIpAddress: 0:0:0:0:0:0:0:1; SessionId: null; Granted Authorities: ROLE_ANONYMOUS'
08-2018-18 17:26:41  - /auth at position 11 of 13 in additional filter chain; firing Filter: 'SessionManagementFilter'
08-2018-18 17:26:41  - /auth at position 12 of 13 in additional filter chain; firing Filter: 'ExceptionTranslationFilter'
08-2018-18 17:26:41  - /auth at position 13 of 13 in additional filter chain; firing Filter: 'FilterSecurityInterceptor'
08-2018-18 17:26:41  - Checking match of request : '/auth'; against '/resources/**'
08-2018-18 17:26:41  - Checking match of request : '/auth'; against '/registration'
08-2018-18 17:26:41  - Checking match of request : '/auth'; against '/forgot'
08-2018-18 17:26:41  - Checking match of request : '/auth'; against '/passwordchange'
08-2018-18 17:26:41  - Checking match of request : '/auth'; against '/sandmail'
08-2018-18 17:26:41  - Checking match of request : '/auth'; against '/resetpassword'
08-2018-18 17:26:41  - Checking match of request : '/auth'; against '/vailidateotp'
08-2018-18 17:26:41  - Checking match of request : '/auth'; against '/auth'
08-2018-18 17:26:41  - Secure object: FilterInvocation: URL: /auth; Attributes: [hasAnyRole('ROLE_user')]
08-2018-18 17:26:41  - Previously Authenticated: org.springframework.security.authentication.AnonymousAuthenticationToken@9055c2bc: Principal: anonymousUser; Credentials: [PROTECTED]; Authenticated: true; Details: org.springframework.security.web.authentication.WebAuthenticationDetails@b364: RemoteIpAddress: 0:0:0:0:0:0:0:1; SessionId: null; Granted Authorities: ROLE_ANONYMOUS
08-2018-18 17:26:41  - Voter: org.springframework.security.web.access.expression.WebExpressionVoter@76518d, returned: -1
08-2018-18 17:26:41  - Access is denied (user is anonymous); redirecting to authentication entry point

从成功登录的地方登录

  RemoteIpAddress: 0:0:0:0:0:0:0:1; SessionId: C3AE04F3ED675FD0D08C99C699E6DE9F; Granted Authorities: ROLE_user
    08-2018-18 17:21:00  - Redirecting to '/auth'
    08-2018-18 17:21:00  - SecurityContext 'org.springframework.security.core.context.SecurityContextImpl@b0b037b2: Authentication: org.springframework.security.authentication.UsernamePasswordAuthenticationToken@b0b037b2: Principal: org.springframework.security.core.userdetails.User@f4bdcd82: Username: mayank.bpt@gmail.com; Password: [PROTECTED]; Enabled: true; AccountNonExpired: true; credentialsNonExpired: true; AccountNonLocked: true; Granted Authorities: ROLE_user; Credentials: [PROTECTED]; Authenticated: true; Details: org.springframework.security.web.authentication.WebAuthenticationDetails@0: RemoteIpAddress: 0:0:0:0:0:0:0:1; SessionId: C3AE04F3ED675FD0D08C99C699E6DE9F; Granted Authorities: ROLE_user' stored to HttpSession: 'org.apache.catalina.session.StandardSessionFacade@d3937f
    08-2018-18 17:21:00  - SecurityContextHolder now cleared, as request processing completed
    08-2018-18 17:21:01  - /auth at position 1 of 13 in additional filter chain; firing Filter: 'WebAsyncManagerIntegrationFilter'
    08-2018-18 17:21:01  - /auth at position 2 of 13 in additional filter chain; firing Filter: 'SecurityContextPersistenceFilter'
    08-2018-18 17:21:01  - Obtained a valid SecurityContext from SPRING_SECURITY_CONTEXT: 'org.springframework.security.core.context.SecurityContextImpl@b0b037b2: Authentication: org.springframework.security.authentication.UsernamePasswordAuthenticationToken@b0b037b2: Principal: org.springframework.security.core.userdetails.User@f4bdcd82: Username: mayank.bpt@gmail.com; Password: [PROTECTED]; Enabled: true; AccountNonExpired: true; credentialsNonExpired: true; AccountNonLocked: true; Granted Authorities: ROLE_user; Credentials: [PROTECTED]; Authenticated: true; Details: org.springframework.security.web.authentication.WebAuthenticationDetails@0: RemoteIpAddress: 0:0:0:0:0:0:0:1; SessionId: C3AE04F3ED675FD0D08C99C699E6DE9F; Granted Authorities: ROLE_user'
    08-2018-18 17:21:01  - /auth at position 3 of 13 in additional filter chain; firing Filter: 'HeaderWriterFilter'
    08-2018-18 17:21:01  - Not injecting HSTS header since it did not match the requestMatcher org.springframework.security.web.header.writers.HstsHeaderWriter$SecureRequestMatcher@145c77e
    08-2018-18 17:21:01  - /auth at position 4 of 13 in additional filter chain; firing Filter: 'LogoutFilter'
    08-2018-18 17:21:01  - Checking match of request : '/auth'; against '/logoutt'
    08-2018-18 17:21:01  - /auth at position 5 of 13 in additional filter chain; firing Filter: 'RecaptchaFilter'
    08-2018-18 17:21:01  - /auth at position 6 of 13 in additional filter chain; firing Filter: 'UsernamePasswordAuthenticationFilter'
    08-2018-18 17:21:01  - Request 'GET /auth' doesn't match 'POST /login
    08-2018-18 17:21:01  - /auth at position 7 of 13 in additional filter chain; firing Filter: 'OtpValidationFilter'
    08-2018-18 17:21:01  - /auth at position 8 of 13 in additional filter chain; firing Filter: 'RequestCacheAwareFilter'
    08-2018-18 17:21:01  - /auth at position 9 of 13 in additional filter chain; firing Filter: 'SecurityContextHolderAwareRequestFilter'
    08-2018-18 17:21:01  - /auth at position 10 of 13 in additional filter chain; firing Filter: 'AnonymousAuthenticationFilter'
    08-2018-18 17:21:01  - SecurityContextHolder not populated with anonymous token, as it already contained: 'org.springframework.security.authentication.UsernamePasswordAuthenticationToken@b0b037b2: Principal: org.springframework.security.core.userdetails.User@f4bdcd82: Username: mayank.bpt@gmail.com; Password: [PROTECTED]; Enabled: true; AccountNonExpired: true; credentialsNonExpired: true; AccountNonLocked: true; Granted Authorities: ROLE_user; Credentials: [PROTECTED]; Authenticated: true; Details: org.springframework.security.web.authentication.WebAuthenticationDetails@0: RemoteIpAddress: 0:0:0:0:0:0:0:1; SessionId: C3AE04F3ED675FD0D08C99C699E6DE9F; Granted Authorities: ROLE_user'
    08-2018-18 17:21:01  - /auth at position 11 of 13 in additional filter chain; firing Filter: 'SessionManagementFilter'
    08-2018-18 17:21:01  - /auth at position 12 of 13 in additional filter chain; firing Filter: 'ExceptionTranslationFilter'
    08-2018-18 17:21:01  - /auth at position 13 of 13 in additional filter chain; firing Filter: 'FilterSecurityInterceptor'
    08-2018-18 17:21:01  - Checking match of request : '/auth'; against '/resources/**'
    08-2018-18 17:21:01  - Checking match of request : '/auth'; against '/registration'
    08-2018-18 17:21:01  - Checking match of request : '/auth'; against '/forgot'
    08-2018-18 17:21:01  - Checking match of request : '/auth'; against '/passwordchange'
    08-2018-18 17:21:01  - Checking match of request : '/auth'; against '/sandmail'
    08-2018-18 17:21:01  - Checking match of request : '/auth'; against '/resetpassword'
    08-2018-18 17:21:01  - Checking match of request : '/auth'; against '/vailidateotp'
    08-2018-18 17:21:01  - Checking match of request : '/auth'; against '/auth'
    08-2018-18 17:21:01  - Secure object: FilterInvocation: URL: /auth; Attributes: [hasAnyRole('ROLE_user')]
    08-2018-18 17:21:01  - Previously Authenticated: org.springframework.security.authentication.UsernamePasswordAuthenticationToken@b0b037b2: Principal: org.springframework.security.core.userdetails.User@f4bdcd82: Username: mayank.bpt@gmail.com; Password: [PROTECTED]; Enabled: true; AccountNonExpired: true; credentialsNonExpired: true; AccountNonLocked: true; Granted Authorities: ROLE_user; Credentials: [PROTECTED]; Authenticated: true; Details: org.springframework.security.web.authentication.WebAuthenticationDetails@0: RemoteIpAddress: 0:0:0:0:0:0:0:1; SessionId: C3AE04F3ED675FD0D08C99C699E6DE9F; Granted Authorities: ROLE_user
    08-2018-18 17:21:01  - Voter: org.springframework.security.web.access.expression.WebExpressionVoter@76518d, returned: 1
    08-2018-18 17:21:01  - Authorization successful
    08-2018-18 17:21:01  - RunAsManager did not change Authentication object
    08-2018-18 17:21:01  - /auth reached end of additional filter chain; proceeding with original chain
    08-2018-18 17:21:01  - userid  mayank.bpt@gmail.com
    08-2018-18 17:21:01  - SecurityContext 'org.springframework.security.core.context.SecurityContextImpl@b086dc79: Authentication: com.hftsolution.auth.OtpAuthenticator@b086dc79: Principal: org.springframework.security.core.userdetails.User@f4bdcd82: Username: mayank.bpt@gmail.com; Password: [PROTECTED]; Enabled: true; AccountNonExpired: true; credentialsNonExpired: true; AccountNonLocked: true; Granted Authorities: ROLE_user; Credentials: [PROTECTED]; Authenticated: true; Details: null; Granted Authorities: ROLE_user, user' stored to HttpSession: 'org.apache.catalina.session.StandardSessionFacade@d3937f
    08-2018-18 17:21:01  - Chain processed normally
    08-2018-18 17:21:01  - SecurityContextHolder now cleared, as request processing completed

任何帮助将不胜感激。

0 个答案:

没有答案