简体   繁体   English

Spring Security如何在Servlet上工作

[英]How does spring security work on a Servlet

I have a java that calls a Servlet: 我有一个调用Servlet的Java:

public class UserServlet extends HttpServlet {

    @Autowired
    private UserService userService;

    @Override
    protected void service(final HttpServletRequest request, final HttpServletResponse response) throws ServletException, IOException {
        userService.checkUser();
        userService.doSomethingRestricted();
    }

    @Override
    public void init(final ServletConfig config) throws ServletException {
            SpringBeanAutowiringSupport.processInjectionBasedOnCurrentContext(this);
            SpringBeanAutowiringSupport.processInjectionBasedOnServletContext(this, config.getServletContext());
            super.init(config);
    }

}

And my autowired service : 还有我的自动接线服务:

@Component(value = "userService")
public class UserService {

    public boolean checkUser() {
        if (SecurityContextHolder.getContext().getAuthentication() != null) {
            Authentication auth = SecurityContextHolder.getContext().getAuthentication();
                if (auth != null && auth.getPrincipal() != null && auth.getPrincipal() instanceof User) {
                    User springUser = (User) auth.getPrincipal();
                    if (springUser != null) {
                        LOG.debug("USER CONNECTED :: {}", springUser.getUsername());
                    }
                }
        } else {
            LOG.debug("NO CONNECTED USER, CREATING ONE");
            Collection<GrantedAuthority> authorities = getGrantedAuthorities();
            org.springframework.security.core.userdetails.User springUser = new org.springframework.security.core.userdetails.User("user","password", true, true, true, true, authorities);
            Authentication auth = new UsernamePasswordAuthenticationToken(springUser, "", authorities);
            SecurityContext sc = new SecurityContextImpl();
            sc.setAuthentication(auth);
            SecurityContextHolder.setContext(sc);
        }
        return true;
    }   


    @Secured({ "CONNECTED" })
    public void doSomethingRestricted() {
        LOG.debug("SOMETHING RESTRICTED HAS BEEN DONE!!");
    }

}
  • When I test my application the first time, the Java client sends a POST to the server, the server would check the user and would not find a context: a new context would be created. 当我第一次测试应用程序时,Java客户端将POST发送到服务器,服务器将检查用户并且找不到上下文:将创建一个新的上下文。

  • When I run the java client the subsequent times, I find an existing Context (the one created in the first call). 在随后的几次运行Java客户端时,我发现了一个现有的上下文(在第一次调用中创建的上下文)。

Obviously there's something missing because If the first user logs in successfully it does not mean any user can connect. 显然缺少某些内容,因为如果第一个用户成功登录,并不意味着任何用户都可以连接。

What am I missing ? 我想念什么? At first I thought about using sessions for each Java client's instance (I dont have web browser clients so I need to set the session ids manually), but when is Spring supposed to get or set the session id in the http request ? 最初,我考虑过为每个Java客户端实例使用会话(我没有Web浏览器客户端,因此我需要手动设置会话ID),但是Spring应该何时在http请求中获取或设置会话ID?

TL;DR : What does SecurityContextHolder.getContext().getAuthentication() do in my example ? TL; DR :在我的示例中, SecurityContextHolder.getContext().getAuthentication()做什么?

It gets you the authentication details of the current login user , have you added 是否添加了当前登录用户的身份验证详细信息

<bean id="httpSessionFilter" class="org.springframework.security.web.context.SecurityContextPersistenceFilter"/>

to introduce login for web application , spring security is designed to work with POJO as well , you would need to add this filter in your mapping if you are doing it old way. 为了引入Web应用程序的登录,spring security也设计为可与POJO一起使用,如果您使用旧方法,则需要在映射中添加此过滤器。 If you are using http tags in applicationContext then it should work as it is. 如果您在applicationContext中使用http标记,则它应该可以正常工作。

</security:filter-chain-map> 

Its been quite long since I have used spring security without the new http tags in applicatin Context . 自从我在applicatin Context中使用了没有新的http标记的spring security以来已经有很长时间了。 The spring security context comes with different filters , SecurityContextPersistenceFilter determines how the context is persisted. Spring安全性上下文带有不同的过滤器,SecurityContextPersistenceFilter确定如何持久化上下文。

"org.springframework.security.web.context.SecurityContextPersistenceFilter" is for persisting security context per session . “ org.springframework.security.web.context.SecurityContextPersistenceFilter”用于持久保存每个会话的安全上下文。

Spring security derived from its integration with acegi security which used to have "net.sf.acegisecurity. ui.webapp.HttpSessionIntegrationFilter" filter for the same task 春季安全性源自其与acegi安全性的集成,该安全性过去曾为同一任务使用“ net.sf.acegisecurity。ui.webapp.HttpSessionIntegrationFilter”过滤器

这是一个过滤器,因此spring可以基于sessionid识别会话。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM