简体   繁体   中英

How does spring security work on a Servlet

I have a java that calls a Servlet:

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.

  • When I run the java client the subsequent times, I find an existing Context (the one created in the first call).

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 ?

: What does SecurityContextHolder.getContext().getAuthentication() do in my example ? :在我的示例中, 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. If you are using http tags in applicationContext then it should work as it is.

</security:filter-chain-map> 

Its been quite long since I have used spring security without the new http tags in applicatin Context . The spring security context comes with different filters , SecurityContextPersistenceFilter determines how the context is persisted.

"org.springframework.security.web.context.SecurityContextPersistenceFilter" is for persisting security context per session .

Spring security derived from its integration with acegi security which used to have "net.sf.acegisecurity. ui.webapp.HttpSessionIntegrationFilter" filter for the same task

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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