首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >为什么Security ()在服务器上返回null

为什么Security ()在服务器上返回null
EN

Stack Overflow用户
提问于 2021-11-11 09:45:01
回答 2查看 566关注 0票数 0

我有一个web应用程序,并使用spring安全性进行身份验证。

所有页面都需要身份验证,但登录页不需要身份验证。

在我的情况下,在本地环境上登录后,我成功地访问了其他需要身份验证的页面。但是我在服务器environment.Because上失败了,getAuthentication()返回null。

我不知道为什么getAuthentication()在服务器环境中返回null。

登录后移动到/foo (本地日志)

代码语言:javascript
运行
复制
[2021-11-11 15:20:05:32506][http-nio-8080-exec-7] DEBUG org.springframework.security.authentication.dao.DaoAuthenticationProvider.createSuccessAuthentication - Authenticated user
[2021-11-11 15:20:05:32507][http-nio-8080-exec-7] DEBUG org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter.successfulAuthentication - Set SecurityContextHolder to UsernamePasswordAuthenticationToken [Principal=LoginUser(loginInfo=com.bar.entity.LoginInfoEntity@12234790), Credentials=[PROTECTED], Authenticated=true, Details=WebAuthenticationDetails [RemoteIpAddress=0:0:0:0:0:0:0:1, SessionId=null], Granted Authorities=[]]
[2021-11-11 15:20:06:33756][http-nio-8080-exec-7] WARN  org.apache.catalina.util.SessionIdGeneratorBase.log - Creation of SecureRandom instance for session ID generation using [SHA1PRNG] took [1,246] milliseconds.
[2021-11-11 15:20:06:33760][http-nio-8080-exec-7] DEBUG org.springframework.security.web.context.HttpSessionSecurityContextRepository.saveContext - Stored SecurityContextImpl [Authentication=UsernamePasswordAuthenticationToken [Principal=LoginUser(loginInfo=com.bar.entity.LoginInfoEntity@12234790), Credentials=[PROTECTED], Authenticated=true, Details=WebAuthenticationDetails [RemoteIpAddress=0:0:0:0:0:0:0:1, SessionId=null], Granted Authorities=[]]] to HttpSession [org.apache.catalina.session.StandardSessionFacade@16178716]
[2021-11-11 15:20:06:33760][http-nio-8080-exec-7] DEBUG org.springframework.security.web.context.HttpSessionSecurityContextRepository.saveContext - Stored SecurityContextImpl [Authentication=UsernamePasswordAuthenticationToken [Principal=LoginUser(loginInfo=com.bar.entity.LoginInfoEntity@12234790), Credentials=[PROTECTED], Authenticated=true, Details=WebAuthenticationDetails [RemoteIpAddress=0:0:0:0:0:0:0:1, SessionId=null], Granted Authorities=[]]] to HttpSession [org.apache.catalina.session.StandardSessionFacade@16178716]
[2021-11-11 15:20:06:33760][http-nio-8080-exec-7] DEBUG org.springframework.security.web.context.SecurityContextPersistenceFilter.doFilter - Cleared SecurityContextHolder to complete request
--move to foo
[2021-11-11 15:20:06:33769][http-nio-8080-exec-8] DEBUG org.springframework.security.web.FilterChainProxy.doFilterInternal - Securing GET /foo
[2021-11-11 15:20:06:33769][http-nio-8080-exec-8] DEBUG org.springframework.security.web.context.HttpSessionSecurityContextRepository.readSecurityContextFromSession - Retrieved SecurityContextImpl [Authentication=UsernamePasswordAuthenticationToken [Principal=LoginUser(loginInfo=com.bar.entity.LoginInfoEntity@12234790), Credentials=[PROTECTED], Authenticated=true, Details=WebAuthenticationDetails [RemoteIpAddress=0:0:0:0:0:0:0:1, SessionId=null], Granted Authorities=[]]]
[2021-11-11 15:20:06:33769][http-nio-8080-exec-8] DEBUG org.springframework.security.web.context.SecurityContextPersistenceFilter.doFilter - Set SecurityContextHolder to SecurityContextImpl [Authentication=UsernamePasswordAuthenticationToken [Principal=LoginUser(loginInfo=com.bar.entity.LoginInfoEntity@12234790), Credentials=[PROTECTED], Authenticated=true, Details=WebAuthenticationDetails [RemoteIpAddress=0:0:0:0:0:0:0:1, SessionId=null], Granted Authorities=[]]]
[2021-11-11 15:20:06:33769][http-nio-8080-exec-8] DEBUG org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping.getHandler - Mapped to com.bar.view.controller.FooController#initalize()
--success
[2021-11-11 15:20:06:33770][http-nio-8080-exec-8] DEBUG org.springframework.security.web.access.intercept.FilterSecurityInterceptor.beforeInvocation - Authorized filter invocation [GET /foo] with attributes [authenticated]

登录后移动到/foo时(服务器日志)。对不起,日志上没有方法名

代码语言:javascript
运行
复制
[2021-11-11 06:17:15:126723][foo] DEBUG org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter - Set SecurityContextHolder to UsernamePasswordAuthenticationToken [Principal=LoginUser(loginInfo=com.bar.entity.LoginInfoEntity@708afefc), Credentials=[PROTECTED], Authenticated=true, Details=WebAuthenticationDetails [RemoteIpAddress=39.110.214.222, SessionId=null], Granted Authorities=[]]
[2021-11-11 06:17:15:126740][foo] DEBUG org.springframework.security.web.context.HttpSessionSecurityContextRepository - Stored SecurityContextImpl [Authentication=UsernamePasswordAuthenticationToken [Principal=LoginUser(loginInfo=com.bar.entity.LoginInfoEntity@708afefc), Credentials=[PROTECTED], Authenticated=true, Details=WebAuthenticationDetails [RemoteIpAddress=39.110.214.222, SessionId=null], Granted Authorities=[]]] to HttpSession [org.apache.catalina.session.StandardSessionFacade@4d6cfed4]
[2021-11-11 06:17:15:126740][foo] DEBUG org.springframework.security.web.context.HttpSessionSecurityContextRepository - Stored SecurityContextImpl [Authentication=UsernamePasswordAuthenticationToken [Principal=LoginUser(loginInfo=com.bar.entity.LoginInfoEntity@708afefc), Credentials=[PROTECTED], Authenticated=true, Details=WebAuthenticationDetails [RemoteIpAddress=39.110.214.222, SessionId=null], Granted Authorities=[]]] to HttpSession [org.apache.catalina.session.StandardSessionFacade@4d6cfed4]
[2021-11-11 06:17:15:126741][foo] DEBUG org.springframework.security.web.context.SecurityContextPersistenceFilter - Cleared SecurityContextHolder to complete request
-- move to foo
[2021-11-11 06:17:15:126766][foo] DEBUG org.springframework.security.web.FilterChainProxy - Securing GET /foo
[2021-11-11 06:17:15:126766][foo] DEBUG org.springframework.security.web.context.SecurityContextPersistenceFilter - Set SecurityContextHolder to empty SecurityContext
[2021-11-11 06:17:15:126766][foo] DEBUG org.springframework.security.web.authentication.AnonymousAuthenticationFilter - Set SecurityContextHolder to anonymous SecurityContext
[2021-11-11 06:17:15:126767][foo] DEBUG org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping - Mapped to com.bar.view.controller.RobotSelectController#initalize()
-- fail
[2021-11-11 06:17:15:126780][foo] DEBUG org.springframework.security.web.access.intercept.FilterSecurityInterceptor - Failed to authorize filter invocation [GET /foo] with attributes [authenticated]

我的源代码

我只有Config和Spring安全

代码语言:javascript
运行
复制
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {


    @Override
    public void configure(WebSecurity web) throws Exception {
      web
        .ignoring()
        .antMatchers("/images/**", "/js/**", "/css/**");
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http
            .authorizeRequests()
              .mvcMatchers(loginPage).permitAll()
              .anyRequest().authenticated()
             .and()
              .formLogin()
               .loginPage(loginPage)
               .loginProcessingUrl(loginSuccessUrl)
               .successHandler(new AuthenticationSuccessHandler() {
                    @Override
                    public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response,
                            Authentication authentication) throws IOException, ServletException {
                        //add Session
                        request.getSession().setMaxInactiveInterval(180000);
                        //move page
                        response.sendRedirect(fooPage);
                    }
                });

    }

}

登录实现UserDetailsService

代码语言:javascript
运行
复制
@Service
public class Login implements UserDetailsService{
    
    
    private final LoginInfoRepository loginRepo;
    
    @Autowired
    public Login(LoginInfoRepository loginRepo) {
        this.loginRepo = loginRepo;
    }

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        LoginInfoEntity entity = loginRepo.findById(username)
                .orElseThrow(() -> new UsernameNotFoundException("not exist user"));
        
        UserDetails userDetails = new LoginUser(entity);
        
        return userDetails; 
    }
    
}

会话信息的loginUser使用

代码语言:javascript
运行
复制
public class LoginUser extends User {

    @SuppressWarnings("unchecked")
    public LoginUser(LoginInfoEntity loginInfo) {
        super(loginInfo.getUserId(), loginInfo.getPassword(), 
                loginInfo.isAvailable(), true, true, true, Collections.EMPTY_SET);
    }
}

谢谢你的阅读。

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2021-11-13 14:36:29

我解决了问题。谢谢亚瑟·克莱佐维奇。原因是contextpath不重定向。我认为本地环境等同于服务器环境。但是Server环境有contextpath,因为我没有设置contextpath。它导致url涉及contextpath。

例如)

  • Succeed在本地- http://99.99.99/foo

登录后获取会话

  • Failed在服务器- http://99.99.99/foo(question's url)

中登录后获取会话

  • Succeed在服务器-http://99.99.99/contextpath/foo

中登录后获取会话

有几种方法可以删除contextpath的url。我选择了最简单的方式更改war名称文件

代码语言:javascript
运行
复制
foo.war -> root.war

在Spring-安全运行良好之后,没有修改代码。

票数 0
EN

Stack Overflow用户

发布于 2021-11-11 10:07:11

org.springframework.security.web.authentication.AnonymousAuthenticationFilter

2021-11 06:17:15:126766调试SecurityContextHolder到匿名SecurityContext

这是理解问题的关键。当您进行重定向时,您正在重定向用户,是的。但是,他的会话信息( cookie )或其他东西并不是重定向请求的一部分。

因此,从/foo端点的角度来看,它不会获得任何凭据信息并将请求视为匿名。

如果你能处理掉这段代码..。

代码语言:javascript
运行
复制
successHandler(.. do redirect ...)

不要像这样做重定向,而是像this那样做,这样可能会解决问题。

通过defaultSuccessUrl重定向

代码语言:javascript
运行
复制
 http.formLogin().defaultSuccessUrl("/success.html", true);

这能解决你的问题吗?在评论中告诉我。

您还可以启用HTTP跟踪,并确切地看到哪个请求与哪个头和有效负载一起到达/foo端点,这将使诊断问题变得更加容易。

您是使用cookie还是JWT进行身份验证?在评论中告诉我。

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/69926150

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档