(window.webpackJsonp=window.webpackJsonp||[]).push([[219],{651:function(e,t,a){"use strict";a.r(t);var n=a(56),i=Object(n.a)({},(function(){var e=this,t=e.$createElement,a=e._self._c||t;return a("ContentSlotsDistributor",{attrs:{"slot-key":e.$parent.slotKey}},[a("h1",{attrs:{id:"spring-security-faq"}},[a("a",{staticClass:"header-anchor",attrs:{href:"#spring-security-faq"}},[e._v("#")]),e._v(" Spring Security FAQ")]),e._v(" "),a("ul",[a("li",[a("p",[a("a",{attrs:{href:"#appendix-faq-general-questions"}},[e._v("General Questions")])])]),e._v(" "),a("li",[a("p",[a("a",{attrs:{href:"#appendix-faq-common-problems"}},[e._v("Common Problems")])])]),e._v(" "),a("li",[a("p",[a("a",{attrs:{href:"#appendix-faq-architecture"}},[e._v("Spring Security Architecture Questions")])])]),e._v(" "),a("li",[a("p",[a("a",{attrs:{href:"#appendix-faq-howto"}},[e._v('Common "Howto" Requests')])])])]),e._v(" "),a("h2",{attrs:{id:"general-questions"}},[a("a",{staticClass:"header-anchor",attrs:{href:"#general-questions"}},[e._v("#")]),e._v(" General Questions")]),e._v(" "),a("ol",[a("li",[a("p",[a("a",{attrs:{href:"#appendix-faq-other-concerns"}},[e._v("Will Spring Security take care of all my application security requirements?")])])]),e._v(" "),a("li",[a("p",[a("a",{attrs:{href:"#appendix-faq-web-xml"}},[e._v("Why not just use web.xml security?")])])]),e._v(" "),a("li",[a("p",[a("a",{attrs:{href:"#appendix-faq-requirements"}},[e._v("What Java and Spring Framework versions are required?")])])]),e._v(" "),a("li",[a("p",[a("a",{attrs:{href:"#appendix-faq-start-simple"}},[e._v("I’m new to Spring Security and I need to build an application that supports CAS single sign-on over HTTPS, while allowing Basic authentication locally for certain URLs, authenticating against multiple back end user information sources (LDAP and JDBC). I’ve copied some configuration files I found but it doesn’t work.")])])])]),e._v(" "),a("h3",{attrs:{id:"will-spring-security-take-care-of-all-my-application-security-requirements"}},[a("a",{staticClass:"header-anchor",attrs:{href:"#will-spring-security-take-care-of-all-my-application-security-requirements"}},[e._v("#")]),e._v(" Will Spring Security take care of all my application security requirements?")]),e._v(" "),a("p",[e._v("Spring Security provides you with a very flexible framework for your authentication and authorization requirements, but there are many other considerations for building a secure application that are outside its scope.\nWeb applications are vulnerable to all kinds of attacks which you should be familiar with, preferably before you start development so you can design and code with them in mind from the beginning.\nCheck out the "),a("a",{attrs:{href:"https://www.owasp.org/",target:"_blank",rel:"noopener noreferrer"}},[e._v("OWASP web site"),a("OutboundLink")],1),e._v(" for information on the major issues facing web application developers and the countermeasures you can use against them.")]),e._v(" "),a("h3",{attrs:{id:"why-not-just-use-web-xml-security"}},[a("a",{staticClass:"header-anchor",attrs:{href:"#why-not-just-use-web-xml-security"}},[e._v("#")]),e._v(" Why not just use web.xml security?")]),e._v(" "),a("p",[e._v("Let’s assume you’re developing an enterprise application based on Spring.\nThere are four security concerns you typically need to address: authentication, web request security, service layer security (i.e. your methods that implement business logic), and domain object instance security (i.e. different domain objects have different permissions). With these typical requirements in mind:")]),e._v(" "),a("ol",[a("li",[a("p",[a("em",[e._v("Authentication")]),e._v(': The servlet specification provides an approach to authentication.\nHowever, you will need to configure the container to perform authentication which typically requires editing of container-specific "realm" settings.\nThis makes a non-portable configuration, and if you need to write an actual Java class to implement the container’s authentication interface, it becomes even more non-portable.\nWith Spring Security you achieve complete portability - right down to the WAR level.\nAlso, Spring Security offers a choice of production-proven authentication providers and mechanisms, meaning you can switch your authentication approaches at deployment time.\nThis is particularly valuable for software vendors writing products that need to work in an unknown target environment.')])]),e._v(" "),a("li",[a("p",[a("em",[e._v("Web request security:")]),e._v(" The servlet specification provides an approach to secure your request URIs.\nHowever, these URIs can only be expressed in the servlet specification’s own limited URI path format.\nSpring Security provides a far more comprehensive approach.\nFor instance, you can use Ant paths or regular expressions, you can consider parts of the URI other than simply the requested page (e.g.\nyou can consider HTTP GET parameters) and you can implement your own runtime source of configuration data.\nThis means your web request security can be dynamically changed during the actual execution of your webapp.")])]),e._v(" "),a("li",[a("p",[a("em",[e._v("Service layer and domain object security:")]),e._v(" The absence of support in the servlet specification for services layer security or domain object instance security represent serious limitations for multi-tiered applications.\nTypically developers either ignore these requirements, or implement security logic within their MVC controller code (or even worse, inside the views). There are serious disadvantages with this approach:")]),e._v(" "),a("ol",[a("li",[a("p",[a("em",[e._v("Separation of concerns:")]),e._v(" Authorization is a crosscutting concern and should be implemented as such.\nMVC controllers or views implementing authorization code makes it more difficult to test both the controller and authorization logic, more difficult to debug, and will often lead to code duplication.")])]),e._v(" "),a("li",[a("p",[a("em",[e._v("Support for rich clients and web services:")]),e._v(" If an additional client type must ultimately be supported, any authorization code embedded within the web layer is non-reusable.\nIt should be considered that Spring remoting exporters only export service layer beans (not MVC controllers). As such authorization logic needs to be located in the services layer to support a multitude of client types.")])]),e._v(" "),a("li",[a("p",[a("em",[e._v("Layering issues:")]),e._v(" An MVC controller or view is simply the incorrect architectural layer to implement authorization decisions concerning services layer methods or domain object instances.\nWhilst the Principal may be passed to the services layer to enable it to make the authorization decision, doing so would introduce an additional argument on every services layer method.\nA more elegant approach is to use a ThreadLocal to hold the Principal, although this would likely increase development time to a point where it would become more economical (on a cost-benefit basis) to simply use a dedicated security framework.")])]),e._v(" "),a("li",[a("p",[a("em",[e._v("Authorisation code quality:")]),e._v(' It is often said of web frameworks that they "make it easier to do the right things, and harder to do the wrong things". Security frameworks are the same, because they are designed in an abstract manner for a wide range of purposes.\nWriting your own authorization code from scratch does not provide the "design check" a framework would offer, and in-house authorization code will typically lack the improvements that emerge from widespread deployment, peer review and new versions.')])])])])]),e._v(" "),a("p",[e._v("For simple applications, servlet specification security may just be enough.\nAlthough when considered within the context of web container portability, configuration requirements, limited web request security flexibility, and non-existent services layer and domain object instance security, it becomes clear why developers often look to alternative solutions.")]),e._v(" "),a("h3",{attrs:{id:"what-java-and-spring-framework-versions-are-required"}},[a("a",{staticClass:"header-anchor",attrs:{href:"#what-java-and-spring-framework-versions-are-required"}},[e._v("#")]),e._v(" What Java and Spring Framework versions are required?")]),e._v(" "),a("p",[e._v("Spring Security 3.0 and 3.1 require at least JDK 1.5 and also require Spring 3.0.3 as a minimum.\nIdeally you should be using the latest release versions to avoid problems.")]),e._v(" "),a("p",[e._v("Spring Security 2.0.x requires a minimum JDK version of 1.4 and is built against Spring 2.0.x.\nIt should also be compatible with applications using Spring 2.5.x.")]),e._v(" "),a("h3",{attrs:{id:"i-ve-copied-some-configuration-files-i-found-but-it-doesn-t-work"}},[a("a",{staticClass:"header-anchor",attrs:{href:"#i-ve-copied-some-configuration-files-i-found-but-it-doesn-t-work"}},[e._v("#")]),e._v(" . I’ve copied some configuration files I found but it doesn’t work.")]),e._v(" "),a("p",[e._v("What could be wrong?")]),e._v(" "),a("p",[e._v("Or substitute an alternative complex scenario…​")]),e._v(" "),a("p",[e._v("Realistically, you need an understanding of the technologies you are intending to use before you can successfully build applications with them.\nSecurity is complicated.\nSetting up a simple configuration using a login form and some hard-coded users using Spring Security’s namespace is reasonably straightforward.\nMoving to using a backed JDBC database is also easy enough.\nBut if you try and jump straight to a complicated deployment scenario like this you will almost certainly be frustrated.\nThere is a big jump in the learning curve required to set up systems like CAS, configure LDAP servers and install SSL certificates properly.\nSo you need to take things one step at a time.")]),e._v(" "),a("p",[e._v('From a Spring Security perspective, the first thing you should do is follow the "Getting Started" guide on the web site.\nThis will take you through a series of steps to get up and running and get some idea of how the framework operates.\nIf you are using other technologies which you aren’t familiar with then you should do some research and try to make sure you can use them in isolation before combining them in a complex system.')]),e._v(" "),a("h2",{attrs:{id:"common-problems"}},[a("a",{staticClass:"header-anchor",attrs:{href:"#common-problems"}},[e._v("#")]),e._v(" Common Problems")]),e._v(" "),a("ol",[a("li",[a("p",[e._v("Authentication")]),e._v(" "),a("ol",[a("li",[a("p",[a("a",{attrs:{href:"#appendix-faq-bad-credentials"}},[e._v('When I try to log in, I get an error message that says "Bad Credentials". What’s wrong?')])])]),e._v(" "),a("li",[a("p",[a("a",{attrs:{href:"#appendix-faq-login-loop"}},[e._v('My application goes into an "endless loop" when I try to login, what’s going on?')])])]),e._v(" "),a("li",[a("p",[a("a",{attrs:{href:"#appendix-faq-anon-access-denied"}},[e._v('I get an exception with the message "Access is denied (user is anonymous);". What’s wrong?')])])]),e._v(" "),a("li",[a("p",[a("a",{attrs:{href:"#appendix-faq-cached-secure-page"}},[e._v("Why can I still see a secured page even after I’ve logged out of my application?")])])]),e._v(" "),a("li",[a("p",[a("a",{attrs:{href:"#auth-exception-credentials-not-found"}},[e._v('I get an exception with the message "An Authentication object was not found in the SecurityContext". What’s wrong?')])])]),e._v(" "),a("li",[a("p",[a("a",{attrs:{href:"#appendix-faq-ldap-authentication"}},[e._v("I can’t get LDAP authentication to work.")])])])])]),e._v(" "),a("li",[a("p",[e._v("Session Management")]),e._v(" "),a("ol",[a("li",[a("p",[a("a",{attrs:{href:"#appendix-faq-concurrent-session-same-browser"}},[e._v("I’m using Spring Security’s concurrent session control to prevent users from logging in more than once at a time.")])])]),e._v(" "),a("li",[a("p",[a("a",{attrs:{href:"#appendix-faq-new-session-on-authentication"}},[e._v("Why does the session Id change when I authenticate through Spring Security?")])])]),e._v(" "),a("li",[a("p",[a("a",{attrs:{href:"#appendix-faq-tomcat-https-session"}},[e._v("I’m using Tomcat (or some other servlet container) and have enabled HTTPS for my login page, switching back to HTTP afterwards.")])])]),e._v(" "),a("li",[a("p",[a("a",{attrs:{href:"#appendix-faq-session-listener-missing"}},[e._v("I’m trying to use the concurrent session-control support but it won’t let me log back in, even if I’m sure I’ve logged out and haven’t exceeded the allowed sessions.")])])]),e._v(" "),a("li",[a("p",[a("a",{attrs:{href:"#appendix-faq-unwanted-session-creation"}},[e._v("Spring Security is creating a session somewhere, even though I’ve configured it not to, by setting the create-session attribute to never.")])])])])]),e._v(" "),a("li",[a("p",[e._v("Miscellaneous")]),e._v(" "),a("ol",[a("li",[a("p",[a("a",{attrs:{href:"#appendix-faq-forbidden-csrf"}},[e._v("I get a 403 Forbidden when performing a POST")])])]),e._v(" "),a("li",[a("p",[a("a",{attrs:{href:"#appendix-faq-no-security-on-forward"}},[e._v("I’m forwarding a request to another URL using the RequestDispatcher, but my security constraints aren’t being applied.")])])]),e._v(" "),a("li",[a("p",[a("a",{attrs:{href:"#appendix-faq-method-security-in-web-context"}},[e._v("I have added Spring Security’s element to my application context but if I add security annotations to my Spring MVC controller beans (Struts actions etc.) then they don’t seem to have an effect.")])])]),e._v(" "),a("li",[a("p",[a("a",{attrs:{href:"#appendix-faq-no-filters-no-context"}},[e._v("I have a user who has definitely been authenticated, but when I try to access the SecurityContextHolder during some requests, the Authentication is null.")])])]),e._v(" "),a("li",[a("p",[a("a",{attrs:{href:"#appendix-faq-method-security-with-taglib"}},[e._v("The authorize JSP Tag doesn’t respect my method security annotations when using the URL attribute.")])])])])])]),e._v(" "),a("h3",{attrs:{id:"when-i-try-to-log-in-i-get-an-error-message-that-says-bad-credentials-what-s-wrong"}},[a("a",{staticClass:"header-anchor",attrs:{href:"#when-i-try-to-log-in-i-get-an-error-message-that-says-bad-credentials-what-s-wrong"}},[e._v("#")]),e._v(' When I try to log in, I get an error message that says "Bad Credentials". What’s wrong?')]),e._v(" "),a("p",[e._v("This means that authentication has failed.\nIt doesn’t say why, as it is good practice to avoid giving details which might help an attacker guess account names or passwords.")]),e._v(" "),a("p",[e._v("This also means that if you ask this question in the forum, you will not get an answer unless you provide additional information.\nAs with any issue you should check the output from the debug log, note any exception stacktraces and related messages.\nStep through the code in a debugger to see where the authentication fails and why.\nWrite a test case which exercises your authentication configuration outside of the application.\nMore often than not, the failure is due to a difference in the password data stored in a database and that entered by the user.\nIf you are using hashed passwords, make sure the value stored in your database is "),a("em",[e._v("exactly")]),e._v(" the same as the value produced by the "),a("code",[e._v("PasswordEncoder")]),e._v(" configured in your application.")]),e._v(" "),a("h3",{attrs:{id:"my-application-goes-into-an-endless-loop-when-i-try-to-login-what-s-going-on"}},[a("a",{staticClass:"header-anchor",attrs:{href:"#my-application-goes-into-an-endless-loop-when-i-try-to-login-what-s-going-on"}},[e._v("#")]),e._v(' My application goes into an "endless loop" when I try to login, what’s going on?')]),e._v(" "),a("p",[e._v('A common user problem with infinite loop and redirecting to the login page is caused by accidentally configuring the login page as a "secured" resource.\nMake sure your configuration allows anonymous access to the login page, either by excluding it from the security filter chain or marking it as requiring ROLE_ANONYMOUS.')]),e._v(" "),a("p",[e._v('If your AccessDecisionManager includes an AuthenticatedVoter, you can use the attribute "IS_AUTHENTICATED_ANONYMOUSLY". This is automatically available if you are using the standard namespace configuration setup.')]),e._v(" "),a("p",[e._v("From Spring Security 2.0.1 onwards, when you are using namespace-based configuration, a check will be made on loading the application context and a warning message logged if your login page appears to be protected.")]),e._v(" "),a("h3",{attrs:{id:"what-s-wrong"}},[a("a",{staticClass:"header-anchor",attrs:{href:"#what-s-wrong"}},[e._v("#")]),e._v(' ;". What’s wrong?')]),e._v(" "),a("p",[e._v("This is a debug level message which occurs the first time an anonymous user attempts to access a protected resource.")]),e._v(" "),a("div",{staticClass:"language- extra-class"},[a("pre",{pre:!0,attrs:{class:"language-text"}},[a("code",[e._v("DEBUG [ExceptionTranslationFilter] - Access is denied (user is anonymous); redirecting to authentication entry point\norg.springframework.security.AccessDeniedException: Access is denied\nat org.springframework.security.vote.AffirmativeBased.decide(AffirmativeBased.java:68)\nat org.springframework.security.intercept.AbstractSecurityInterceptor.beforeInvocation(AbstractSecurityInterceptor.java:262)\n")])])]),a("p",[e._v("It is normal and shouldn’t be anything to worry about.")]),e._v(" "),a("h3",{attrs:{id:"why-can-i-still-see-a-secured-page-even-after-i-ve-logged-out-of-my-application"}},[a("a",{staticClass:"header-anchor",attrs:{href:"#why-can-i-still-see-a-secured-page-even-after-i-ve-logged-out-of-my-application"}},[e._v("#")]),e._v(" Why can I still see a secured page even after I’ve logged out of my application?")]),e._v(" "),a("p",[e._v('The most common reason for this is that your browser has cached the page and you are seeing a copy which is being retrieved from the browsers cache.\nVerify this by checking whether the browser is actually sending the request (check your server access logs, the debug log or use a suitable browser debugging plugin such as "Tamper Data" for Firefox). This has nothing to do with Spring Security and you should configure your application or server to set the appropriate '),a("code",[e._v("Cache-Control")]),e._v(" response headers.\nNote that SSL requests are never cached.")]),e._v(" "),a("h3",{attrs:{id:"i-get-an-exception-with-the-message-an-authentication-object-was-not-found-in-the-securitycontext-what-s-wrong"}},[a("a",{staticClass:"header-anchor",attrs:{href:"#i-get-an-exception-with-the-message-an-authentication-object-was-not-found-in-the-securitycontext-what-s-wrong"}},[e._v("#")]),e._v(' I get an exception with the message "An Authentication object was not found in the SecurityContext". What’s wrong?')]),e._v(" "),a("p",[e._v("This is a another debug level message which occurs the first time an anonymous user attempts to access a protected resource, but when you do not have an "),a("code",[e._v("AnonymousAuthenticationFilter")]),e._v(" in your filter chain configuration.")]),e._v(" "),a("div",{staticClass:"language- extra-class"},[a("pre",{pre:!0,attrs:{class:"language-text"}},[a("code",[e._v("DEBUG [ExceptionTranslationFilter] - Authentication exception occurred; redirecting to authentication entry point\norg.springframework.security.AuthenticationCredentialsNotFoundException:\n\t\t\t\t\t\t\tAn Authentication object was not found in the SecurityContext\nat org.springframework.security.intercept.AbstractSecurityInterceptor.credentialsNotFound(AbstractSecurityInterceptor.java:342)\nat org.springframework.security.intercept.AbstractSecurityInterceptor.beforeInvocation(AbstractSecurityInterceptor.java:254)\n")])])]),a("p",[e._v("It is normal and shouldn’t be anything to worry about.")]),e._v(" "),a("h3",{attrs:{id:"i-can-t-get-ldap-authentication-to-work"}},[a("a",{staticClass:"header-anchor",attrs:{href:"#i-can-t-get-ldap-authentication-to-work"}},[e._v("#")]),e._v(" I can’t get LDAP authentication to work.")]),e._v(" "),a("p",[e._v("What’s wrong with my configuration?")]),e._v(" "),a("p",[e._v("Note that the permissions for an LDAP directory often do not allow you to read the password for a user.\nHence it is often not possible to use the "),a("a",{attrs:{href:"#appendix-faq-what-is-userdetailservice"}},[e._v("What is a UserDetailsService and do I need one?")]),e._v(' where Spring Security compares the stored password with the one submitted by the user.\nThe most common approach is to use LDAP "bind", which is one of the operations supported by '),a("a",{attrs:{href:"https://en.wikipedia.org/wiki/Lightweight_Directory_Access_Protocol",target:"_blank",rel:"noopener noreferrer"}},[e._v("the LDAP protocol"),a("OutboundLink")],1),e._v(". With this approach, Spring Security validates the password by attempting to authenticate to the directory as the user.")]),e._v(" "),a("p",[e._v("The most common problem with LDAP authentication is a lack of knowledge of the directory server tree structure and configuration.\nThis will be different in different companies, so you have to find it out yourself.\nBefore adding a Spring Security LDAP configuration to an application, it’s a good idea to write a simple test using standard Java LDAP code (without Spring Security involved), and make sure you can get that to work first.\nFor example, to authenticate a user, you could use the following code:")]),e._v(" "),a("p",[e._v("Java")]),e._v(" "),a("div",{staticClass:"language- extra-class"},[a("pre",{pre:!0,attrs:{class:"language-text"}},[a("code",[e._v('@Test\npublic void ldapAuthenticationIsSuccessful() throws Exception {\n\t\tHashtable env = new Hashtable();\n\t\tenv.put(Context.SECURITY_AUTHENTICATION, "simple");\n\t\tenv.put(Context.SECURITY_PRINCIPAL, "cn=joe,ou=users,dc=mycompany,dc=com");\n\t\tenv.put(Context.PROVIDER_URL, "ldap://mycompany.com:389/dc=mycompany,dc=com");\n\t\tenv.put(Context.SECURITY_CREDENTIALS, "joespassword");\n\t\tenv.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory");\n\n\t\tInitialLdapContext ctx = new InitialLdapContext(env, null);\n\n}\n')])])]),a("p",[e._v("Kotlin")]),e._v(" "),a("div",{staticClass:"language- extra-class"},[a("pre",{pre:!0,attrs:{class:"language-text"}},[a("code",[e._v('@Test\nfun ldapAuthenticationIsSuccessful() {\n val env = Hashtable()\n env[Context.SECURITY_AUTHENTICATION] = "simple"\n env[Context.SECURITY_PRINCIPAL] = "cn=joe,ou=users,dc=mycompany,dc=com"\n env[Context.PROVIDER_URL] = "ldap://mycompany.com:389/dc=mycompany,dc=com"\n env[Context.SECURITY_CREDENTIALS] = "joespassword"\n env[Context.INITIAL_CONTEXT_FACTORY] = "com.sun.jndi.ldap.LdapCtxFactory"\n val ctx = InitialLdapContext(env, null)\n}\n')])])]),a("h3",{attrs:{id:"session-management"}},[a("a",{staticClass:"header-anchor",attrs:{href:"#session-management"}},[e._v("#")]),e._v(" Session Management")]),e._v(" "),a("p",[e._v("Session management issues are a common source of forum questions.\nIf you are developing Java web applications, you should understand how the session is maintained between the servlet container and the user’s browser.\nYou should also understand the difference between secure and non-secure cookies and the implications of using HTTP/HTTPS and switching between the two.\nSpring Security has nothing to do with maintaining the session or providing session identifiers.\nThis is entirely handled by the servlet container.")]),e._v(" "),a("h3",{attrs:{id:"i-m-using-spring-security-s-concurrent-session-control-to-prevent-users-from-logging-in-more-than-once-at-a-time"}},[a("a",{staticClass:"header-anchor",attrs:{href:"#i-m-using-spring-security-s-concurrent-session-control-to-prevent-users-from-logging-in-more-than-once-at-a-time"}},[e._v("#")]),e._v(" I’m using Spring Security’s concurrent session control to prevent users from logging in more than once at a time.")]),e._v(" "),a("p",[e._v("When I open another browser window after logging in, it doesn’t stop me from logging in again.\nWhy can I log in more than once?")]),e._v(" "),a("p",[e._v("Browsers generally maintain a single session per browser instance.\nYou cannot have two separate sessions at once.\nSo if you log in again in another window or tab you are just reauthenticating in the same session.\nThe server doesn’t know anything about tabs, windows or browser instances.\nAll it sees are HTTP requests and it ties those to a particular session according to the value of the JSESSIONID cookie that they contain.\nWhen a user authenticates during a session, Spring Security’s concurrent session control checks the number of "),a("em",[e._v("other authenticated sessions")]),e._v(" that they have.\nIf they are already authenticated with the same session, then re-authenticating will have no effect.")]),e._v(" "),a("h3",{attrs:{id:"why-does-the-session-id-change-when-i-authenticate-through-spring-security"}},[a("a",{staticClass:"header-anchor",attrs:{href:"#why-does-the-session-id-change-when-i-authenticate-through-spring-security"}},[e._v("#")]),e._v(" Why does the session Id change when I authenticate through Spring Security?")]),e._v(" "),a("p",[e._v('With the default configuration, Spring Security changes the session ID when the user authenticates.\nIf you’re using a Servlet 3.1 or newer container, the session ID is simply changed.\nIf you’re using an older container, Spring Security invalidates the existing session, creates a new session, and transfers the session data to the new session.\nChanging the session identifier in this manner prevents"session-fixation" attacks.\nYou can find more about this online and in the reference manual.')]),e._v(" "),a("h3",{attrs:{id:"and-have-enabled-https-for-my-login-page-switching-back-to-http-afterwards"}},[a("a",{staticClass:"header-anchor",attrs:{href:"#and-have-enabled-https-for-my-login-page-switching-back-to-http-afterwards"}},[e._v("#")]),e._v(" and have enabled HTTPS for my login page, switching back to HTTP afterwards.")]),e._v(" "),a("p",[e._v("It doesn’t work - I just end up back at the login page after authenticating.")]),e._v(" "),a("p",[e._v('This happens because sessions created under HTTPS, for which the session cookie is marked as "secure", cannot subsequently be used under HTTP. The browser will not send the cookie back to the server and any session state will be lost (including the security context information). Starting a session in HTTP first should work as the session cookie won’t be marked as secure.\nHowever, Spring Security’s '),a("a",{attrs:{href:"https://docs.spring.io/spring-security/site/docs/3.1.x/reference/springsecurity-single.html#ns-session-fixation",target:"_blank",rel:"noopener noreferrer"}},[e._v("Session Fixation Protection"),a("OutboundLink")],1),e._v(" can interfere with this because it results in a new session ID cookie being sent back to the user’s browser, usually with the secure flag.\nTo get around this, you can disable session fixation protection, but in newer Servlet containers you can also configure session cookies to never use the secure flag.\nNote that switching between HTTP and HTTPS is not a good idea in general, as any application which uses HTTP at all is vulnerable to man-in-the-middle attacks.\nTo be truly secure, the user should begin accessing your site in HTTPS and continue using it until they log out.\nEven clicking on an HTTPS link from a page accessed over HTTP is potentially risky.\nIf you need more convincing, check out a tool like "),a("a",{attrs:{href:"https://github.com/moxie0/sslstrip/",target:"_blank",rel:"noopener noreferrer"}},[e._v("sslstrip"),a("OutboundLink")],1),e._v(".")]),e._v(" "),a("h3",{attrs:{id:"i-m-not-switching-between-http-and-https-but-my-session-is-still-getting-lost"}},[a("a",{staticClass:"header-anchor",attrs:{href:"#i-m-not-switching-between-http-and-https-but-my-session-is-still-getting-lost"}},[e._v("#")]),e._v(" I’m not switching between HTTP and HTTPS but my session is still getting lost")]),e._v(" "),a("p",[e._v("Sessions are maintained either by exchanging a session cookie or by adding a "),a("code",[e._v("jsessionid")]),e._v(" parameter to URLs (this happens automatically if you are using JSTL to output URLs, or if you call "),a("code",[e._v("HttpServletResponse.encodeUrl")]),e._v(" on URLs (before a redirect, for example). If clients have cookies disabled, and you are not rewriting URLs to include the "),a("code",[e._v("jsessionid")]),e._v(", then the session will be lost.\nNote that the use of cookies is preferred for security reasons, as it does not expose the session information in the URL.")]),e._v(" "),a("h3",{attrs:{id:"i-m-trying-to-use-the-concurrent-session-control-support-but-it-won-t-let-me-log-back-in-even-if-i-m-sure-i-ve-logged-out-and-haven-t-exceeded-the-allowed-sessions"}},[a("a",{staticClass:"header-anchor",attrs:{href:"#i-m-trying-to-use-the-concurrent-session-control-support-but-it-won-t-let-me-log-back-in-even-if-i-m-sure-i-ve-logged-out-and-haven-t-exceeded-the-allowed-sessions"}},[e._v("#")]),e._v(" I’m trying to use the concurrent session-control support but it won’t let me log back in, even if I’m sure I’ve logged out and haven’t exceeded the allowed sessions.")]),e._v(" "),a("p",[e._v("Make sure you have added the listener to your web.xml file.\nIt is essential to make sure that the Spring Security session registry is notified when a session is destroyed.\nWithout it, the session information will not be removed from the registry.")]),e._v(" "),a("div",{staticClass:"language- extra-class"},[a("pre",{pre:!0,attrs:{class:"language-text"}},[a("code",[e._v("\n\t\torg.springframework.security.web.session.HttpSessionEventPublisher\n\n")])])]),a("h3",{attrs:{id:"spring-security-is-creating-a-session-somewhere-even-though-i-ve-configured-it-not-to-by-setting-the-create-session-attribute-to-never"}},[a("a",{staticClass:"header-anchor",attrs:{href:"#spring-security-is-creating-a-session-somewhere-even-though-i-ve-configured-it-not-to-by-setting-the-create-session-attribute-to-never"}},[e._v("#")]),e._v(" Spring Security is creating a session somewhere, even though I’ve configured it not to, by setting the create-session attribute to never.")]),e._v(" "),a("p",[e._v("This usually means that the user’s application is creating a session somewhere, but that they aren’t aware of it.\nThe most common culprit is a JSP. Many people aren’t aware that JSPs create sessions by default.\nTo prevent a JSP from creating a session, add the directive "),a("code",[e._v('<%@ page session="false" %>')]),e._v(" to the top of the page.")]),e._v(" "),a("p",[e._v("If you are having trouble working out where a session is being created, you can add some debugging code to track down the location(s). One way to do this would be to add a "),a("code",[e._v("javax.servlet.http.HttpSessionListener")]),e._v(" to your application, which calls "),a("code",[e._v("Thread.dumpStack()")]),e._v(" in the "),a("code",[e._v("sessionCreated")]),e._v(" method.")]),e._v(" "),a("h3",{attrs:{id:"i-get-a-403-forbidden-when-performing-a-post"}},[a("a",{staticClass:"header-anchor",attrs:{href:"#i-get-a-403-forbidden-when-performing-a-post"}},[e._v("#")]),e._v(" I get a 403 Forbidden when performing a POST")]),e._v(" "),a("p",[e._v("If an HTTP 403 Forbidden is returned for HTTP POST, but works for HTTP GET then the issue is most likely related to "),a("a",{attrs:{href:"https://docs.spring.io/spring-security/site/docs/3.2.x/reference/htmlsingle/#csrf",target:"_blank",rel:"noopener noreferrer"}},[e._v("CSRF"),a("OutboundLink")],1),e._v(". Either provide the CSRF Token or disable CSRF protection (not recommended).")]),e._v(" "),a("h3",{attrs:{id:"i-m-forwarding-a-request-to-another-url-using-the-requestdispatcher-but-my-security-constraints-aren-t-being-applied"}},[a("a",{staticClass:"header-anchor",attrs:{href:"#i-m-forwarding-a-request-to-another-url-using-the-requestdispatcher-but-my-security-constraints-aren-t-being-applied"}},[e._v("#")]),e._v(" I’m forwarding a request to another URL using the RequestDispatcher, but my security constraints aren’t being applied.")]),e._v(" "),a("p",[e._v("Filters are not applied by default to forwards or includes.\nIf you really want the security filters to be applied to forwards and/or includes, then you have to configure these explicitly in your web.xml using the element, a child element of .")]),e._v(" "),a("h3",{attrs:{id:"then-they-don-t-seem-to-have-an-effect"}},[a("a",{staticClass:"header-anchor",attrs:{href:"#then-they-don-t-seem-to-have-an-effect"}},[e._v("#")]),e._v(" then they don’t seem to have an effect.")]),e._v(" "),a("p",[e._v("In a Spring web application, the application context which holds the Spring MVC beans for the dispatcher servlet is often separate from the main application context.\nIt is often defined in a file called "),a("code",[e._v("myapp-servlet.xml")]),e._v(', where "myapp" is the name assigned to the Spring '),a("code",[e._v("DispatcherServlet")]),e._v(" in "),a("code",[e._v("web.xml")]),e._v(". An application can have multiple "),a("code",[e._v("DispatcherServlet")]),e._v('s, each with its own isolated application context.\nThe beans in these "child" contexts are not visible to the rest of the application.\nThe"parent" application context is loaded by the '),a("code",[e._v("ContextLoaderListener")]),e._v(" you define in your "),a("code",[e._v("web.xml")]),e._v(" and is visible to all the child contexts.\nThis parent context is usually where you define your security configuration, including the "),a("code",[e._v("")]),e._v(" element). As a result any security constraints applied to methods in these web beans will not be enforced, since the beans cannot be seen from the "),a("code",[e._v("DispatcherServlet")]),e._v(" context.\nYou need to either move the "),a("code",[e._v("")]),e._v(" declaration to the web context or moved the beans you want secured into the main application context.")]),e._v(" "),a("p",[e._v("Generally we would recommend applying method security at the service layer rather than on individual web controllers.")]),e._v(" "),a("h3",{attrs:{id:"i-have-a-user-who-has-definitely-been-authenticated-but-when-i-try-to-access-the-securitycontextholder-during-some-requests-the-authentication-is-null"}},[a("a",{staticClass:"header-anchor",attrs:{href:"#i-have-a-user-who-has-definitely-been-authenticated-but-when-i-try-to-access-the-securitycontextholder-during-some-requests-the-authentication-is-null"}},[e._v("#")]),e._v(" I have a user who has definitely been authenticated, but when I try to access the SecurityContextHolder during some requests, the Authentication is null.")]),e._v(" "),a("p",[e._v("Why can’t I see the user information?")]),e._v(" "),a("p",[e._v("If you have excluded the request from the security filter chain using the attribute "),a("code",[e._v("filters='none'")]),e._v(" in the "),a("code",[e._v("")]),e._v(" element that matches the URL pattern, then the "),a("code",[e._v("SecurityContextHolder")]),e._v(" will not be populated for that request.\nCheck the debug log to see whether the request is passing through the filter chain.\n(You are reading the debug log, right?).")]),e._v(" "),a("h3",{attrs:{id:"the-authorize-jsp-tag-doesn-t-respect-my-method-security-annotations-when-using-the-url-attribute"}},[a("a",{staticClass:"header-anchor",attrs:{href:"#the-authorize-jsp-tag-doesn-t-respect-my-method-security-annotations-when-using-the-url-attribute"}},[e._v("#")]),e._v(" The authorize JSP Tag doesn’t respect my method security annotations when using the URL attribute.")]),e._v(" "),a("p",[e._v("Method security will not hide links when using the "),a("code",[e._v("url")]),e._v(" attribute in "),a("code",[e._v("")]),e._v(" because we cannot readily reverse engineer what URL is mapped to what controller endpoint as controllers can rely on headers, current user, etc to determine what method to invoke.")]),e._v(" "),a("h2",{attrs:{id:"spring-security-architecture-questions"}},[a("a",{staticClass:"header-anchor",attrs:{href:"#spring-security-architecture-questions"}},[e._v("#")]),e._v(" Spring Security Architecture Questions")]),e._v(" "),a("ol",[a("li",[a("p",[a("a",{attrs:{href:"#appendix-faq-where-is-class-x"}},[e._v("How do I know which package class X is in?")])])]),e._v(" "),a("li",[a("p",[a("a",{attrs:{href:"#appendix-faq-namespace-to-bean-mapping"}},[e._v("How do the namespace elements map to conventional bean configurations?")])])]),e._v(" "),a("li",[a("p",[a("a",{attrs:{href:"#appendix-faq-role-prefix"}},[e._v('What does "ROLE_" mean and why do I need it on my role names?')])])]),e._v(" "),a("li",[a("p",[a("a",{attrs:{href:"#appendix-faq-what-dependencies"}},[e._v("How do I know which dependencies to add to my application to work with Spring Security?")])])]),e._v(" "),a("li",[a("p",[a("a",{attrs:{href:"#appendix-faq-apacheds-deps"}},[e._v("What dependencies are needed to run an embedded ApacheDS LDAP server?")])])]),e._v(" "),a("li",[a("p",[a("a",{attrs:{href:"#appendix-faq-what-is-userdetailservice"}},[e._v("What is a UserDetailsService and do I need one?")])])])]),e._v(" "),a("h3",{attrs:{id:"how-do-i-know-which-package-class-x-is-in"}},[a("a",{staticClass:"header-anchor",attrs:{href:"#how-do-i-know-which-package-class-x-is-in"}},[e._v("#")]),e._v(" How do I know which package class X is in?")]),e._v(" "),a("p",[e._v("The best way of locating classes is by installing the Spring Security source in your IDE. The distribution includes source jars for each of the modules the project is divided up into.\nAdd these to your project source path and you can navigate directly to Spring Security classes ("),a("code",[e._v("Ctrl-Shift-T")]),e._v(" in Eclipse). This also makes debugging easier and allows you to troubleshoot exceptions by looking directly at the code where they occur to see what’s going on there.")]),e._v(" "),a("h3",{attrs:{id:"how-do-the-namespace-elements-map-to-conventional-bean-configurations"}},[a("a",{staticClass:"header-anchor",attrs:{href:"#how-do-the-namespace-elements-map-to-conventional-bean-configurations"}},[e._v("#")]),e._v(" How do the namespace elements map to conventional bean configurations?")]),e._v(" "),a("p",[e._v('There is a general overview of what beans are created by the namespace in the namespace appendix of the reference guide.\nThere is also a detailed blog article called "Behind the Spring Security Namespace" on '),a("a",{attrs:{href:"https://spring.io/blog/2010/03/06/behind-the-spring-security-namespace/",target:"_blank",rel:"noopener noreferrer"}},[e._v("blog.springsource.com"),a("OutboundLink")],1),e._v(". If want to know the full details then the code is in the "),a("code",[e._v("spring-security-config")]),e._v(" module within the Spring Security 3.0 distribution.\nYou should probably read the chapters on namespace parsing in the standard Spring Framework reference documentation first.")]),e._v(" "),a("h3",{attrs:{id:"what-does-role-mean-and-why-do-i-need-it-on-my-role-names"}},[a("a",{staticClass:"header-anchor",attrs:{href:"#what-does-role-mean-and-why-do-i-need-it-on-my-role-names"}},[e._v("#")]),e._v(' What does "ROLE_" mean and why do I need it on my role names?')]),e._v(" "),a("p",[e._v("Spring Security has a voter-based architecture which means that an access decision is made by a series of "),a("code",[e._v("AccessDecisionVoter")]),e._v('s.\nThe voters act on the "configuration attributes" which are specified for a secured resource (such as a method invocation). With this approach, not all attributes may be relevant to all voters and a voter needs to know when it should ignore an attribute (abstain) and when it should vote to grant or deny access based on the attribute value.\nThe most common voter is the '),a("code",[e._v("RoleVoter")]),e._v(' which by default votes whenever it finds an attribute with the "ROLE_" prefix.\nIt makes a simple comparison of the attribute (such as "ROLE_USER") with the names of the authorities which the current user has been assigned.\nIf it finds a match (they have an authority called "ROLE_USER"), it votes to grant access, otherwise it votes to deny access.')]),e._v(" "),a("p",[e._v("The prefix can be changed by setting the "),a("code",[e._v("rolePrefix")]),e._v(" property of "),a("code",[e._v("RoleVoter")]),e._v(". If you only need to use roles in your application and have no need for other custom voters, then you can set the prefix to a blank string, in which case the "),a("code",[e._v("RoleVoter")]),e._v(" will treat all attributes as roles.")]),e._v(" "),a("h3",{attrs:{id:"how-do-i-know-which-dependencies-to-add-to-my-application-to-work-with-spring-security"}},[a("a",{staticClass:"header-anchor",attrs:{href:"#how-do-i-know-which-dependencies-to-add-to-my-application-to-work-with-spring-security"}},[e._v("#")]),e._v(" How do I know which dependencies to add to my application to work with Spring Security?")]),e._v(" "),a("p",[e._v("It will depend on what features you are using and what type of application you are developing.\nWith Spring Security 3.0, the project jars are divided into clearly distinct areas of functionality, so it is straightforward to work out which Spring Security jars you need from your application requirements.\nAll applications will need the "),a("code",[e._v("spring-security-core")]),e._v(" jar.\nIf you’re developing a web application, you need the "),a("code",[e._v("spring-security-web")]),e._v(" jar.\nIf you’re using security namespace configuration you need the "),a("code",[e._v("spring-security-config")]),e._v(" jar, for LDAP support you need the "),a("code",[e._v("spring-security-ldap")]),e._v(" jar and so on.")]),e._v(" "),a("p",[e._v("For third-party jars the situation isn’t always quite so obvious.\nA good starting point is to copy those from one of the pre-built sample applications WEB-INF/lib directories.\nFor a basic application, you can start with the tutorial sample.\nIf you want to use LDAP, with an embedded test server, then use the LDAP sample as a starting point.\nThe reference manual also includes "),a("a",{attrs:{href:"https://docs.spring.io/spring-security/site/docs/5.6.2/reference/html5/#modules",target:"_blank",rel:"noopener noreferrer"}},[e._v("an appendix"),a("OutboundLink")],1),e._v(" listing the first-level dependencies for each Spring Security module with some information on whether they are optional and what they are required for.")]),e._v(" "),a("p",[e._v('If you are building your project with maven, then adding the appropriate Spring Security modules as dependencies to your pom.xml will automatically pull in the core jars that the framework requires.\nAny which are marked as "optional" in the Spring Security POM files will have to be added to your own pom.xml file if you need them.')]),e._v(" "),a("h3",{attrs:{id:"what-dependencies-are-needed-to-run-an-embedded-apacheds-ldap-server"}},[a("a",{staticClass:"header-anchor",attrs:{href:"#what-dependencies-are-needed-to-run-an-embedded-apacheds-ldap-server"}},[e._v("#")]),e._v(" What dependencies are needed to run an embedded ApacheDS LDAP server?")]),e._v(" "),a("p",[e._v("If you are using Maven, you need to add the following to your pom dependencies:")]),e._v(" "),a("div",{staticClass:"language- extra-class"},[a("pre",{pre:!0,attrs:{class:"language-text"}},[a("code",[e._v("\n\t\torg.apache.directory.server\n\t\tapacheds-core\n\t\t1.5.5\n\t\truntime\n\n\n\t\torg.apache.directory.server\n\t\tapacheds-server-jndi\n\t\t1.5.5\n\t\truntime\n\n")])])]),a("p",[e._v("The other required jars should be pulled in transitively.")]),e._v(" "),a("h3",{attrs:{id:"what-is-a-userdetailsservice-and-do-i-need-one"}},[a("a",{staticClass:"header-anchor",attrs:{href:"#what-is-a-userdetailsservice-and-do-i-need-one"}},[e._v("#")]),e._v(" What is a UserDetailsService and do I need one?")]),e._v(" "),a("p",[a("code",[e._v("UserDetailsService")]),e._v(" is a DAO interface for loading data that is specific to a user account.\nIt has no other function other to load that data for use by other components within the framework.\nIt is not responsible for authenticating the user.\nAuthenticating a user with a username/password combination is most commonly performed by the "),a("code",[e._v("DaoAuthenticationProvider")]),e._v(", which is injected with a "),a("code",[e._v("UserDetailsService")]),e._v(" to allow it to load the password (and other data) for a user in order to compare it with the submitted value.\nNote that if you are using LDAP, "),a("a",{attrs:{href:"#appendix-faq-ldap-authentication"}},[e._v("this approach may not work")]),e._v(".")]),e._v(" "),a("p",[e._v("If you want to customize the authentication process then you should implement "),a("code",[e._v("AuthenticationProvider")]),e._v(" yourself.\nSee this "),a("a",{attrs:{href:"https://spring.io/blog/2010/08/02/spring-security-in-google-app-engine/",target:"_blank",rel:"noopener noreferrer"}},[e._v(" blog article"),a("OutboundLink")],1),e._v(" for an example integrating Spring Security authentication with Google App Engine.")]),e._v(" "),a("h2",{attrs:{id:"common-howto-requests"}},[a("a",{staticClass:"header-anchor",attrs:{href:"#common-howto-requests"}},[e._v("#")]),e._v(' Common "Howto" Requests')]),e._v(" "),a("ol",[a("li",[a("p",[a("a",{attrs:{href:"#appendix-faq-extra-login-fields"}},[e._v("I need to login in with more information than just the username.")])])]),e._v(" "),a("li",[a("p",[a("a",{attrs:{href:"#appendix-faq-matching-url-fragments"}},[e._v("How do I apply different intercept-url constraints where only the fragment value of the requested URLs differs (e.g./foo#bar and /foo#blah?")])])]),e._v(" "),a("li",[a("p",[a("a",{attrs:{href:"#appendix-faq-request-details-in-user-service"}},[e._v("How do I access the user’s IP Address (or other web-request data) in a UserDetailsService?")])])]),e._v(" "),a("li",[a("p",[a("a",{attrs:{href:"#appendix-faq-access-session-from-user-service"}},[e._v("How do I access the HttpSession from a UserDetailsService?")])])]),e._v(" "),a("li",[a("p",[a("a",{attrs:{href:"#appendix-faq-password-in-user-service"}},[e._v("How do I access the user’s password in a UserDetailsService?")])])]),e._v(" "),a("li",[a("p",[a("a",{attrs:{href:"#appendix-faq-dynamic-url-metadata"}},[e._v("How do I define the secured URLs within an application dynamically?")])])]),e._v(" "),a("li",[a("p",[a("a",{attrs:{href:"#appendix-faq-ldap-authorities"}},[e._v("How do I authenticate against LDAP but load user roles from a database?")])])]),e._v(" "),a("li",[a("p",[a("a",{attrs:{href:"#appendix-faq-namespace-post-processor"}},[e._v("I want to modify the property of a bean that is created by the namespace, but there is nothing in the schema to support it.")])])])]),e._v(" "),a("h3",{attrs:{id:"i-need-to-login-in-with-more-information-than-just-the-username"}},[a("a",{staticClass:"header-anchor",attrs:{href:"#i-need-to-login-in-with-more-information-than-just-the-username"}},[e._v("#")]),e._v(" I need to login in with more information than just the username.")]),e._v(" "),a("p",[e._v("How do I add support for extra login fields (e.g.\na company name)?")]),e._v(" "),a("p",[e._v("This question comes up repeatedly in the Spring Security forum so you will find more information there by searching the archives (or through google).")]),e._v(" "),a("p",[e._v("The submitted login information is processed by an instance of "),a("code",[e._v("UsernamePasswordAuthenticationFilter")]),e._v(". You will need to customize this class to handle the extra data field(s). One option is to use your own customized authentication token class (rather than the standard "),a("code",[e._v("UsernamePasswordAuthenticationToken")]),e._v('), another is simply to concatenate the extra fields with the username (for example, using a ":" as the separator) and pass them in the username property of '),a("code",[e._v("UsernamePasswordAuthenticationToken")]),e._v(".")]),e._v(" "),a("p",[e._v("You will also need to customize the actual authentication process.\nIf you are using a custom authentication token class, for example, you will have to write an "),a("code",[e._v("AuthenticationProvider")]),e._v(" to handle it (or extend the standard "),a("code",[e._v("DaoAuthenticationProvider")]),e._v("). If you have concatenated the fields, you can implement your own "),a("code",[e._v("UserDetailsService")]),e._v(" which splits them up and loads the appropriate user data for authentication.")]),e._v(" "),a("h3",{attrs:{id:"how-do-i-apply-different-intercept-url-constraints-where-only-the-fragment-value-of-the-requested-urls-differs-e-g-foo-bar-and-foo-blah"}},[a("a",{staticClass:"header-anchor",attrs:{href:"#how-do-i-apply-different-intercept-url-constraints-where-only-the-fragment-value-of-the-requested-urls-differs-e-g-foo-bar-and-foo-blah"}},[e._v("#")]),e._v(" How do I apply different intercept-url constraints where only the fragment value of the requested URLs differs (e.g./foo#bar and /foo#blah?")]),e._v(" "),a("p",[e._v("You can’t do this, since the fragment is not transmitted from the browser to the server.\nThe URLs above are identical from the server’s perspective.\nThis is a common question from GWT users.")]),e._v(" "),a("h3",{attrs:{id:"in-a-userdetailsservice"}},[a("a",{staticClass:"header-anchor",attrs:{href:"#in-a-userdetailsservice"}},[e._v("#")]),e._v(" in a UserDetailsService?")]),e._v(" "),a("p",[e._v("Obviously you can’t (without resorting to something like thread-local variables) since the only information supplied to the interface is the username.\nInstead of implementing "),a("code",[e._v("UserDetailsService")]),e._v(", you should implement "),a("code",[e._v("AuthenticationProvider")]),e._v(" directly and extract the information from the supplied "),a("code",[e._v("Authentication")]),e._v(" token.")]),e._v(" "),a("p",[e._v("In a standard web setup, the "),a("code",[e._v("getDetails()")]),e._v(" method on the "),a("code",[e._v("Authentication")]),e._v(" object will return an instance of "),a("code",[e._v("WebAuthenticationDetails")]),e._v(". If you need additional information, you can inject a custom "),a("code",[e._v("AuthenticationDetailsSource")]),e._v(" into the authentication filter you are using.\nIf you are using the namespace, for example with the "),a("code",[e._v("")]),e._v(" element, then you should remove this element and replace it with a "),a("code",[e._v("")]),e._v(" declaration pointing to an explicitly configured "),a("code",[e._v("UsernamePasswordAuthenticationFilter")]),e._v(".")]),e._v(" "),a("h3",{attrs:{id:"how-do-i-access-the-httpsession-from-a-userdetailsservice"}},[a("a",{staticClass:"header-anchor",attrs:{href:"#how-do-i-access-the-httpsession-from-a-userdetailsservice"}},[e._v("#")]),e._v(" How do I access the HttpSession from a UserDetailsService?")]),e._v(" "),a("p",[e._v("You can’t, since the "),a("code",[e._v("UserDetailsService")]),e._v(" has no awareness of the servlet API. If you want to store custom user data, then you should customize the "),a("code",[e._v("UserDetails")]),e._v(" object which is returned.\nThis can then be accessed at any point, via the thread-local "),a("code",[e._v("SecurityContextHolder")]),e._v(". A call to "),a("code",[e._v("SecurityContextHolder.getContext().getAuthentication().getPrincipal()")]),e._v(" will return this custom object.")]),e._v(" "),a("p",[e._v("If you really need to access the session, then it must be done by customizing the web tier.")]),e._v(" "),a("h3",{attrs:{id:"how-do-i-access-the-user-s-password-in-a-userdetailsservice"}},[a("a",{staticClass:"header-anchor",attrs:{href:"#how-do-i-access-the-user-s-password-in-a-userdetailsservice"}},[e._v("#")]),e._v(" How do I access the user’s password in a UserDetailsService?")]),e._v(" "),a("p",[e._v('You can’t (and shouldn’t). You are probably misunderstanding its purpose.\nSee "'),a("a",{attrs:{href:"#appendix-faq-what-is-userdetailservice"}},[e._v("What is a UserDetailsService?")]),e._v('" above.')]),e._v(" "),a("h3",{attrs:{id:"how-do-i-define-the-secured-urls-within-an-application-dynamically"}},[a("a",{staticClass:"header-anchor",attrs:{href:"#how-do-i-define-the-secured-urls-within-an-application-dynamically"}},[e._v("#")]),e._v(" How do I define the secured URLs within an application dynamically?")]),e._v(" "),a("p",[e._v("People often ask about how to store the mapping between secured URLs and security metadata attributes in a database, rather than in the application context.")]),e._v(" "),a("p",[e._v("The first thing you should ask yourself is if you really need to do this.\nIf an application requires securing, then it also requires that the security be tested thoroughly based on a defined policy.\nIt may require auditing and acceptance testing before being rolled out into a production environment.\nA security-conscious organization should be aware that the benefits of their diligent testing process could be wiped out instantly by allowing the security settings to be modified at runtime by changing a row or two in a configuration database.\nIf you have taken this into account (perhaps using multiple layers of security within your application) then Spring Security allows you to fully customize the source of security metadata.\nYou can make it fully dynamic if you choose.")]),e._v(" "),a("p",[e._v("Both method and web security are protected by subclasses of "),a("code",[e._v("AbstractSecurityInterceptor")]),e._v(" which is configured with a "),a("code",[e._v("SecurityMetadataSource")]),e._v(" from which it obtains the metadata for a particular method or filter invocation.\nFor web security, the interceptor class is "),a("code",[e._v("FilterSecurityInterceptor")]),e._v(" and it uses the marker interface "),a("code",[e._v("FilterInvocationSecurityMetadataSource")]),e._v('. The "secured object" type it operates on is a '),a("code",[e._v("FilterInvocation")]),e._v(". The default implementation which is used (both in the namespace "),a("code",[e._v("")]),e._v(' and when configuring the interceptor explicitly, stores the list of URL patterns and their corresponding list of "configuration attributes" (instances of '),a("code",[e._v("ConfigAttribute")]),e._v(") in an in-memory map.")]),e._v(" "),a("p",[e._v("To load the data from an alternative source, you must be using an explicitly declared security filter chain (typically Spring Security’s "),a("code",[e._v("FilterChainProxy")]),e._v(") in order to customize the "),a("code",[e._v("FilterSecurityInterceptor")]),e._v(" bean.\nYou can’t use the namespace.\nYou would then implement "),a("code",[e._v("FilterInvocationSecurityMetadataSource")]),e._v(" to load the data as you please for a particular "),a("code",[e._v("FilterInvocation")]),e._v(" "),a("sup",{staticClass:"footnote"},[e._v("["),a("a",{staticClass:"footnote",attrs:{id:"_footnoteref_1",href:"#_footnotedef_1",title:"View footnote."}},[e._v("1")]),e._v("]")]),e._v(". A very basic outline would look something like this:")]),e._v(" "),a("p",[e._v("Java")]),e._v(" "),a("div",{staticClass:"language- extra-class"},[a("pre",{pre:!0,attrs:{class:"language-text"}},[a("code",[e._v("\tpublic class MyFilterSecurityMetadataSource implements FilterInvocationSecurityMetadataSource {\n\n\t\tpublic List getAttributes(Object object) {\n\t\t\tFilterInvocation fi = (FilterInvocation) object;\n\t\t\t\tString url = fi.getRequestUrl();\n\t\t\t\tString httpMethod = fi.getRequest().getMethod();\n\t\t\t\tList attributes = new ArrayList();\n\n\t\t\t\t// Lookup your database (or other source) using this information and populate the\n\t\t\t\t// list of attributes\n\n\t\t\t\treturn attributes;\n\t\t}\n\n\t\tpublic Collection getAllConfigAttributes() {\n\t\t\treturn null;\n\t\t}\n\n\t\tpublic boolean supports(Class clazz) {\n\t\t\treturn FilterInvocation.class.isAssignableFrom(clazz);\n\t\t}\n\t}\n")])])]),a("p",[e._v("Kotlin")]),e._v(" "),a("div",{staticClass:"language- extra-class"},[a("pre",{pre:!0,attrs:{class:"language-text"}},[a("code",[e._v("class MyFilterSecurityMetadataSource : FilterInvocationSecurityMetadataSource {\n override fun getAttributes(securedObject: Any): List {\n val fi = securedObject as FilterInvocation\n val url = fi.requestUrl\n val httpMethod = fi.request.method\n\n // Lookup your database (or other source) using this information and populate the\n // list of attributes\n return ArrayList()\n }\n\n override fun getAllConfigAttributes(): Collection? {\n return null\n }\n\n override fun supports(clazz: Class<*>): Boolean {\n return FilterInvocation::class.java.isAssignableFrom(clazz)\n }\n}\n")])])]),a("p",[e._v("For more information, look at the code for "),a("code",[e._v("DefaultFilterInvocationSecurityMetadataSource")]),e._v(".")]),e._v(" "),a("h3",{attrs:{id:"how-do-i-authenticate-against-ldap-but-load-user-roles-from-a-database"}},[a("a",{staticClass:"header-anchor",attrs:{href:"#how-do-i-authenticate-against-ldap-but-load-user-roles-from-a-database"}},[e._v("#")]),e._v(" How do I authenticate against LDAP but load user roles from a database?")]),e._v(" "),a("p",[e._v("The "),a("code",[e._v("LdapAuthenticationProvider")]),e._v(" bean (which handles normal LDAP authentication in Spring Security) is configured with two separate strategy interfaces, one which performs the authentication and one which loads the user authorities, called "),a("code",[e._v("LdapAuthenticator")]),e._v(" and "),a("code",[e._v("LdapAuthoritiesPopulator")]),e._v(" respectively.\nThe "),a("code",[e._v("DefaultLdapAuthoritiesPopulator")]),e._v(" loads the user authorities from the LDAP directory and has various configuration parameters to allow you to specify how these should be retrieved.")]),e._v(" "),a("p",[e._v("To use JDBC instead, you can implement the interface yourself, using whatever SQL is appropriate for your schema:")]),e._v(" "),a("p",[e._v("Java")]),e._v(" "),a("div",{staticClass:"language- extra-class"},[a("pre",{pre:!0,attrs:{class:"language-text"}},[a("code",[e._v('\tpublic class MyAuthoritiesPopulator implements LdapAuthoritiesPopulator {\n\t\t@Autowired\n\t\tJdbcTemplate template;\n\n\t\tList getGrantedAuthorities(DirContextOperations userData, String username) {\n\t\t\treturn template.query("select role from roles where username = ?",\n\t\t\t\t\tnew String[] {username},\n\t\t\t\t\tnew RowMapper() {\n\t\t\t\t /**\n\t\t\t\t * We\'re assuming here that you\'re using the standard convention of using the role\n\t\t\t\t * prefix "ROLE_" to mark attributes which are supported by Spring Security\'s RoleVoter.\n\t\t\t\t */\n\t\t\t\t@Override\n\t\t\t\tpublic GrantedAuthority mapRow(ResultSet rs, int rowNum) throws SQLException {\n\t\t\t\t\treturn new SimpleGrantedAuthority("ROLE_" + rs.getString(1));\n\t\t\t\t}\n\t\t\t});\n\t\t}\n\t}\n')])])]),a("p",[e._v("Kotlin")]),e._v(" "),a("div",{staticClass:"language- extra-class"},[a("pre",{pre:!0,attrs:{class:"language-text"}},[a("code",[e._v('class MyAuthoritiesPopulator : LdapAuthoritiesPopulator {\n @Autowired\n lateinit var template: JdbcTemplate\n\n override fun getGrantedAuthorities(userData: DirContextOperations, username: String): MutableList {\n return template.query("select role from roles where username = ?",\n arrayOf(username)\n ) { rs, _ ->\n /**\n * We\'re assuming here that you\'re using the standard convention of using the role\n * prefix "ROLE_" to mark attributes which are supported by Spring Security\'s RoleVoter.\n */\n SimpleGrantedAuthority("ROLE_" + rs.getString(1))\n }\n }\n}\n')])])]),a("p",[e._v("You would then add a bean of this type to your application context and inject it into the "),a("code",[e._v("LdapAuthenticationProvider")]),e._v(". This is covered in the section on configuring LDAP using explicit Spring beans in the LDAP chapter of the reference manual.\nNote that you can’t use the namespace for configuration in this case.\nYou should also consult the Javadoc for the relevant classes and interfaces.")]),e._v(" "),a("h3",{attrs:{id:"i-want-to-modify-the-property-of-a-bean-that-is-created-by-the-namespace-but-there-is-nothing-in-the-schema-to-support-it"}},[a("a",{staticClass:"header-anchor",attrs:{href:"#i-want-to-modify-the-property-of-a-bean-that-is-created-by-the-namespace-but-there-is-nothing-in-the-schema-to-support-it"}},[e._v("#")]),e._v(" I want to modify the property of a bean that is created by the namespace, but there is nothing in the schema to support it.")]),e._v(" "),a("p",[e._v("What can I do short of abandoning namespace use?")]),e._v(" "),a("p",[e._v("The namespace functionality is intentionally limited, so it doesn’t cover everything that you can do with plain beans.\nIf you want to do something simple, like modify a bean, or inject a different dependency, you can do this by adding a "),a("code",[e._v("BeanPostProcessor")]),e._v(" to your configuration.\nMore information can be found in the "),a("a",{attrs:{href:"https://docs.spring.io/spring/docs/3.0.x/spring-framework-reference/htmlsingle/spring-framework-reference.html#beans-factory-extension-bpp",target:"_blank",rel:"noopener noreferrer"}},[e._v("Spring Reference Manual"),a("OutboundLink")],1),e._v(". In order to do this, you need to know a bit about which beans are created, so you should also read the blog article in the above question on "),a("a",{attrs:{href:"#appendix-faq-namespace-to-bean-mapping"}},[e._v("how the namespace maps to Spring beans")]),e._v(".")]),e._v(" "),a("p",[e._v("Normally, you would add the functionality you require to the "),a("code",[e._v("postProcessBeforeInitialization")]),e._v(" method of "),a("code",[e._v("BeanPostProcessor")]),e._v(". Let’s say that you want to customize the "),a("code",[e._v("AuthenticationDetailsSource")]),e._v(" used by the "),a("code",[e._v("UsernamePasswordAuthenticationFilter")]),e._v(", (created by the "),a("code",[e._v("form-login")]),e._v(" element). You want to extract a particular header called "),a("code",[e._v("CUSTOM_HEADER")]),e._v(" from the request and make use of it while authenticating the user.\nThe processor class would look like this:")]),e._v(" "),a("p",[e._v("Java")]),e._v(" "),a("div",{staticClass:"language- extra-class"},[a("pre",{pre:!0,attrs:{class:"language-text"}},[a("code",[e._v('public class CustomBeanPostProcessor implements BeanPostProcessor {\n\n\t\tpublic Object postProcessAfterInitialization(Object bean, String name) {\n\t\t\t\tif (bean instanceof UsernamePasswordAuthenticationFilter) {\n\t\t\t\t\t\tSystem.out.println("********* Post-processing " + name);\n\t\t\t\t\t\t((UsernamePasswordAuthenticationFilter)bean).setAuthenticationDetailsSource(\n\t\t\t\t\t\t\t\t\t\tnew AuthenticationDetailsSource() {\n\t\t\t\t\t\t\t\t\t\t\t\tpublic Object buildDetails(Object context) {\n\t\t\t\t\t\t\t\t\t\t\t\t\t\treturn ((HttpServletRequest)context).getHeader("CUSTOM_HEADER");\n\t\t\t\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t\t\t});\n\t\t\t\t}\n\t\t\t\treturn bean;\n\t\t}\n\n\t\tpublic Object postProcessBeforeInitialization(Object bean, String name) {\n\t\t\t\treturn bean;\n\t\t}\n}\n')])])]),a("p",[e._v("Kotlin")]),e._v(" "),a("div",{staticClass:"language- extra-class"},[a("pre",{pre:!0,attrs:{class:"language-text"}},[a("code",[e._v('class CustomBeanPostProcessor : BeanPostProcessor {\n override fun postProcessAfterInitialization(bean: Any, name: String): Any {\n if (bean is UsernamePasswordAuthenticationFilter) {\n println("********* Post-processing $name")\n bean.setAuthenticationDetailsSource(\n AuthenticationDetailsSource { context -> context.getHeader("CUSTOM_HEADER") })\n }\n return bean\n }\n\n override fun postProcessBeforeInitialization(bean: Any, name: String?): Any {\n return bean\n }\n}\n')])])]),a("p",[e._v("You would then register this bean in your application context.\nSpring will automatically invoke it on the beans defined in the application context.")]),e._v(" "),a("hr"),e._v(" "),a("p",[a("a",{attrs:{href:"#_footnoteref_1"}},[e._v("1")]),e._v(". The "),a("code",[e._v("FilterInvocation")]),e._v(" object contains the "),a("code",[e._v("HttpServletRequest")]),e._v(", so you can obtain the URL or any other relevant information on which to base your decision on what the list of returned attributes will contain.")]),e._v(" "),a("p",[a("RouterLink",{attrs:{to:"/en/spring-security/namespace/websocket.html"}},[e._v("WebSocket Security")]),a("RouterLink",{attrs:{to:"/reactive/index.html"}},[e._v("Reactive Applications")])],1)])}),[],!1,null,null,null);t.default=i.exports}}]);