[[appendix-faq]]
= Spring Security FAQ

This FAQ has the following sections:

* <<appendix-faq-general-questions>>
* <<appendix-faq-common-problems>>
* <<appendix-faq-architecture>>
* <<appendix-faq-howto>>

[[appendix-faq-general-questions]]
== General Questions

This FAQ answers the following general questions:

* <<appendix-faq-other-concerns>>
* <<appendix-faq-web-xml>>
* <<appendix-faq-requirements>>
* <<appendix-faq-start-simple>>


[[appendix-faq-other-concerns]]
=== Can Spring Security take care of all my application security requirements?

Spring Security provides you with a flexible framework for your authentication and authorization requirements, but there are many other considerations for building a secure application that are outside its scope.
Web applications are vulnerable to all kinds of attacks with which you should be familiar, preferably before you start development so that you can design and code with them in mind from the beginning.
Check out the https://www.owasp.org/[OWASP website] for information on the major issues that face web application developers and the countermeasures you can use against them.


[[appendix-faq-web-xml]]
=== Why Not Use web.xml Security?

Suppose you are developing an enterprise application based on Spring.
You typically need to address four security concerns : authentication, web request security, service layer security (your methods that implement business logic), and domain object instance security (different domain objects can have different permissions). With these typical requirements in mind, we have the following considerations:

* _Authentication_: The servlet specification provides an approach to authentication.
However, you need to configure the container to perform authentication, which typically requires editing of container-specific "`realm`" settings.
This makes a non-portable configuration. Also, if you need to write an actual Java class to implement the container's authentication interface, it becomes even more non-portable.
With Spring Security, you achieve complete portability -- right down to the WAR level.
Also, Spring Security offers a choice of production-proven authentication providers and mechanisms, meaning you can switch your authentication approaches at deployment time.
This is particularly valuable for software vendors writing products that need to work in an unknown target environment.

* _Web request security:_ The servlet specification provides an approach to secure your request URIs.
However, these URIs can be expressed only in the servlet specification's own limited URI path format.
Spring Security provides a far more comprehensive approach.
For instance, you can use Ant paths or regular expressions, you can consider parts of the URI other than simply the requested page (for example,
you can consider HTTP GET parameters), and you can implement your own runtime source of configuration data.
This means that you can dynamically change your web request security during the actual execution of your web application.

* _Service layer and domain object security:_ The absence of support in the servlet specification for services layer security or domain object instance security represents serious limitations for multi-tiered applications.
Typically, 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:

** _Separation of concerns:_ Authorization is a crosscutting concern and should be implemented as such.
MVC controllers or views that implement authorization code makes it more difficult to test both the controller and the authorization logic, is more difficult to debug, and often leads to code duplication.

** _Support for rich clients and web services:_ If an additional client type must ultimately be supported, any authorization code embedded within the web layer is non-reusable.
It should be considered that Spring remoting exporters export only service layer beans (not MVC controllers). As a result, authorization logic needs to be located in the services layer to support a multitude of client types.

** _Layering issues:_ An MVC controller or view is the incorrect architectural layer in which to implement authorization decisions concerning services layer methods or domain object instances.
While 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.
A 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 use a dedicated security framework.

** _Authorization code quality:_ 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.
Writing your own authorization code from scratch does not provide the "`design check`" a framework would offer, and in-house authorization code typically lacks the improvements that emerge from widespread deployment, peer review, and new versions.

For simple applications, servlet specification security may be enough.
Although 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.


[[appendix-faq-requirements]]
=== What Java and Spring Framework versions are required?

Spring Security 3.0 and 3.1 require at least JDK 1.5 and also require Spring 3.0.3 as a minimum.
Ideally, you should use the latest release versions to avoid problems.

Spring Security 2.0.x requires a minimum JDK version of 1.4 and is built against Spring 2.0.x.
It should also be compatible with applications that use Spring 2.5.x.


[[appendix-faq-start-simple]]
==== I have a complex scenario. What could be wrong?

(This answer address complex scenarios in general by dealing with a particular scenario.)

Suppose you are new to Spring Security and 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). You have copied some configuration files but have found that it does not work. What could be wrong?

You need an understanding of the technologies you intend to use before you can successfully build applications with them.
Security is complicated.
Setting up a simple configuration by using a login form and some hard-coded users with Spring Security's namespace is reasonably straightforward.
Moving to using a backed JDBC database is also easy enough.
However, if you try to jump straight to a complicated deployment scenario like this scenario, you are almost certain to be frustrated.
There is a big jump in the learning curve required to set up systems such as CAS, configure LDAP servers, and install SSL certificates properly.
So you need to take things one step at a time.

From a Spring Security perspective, the first thing you should do is follow the "`Getting Started`" guide on the website.
This will take you through a series of steps to get up and running and get some idea of how the framework operates.
If you use other technologies with which you are not familiar, you should do some research and try to make sure you can use them in isolation before combining them in a complex system.

[[appendix-faq-common-problems]]
== Common Problems

This section addresses the most common problems that people encounter when using Spring Security:

* Authentication
** <<appendix-faq-bad-credentials>>
** <<appendix-faq-login-loop>>
** <<appendix-faq-anon-access-denied>>
** <<appendix-faq-cached-secure-page>>
** <<auth-exception-credentials-not-found>>
** <<appendix-faq-ldap-authentication>>
* Session Management
** <<appendix-faq-concurrent-session-same-browser>>
** <<appendix-faq-new-session-on-authentication>>
** <<appendix-faq-tomcat-https-session>>
** <<appendix-faq-session-listener-missing>>
** <<appendix-faq-unwanted-session-creation>>
* Miscellaneous
** <<appendix-faq-forbidden-csrf>>
** <<appendix-faq-no-security-on-forward>>
** <<appendix-faq-method-security-in-web-context>>
** <<appendix-faq-no-filters-no-context>>
** <<appendix-faq-method-security-with-taglib>>

[[appendix-faq-bad-credentials]]
=== When I try to log in, I get an error message that says, "`Bad Credentials`". What is wrong?

This means that authentication has failed.
It does not say why, as it is good practice to avoid giving details that might help an attacker guess account names or passwords.

This also means that, if you ask this question online, you should not expect an answer unless you provide additional information.
As with any issue, you should check the output from the debug log and note any exception stacktraces and related messages.
You should step through the code in a debugger to see where the authentication fails and why.
You should also write a test case which exercises your authentication configuration outside the application.
If you use hashed passwords, make sure the value stored in your database is _exactly_ the same as the value produced by the `PasswordEncoder` configured in your application.


[[appendix-faq-login-loop]]
=== My application goes into an "`endless loop`" when I try to log in. What is going on?

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.
Make sure your configuration allows anonymous access to the login page.
You can do so with the xref:servlet/authorization/authorize-http-requests.adoc[`authorizeHttpRequests`] DSL.

[TIP]
====
When you use namespace- or DSL-based configuration, a check is made on loading the application context and a warning message logged if your login page appears to be protected.
====

[[appendix-faq-anon-access-denied]]
=== I get an exception with the message "Access is denied (user is anonymous);". What's wrong?

This is a debug level message which occurs the first time an anonymous user attempts to access a protected resource.

[source]
----
DEBUG [ExceptionTranslationFilter] - Access is denied (user is anonymous); redirecting to authentication entry point
org.springframework.security.AccessDeniedException: Access is denied
at org.springframework.security.vote.AffirmativeBased.decide(AffirmativeBased.java:68)
at org.springframework.security.intercept.AbstractSecurityInterceptor.beforeInvocation(AbstractSecurityInterceptor.java:262)
----

It is normal and shouldn't be anything to worry about.


[[appendix-faq-cached-secure-page]]
=== Why can I still see a secured page even after I have logged out of my application?

The most common reason for this is that your browser has cached the page, and you are seeing a copy that is being retrieved from the browsers cache.
Verify this by checking whether the browser is actually sending the request (check your server access logs and 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 `Cache-Control` response headers.
Note that SSL requests are never cached.


[[auth-exception-credentials-not-found]]
=== I get an exception with a message of "An Authentication object was not found in the SecurityContext". What is wrong?

The following listing shows another debug-level message that occurs the first time an anonymous user attempts to access a protected resource. However, this listing shows what happens when you do not have an `AnonymousAuthenticationFilter` in your filter chain configuration:

[source]
----
DEBUG [ExceptionTranslationFilter] - Authentication exception occurred; redirecting to authentication entry point
org.springframework.security.AuthenticationCredentialsNotFoundException:
							An Authentication object was not found in the SecurityContext
at org.springframework.security.intercept.AbstractSecurityInterceptor.credentialsNotFound(AbstractSecurityInterceptor.java:342)
at org.springframework.security.intercept.AbstractSecurityInterceptor.beforeInvocation(AbstractSecurityInterceptor.java:254)
----

It is normal and is not something to worry about.


[[appendix-faq-ldap-authentication]]
=== I can't get LDAP authentication to work. What's wrong with my configuration?

Note that the permissions for an LDAP directory often do not let you read the password for a user.
Hence, it is often not possible to use the <<appendix-faq-what-is-userdetailservice>> where Spring Security compares the stored password with the one submitted by the user.
The most common approach is to use LDAP "`bind`", which is one of the operations supported by https://en.wikipedia.org/wiki/Lightweight_Directory_Access_Protocol[the LDAP protocol]. With this approach, Spring Security validates the password by trying to authenticate to the directory as the user.

The most common problem with LDAP authentication is a lack of knowledge of the directory server tree structure and configuration.
This differs from one company to another, so you have to find it out yourself.
Before adding a Spring Security LDAP configuration to an application, you should write a simple test by using standard Java LDAP code (without Spring Security involved) and make sure you can get that to work first.
For example, to authenticate a user, you could use the following code:

[tabs]
======
Java::
+
[source,java,role="primary"]
----

@Test
public void ldapAuthenticationIsSuccessful() throws Exception {
		Hashtable<String,String> env = new Hashtable<String,String>();
		env.put(Context.SECURITY_AUTHENTICATION, "simple");
		env.put(Context.SECURITY_PRINCIPAL, "cn=joe,ou=users,dc=mycompany,dc=com");
		env.put(Context.PROVIDER_URL, "ldap://mycompany.com:389/dc=mycompany,dc=com");
		env.put(Context.SECURITY_CREDENTIALS, "joespassword");
		env.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory");

		InitialLdapContext ctx = new InitialLdapContext(env, null);

}

----

Kotlin::
+
[source,kotlin,role="secondary"]
----
@Test
fun ldapAuthenticationIsSuccessful() {
    val env = Hashtable<String, String>()
    env[Context.SECURITY_AUTHENTICATION] = "simple"
    env[Context.SECURITY_PRINCIPAL] = "cn=joe,ou=users,dc=mycompany,dc=com"
    env[Context.PROVIDER_URL] = "ldap://mycompany.com:389/dc=mycompany,dc=com"
    env[Context.SECURITY_CREDENTIALS] = "joespassword"
    env[Context.INITIAL_CONTEXT_FACTORY] = "com.sun.jndi.ldap.LdapCtxFactory"
    val ctx = InitialLdapContext(env, null)
}
----
======

=== Session Management

Session management issues are a common source of questions.
If you are developing Java web applications, you should understand how the session is maintained between the servlet container and the user's browser.
You should also understand the difference between secure and non-secure cookies and the implications of using HTTP and HTTPS and switching between the two.
Spring Security has nothing to do with maintaining the session or providing session identifiers.
This is entirely handled by the servlet container.


[[appendix-faq-concurrent-session-same-browser]]
=== I am using Spring Security's concurrent session control to prevent users from logging in more than once at the same time. When I open another browser window after logging in, it does not stop me from logging in again. Why can I log in more than once?

Browsers generally maintain a single session per browser instance.
You cannot have two separate sessions at once.
So if you log in again in another window or tab you are just reauthenticating in the same session.
So, if you log in again in another window or tab, you are reauthenticating in the same session.
The server does not know anything about tabs, windows, or browser instances.
All it sees are HTTP requests, and it ties those to a particular session according to the value of the `JSESSIONID` cookie that they contain.
When a user authenticates during a session, Spring Security's concurrent session control checks the number of _other authenticated sessions_ that they have.
If they are already authenticated with the same session, re-authenticating has no effect.


[[appendix-faq-new-session-on-authentication]]
=== Why does the session ID change when I authenticate through Spring Security?

With the default configuration, Spring Security changes the session ID when the user authenticates.
If you use a Servlet 3.1 or newer container, the session ID is simply changed.
If you use an older container, Spring Security invalidates the existing session, creates a new session, and transfers the session data to the new session.
Changing the session identifier in this manner prevents "`session-fixation`" attacks.
You can find more about this online and in the reference manual.


[[appendix-faq-tomcat-https-session]]
=== I use Tomcat (or some other servlet container) and have enabled HTTPS for my login page, switching back to HTTP afterward. It does not work. I end up back at the login page after authenticating.
It doesn't work - I just end up back at the login page after authenticating.

This happens because sessions created under HTTPS, for which the session cookie is marked as "`secure`", cannot subsequently be used under HTTP. The browser does not send the cookie back to the server, and any session state (including the security context information) is lost. Starting a session in HTTP first should work, as the session cookie is not marked as secure.
However, Spring Security's https://docs.spring.io/spring-security/site/docs/3.1.x/reference/springsecurity-single.html#ns-session-fixation[Session Fixation Protection] 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.
To get around this, you can disable session fixation protection. However, in newer Servlet containers, you can also configure session cookies to never use the secure flag.


[IMPORTANT]
====
Switching between HTTP and HTTPS is not a good idea in general, as any application that uses HTTP at all is vulnerable to man-in-the-middle attacks.
To be truly secure, the user should begin accessing your site in HTTPS and continue using it until they log out.
Even clicking on an HTTPS link from a page accessed over HTTP is potentially risky.
If you need more convincing, check out a tool like https://github.com/moxie0/sslstrip/[sslstrip].
====


===  I am not switching between HTTP and HTTPS, but my session is still lost. What happened?

Sessions are maintained either by exchanging a session cookie or by adding a `jsessionid` parameter to URLs (this happens automatically if you use JSTL to output URLs or if you call `HttpServletResponse.encodeUrl` on URLs (before a redirect, for example). If clients have cookies disabled, and you are not rewriting URLs to include the `jsessionid`, the session is lost.
Note that the use of cookies is preferred for security reasons, as it does not expose the session information in the URL.

[[appendix-faq-session-listener-missing]]
===  I am trying to use the concurrent session-control support, but it does not let me log back in, even if I am sure I have logged out and have not exceeded the allowed sessions. What is wrong?

Make sure you have added the listener to your `web.xml` file.
It is essential to make sure that the Spring Security session registry is notified when a session is destroyed.
Without it, the session information is not removed from the registry.
The following example adds a listener in a `web.xml` file:

[source,xml]
----
<listener>
		<listener-class>org.springframework.security.web.session.HttpSessionEventPublisher</listener-class>
</listener>
----

[[appendix-faq-unwanted-session-creation]]
=== Spring Security creates a session somewhere, even though I have configured it not to, by setting the create-session attribute to never. What is wrong?

This usually means that the user's application is creating a session somewhere but that they are not aware of it.
The most common culprit is a JSP. Many people are not aware that JSPs create sessions by default.
To prevent a JSP from creating a session, add the `<%@ page session="false" %>` directive to the top of the page.

If you have 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 is to add a `javax.servlet.http.HttpSessionListener`, which calls `Thread.dumpStack()` in the `sessionCreated` method, to your application.

[[appendix-faq-forbidden-csrf]]
=== I get a 403 Forbidden when performing a POST. What is wrong?

If an HTTP 403 Forbidden error is returned for HTTP POST, but it works for HTTP GET, the issue is most likely related to https://docs.spring.io/spring-security/site/docs/3.2.x/reference/htmlsingle/#csrf[CSRF]. Either provide the CSRF Token or disable CSRF protection (the latter is not recommended).

[[appendix-faq-no-security-on-forward]]
=== I am forwarding a request to another URL by using the RequestDispatcher, but my security constraints are not being applied.

By default, filters are not applied to forwards or includes.
If you really want the security filters to be applied to forwards or includes, you have to configure these explicitly in your `web.xml` file by using the `<dispatcher>` element, which is a child element of the `<filter-mapping>` element.


[[appendix-faq-method-security-in-web-context]]
=== I have added Spring Security's <global-method-security> element to my application context, but, if I add security annotations to my Spring MVC controller beans (Struts actions etc.), they do not seem to have an effect. Why not?

In a Spring web application, the application context that holds the Spring MVC beans for the dispatcher servlet is often separate from the main application context.
It is often defined in a file called `myapp-servlet.xml`, where `myapp` is the name assigned to the Spring `DispatcherServlet` in the `web.xml` file. An application can have multiple `DispatcherServlet` instances, each with its own isolated application context.
The beans in these "`child`" contexts are not visible to the rest of the application.
The "`parent`" application context is loaded by the `ContextLoaderListener` you define in your `web.xml` file and is visible to all the child contexts.
This parent context is usually where you define your security configuration, including the `<global-method-security>` element. As a result, any security constraints applied to methods in these web beans are not enforced, since the beans cannot be seen from the `DispatcherServlet` context.
You need to either move the `<global-method-security>` declaration to the web context or move the beans you want secured into the main application context.

Generally, we recommend applying method security at the service layer rather than on individual web controllers.


[[appendix-faq-no-filters-no-context]]
=== I have a user who has definitely been authenticated, but, when I try to access the SecurityContextHolder during some requests, the Authentication is null. Why can I not see the user information?
Why can't I see the user information?

If you have excluded the request from the security filter chain by using the `filters='none'` attribute in the `<intercept-url>` element that matches the URL pattern, the `SecurityContextHolder` is not populated for that request.
Check the debug log to see whether the request is passing through the filter chain.
(You are reading the debug log, right?)

[[appendix-faq-method-security-with-taglib]]
=== The authorize JSP Tag does not respect my method security annotations when using the URL attribute. Why not?

Method security does not hide links when using the `url` attribute in `<sec:authorize>`, because we cannot readily reverse engineer what URL is mapped to what controller endpoint. We are limited because controllers can rely on headers, the current user, and other details to determine what method to invoke.

[[appendix-faq-architecture]]
== Spring Security Architecture Questions

This section addresses common Spring Security architecture questions:

. <<appendix-faq-where-is-class-x>>
. <<appendix-faq-namespace-to-bean-mapping>>
. <<appendix-faq-role-prefix>>
. <<appendix-faq-what-dependencies>>
. <<appendix-faq-unboundid-deps>>
. <<appendix-faq-what-is-userdetailservice>>


[[appendix-faq-where-is-class-x]]
=== How do I know which package class X is in?

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.
Add these to your project source path, and then you can navigate directly to Spring Security classes (`Ctrl-Shift-T` in Eclipse). This also makes debugging easier and lets you troubleshoot exceptions by looking directly at the code where they occur to see what is going on there.

[[appendix-faq-namespace-to-bean-mapping]]
=== How do the namespace elements map to conventional bean configurations?

There is a general overview of what beans are created by the namespace in the namespace appendix of the reference guide.
There is also a detailed blog article called "Behind the Spring Security Namespace" on https://spring.io/blog/2010/03/06/behind-the-spring-security-namespace/[blog.springsource.com]. If you want to know the full details, then the code is in the `spring-security-config` module within the Spring Security 3.0 distribution.
You should probably read the chapters on namespace parsing in the standard Spring Framework reference documentation first.


[[appendix-faq-role-prefix]]
=== What does "ROLE_" mean?

`ROLE_` is a way to identify the nature of a given authority.
An authority prefixed by `ROLE_` means that this authority is a role, likely derived from an RBAC authorization model.

Having a prefix allows for clear differentiation from OAuth 2.0 scopes (which use `SCOPE_`) and authorities granted from other sources as well.

You may choose to not prefix your authorities.
Modern Spring Security authorization components either allow you to supply the entire authority name, rendering the prefix unnecessary.
An example of this is how xref:servlet/authorization/authorize-http-requests.adoc[`authorizeHttpRequests`] and xref:servlet/authorization/method-security.adoc[`@PreAuthorize`] allow you to call `hasAuthority` or `hasRole`.

[[appendix-faq-what-dependencies]]
=== How do I know which dependencies to add to my application to work with Spring Security?

It depends on what features you are using and what type of application you are developing.
With 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.
All applications need the `spring-security-core` jar.
If you are developing a web application, you need the `spring-security-web` jar.
If you are using security namespace configuration, you need the `spring-security-config` jar. For LDAP support, you need the `spring-security-ldap` jar. And so on.

For third-party jars, the situation is not always quite so obvious.
A good starting point is to copy those from one of the pre-built sample applications `WEB-INF/lib` directories.
For a basic application, you can start with the tutorial sample.
For a basic application, you can start with the tutorial sample.
If you want to use LDAP with an embedded test server, use the LDAP sample as a starting point.
The reference manual also includes <<appendix-namespace,an appendix>> that lists the first-level dependencies for each Spring Security module, with some information on whether they are optional and when they are required.

If you build your project with Maven, adding the appropriate Spring Security modules as dependencies to your `pom.xml` file automatically pulls in the core jars that the framework requires.
Any that are marked as "`optional`" in the Spring Security `pom.xml` files have to be added to your own `pom.xml` file if you need them.

[[appendix-faq-unboundid-deps]]
=== What dependencies are needed to run an embedded UnboundID LDAP server?

You need to add the following dependency to your project:

[tabs]
======
Maven::
+
[source,maven,role="primary"]
----
<dependency>
		<groupId>com.unboundid</groupId>
		<artifactId>unboundid-ldapsdk</artifactId>
		<version>7.0.1</version>
		<scope>runtime</scope>
</dependency>
----

Gradle::
+
[source,gradle,role="secondary"]
----
implementation 'com.unboundid:unboundid-ldapsdk:7.0.1'
----
======


[[appendix-faq-apacheds-deps]]
=== What dependencies are needed to run an embedded ApacheDS LDAP server?

Spring Security 7 removes support for Apache DS.
Please use <<appendix-faq-unboundid-deps,UnboundID>> instead.

[[appendix-faq-what-is-userdetailservice]]
=== What is a UserDetailsService and do I need one?

`UserDetailsService` is a DAO interface for loading data that is specific to a user account.
It has no function other than to load that data for use by other components within the framework.
It is not responsible for authenticating the user.
Authenticating a user with a username and password combination is most commonly performed by the `DaoAuthenticationProvider`, which is injected with a `UserDetailsService` to let it load the password (and other data) for a user, to compare it with the submitted value.
Note that, if you use LDAP, <<appendix-faq-ldap-authentication,this approach may not work>>.

If you want to customize the authentication process, you should implement `AuthenticationProvider` yourself.
See this https://spring.io/blog/2010/08/02/spring-security-in-google-app-engine/[ blog article] for an example that integrate Spring Security authentication with Google App Engine.

[[appendix-faq-howto]]
== Common How-to Questions

This section addresses common how-to questions about Spring Security:

. <<appendix-faq-extra-login-fields>>
. <<appendix-faq-matching-url-fragments>>
. <<appendix-faq-request-details-in-user-service>>
. <<appendix-faq-access-session-from-user-service>>
. <<appendix-faq-password-in-user-service>>
. <<appendix-faq-dynamic-url-metadata>>
. <<appendix-faq-ldap-authorities>>
. <<appendix-faq-namespace-post-processor>>


[[appendix-faq-extra-login-fields]]
=== I need to log in with more information than just the username. How do I add support for extra login fields (such as a company name)?

This question comes up repeatedly, so you can find more information by searching online.

The submitted login information is processed by an instance of `UsernamePasswordAuthenticationFilter`. You need to customize this class to handle the extra data fields. One option is to use your own customized authentication token class (rather than the standard `UsernamePasswordAuthenticationToken`). Another option is to concatenate the extra fields with the username (for example, by using a `:` character as the separator) and pass them in the username property of `UsernamePasswordAuthenticationToken`.

You also need to customize the actual authentication process.
If you use a custom authentication token class, for example, you will have to write an `AuthenticationProvider` (or extend the standard `DaoAuthenticationProvider`) to handle it. If you have concatenated the fields, you can implement your own `UserDetailsService` to split them up and load the appropriate user data for authentication.

[[appendix-faq-matching-url-fragments]]
=== How do I apply different intercept-url constraints where only the fragment value of the requested URLs differs (such as /thing1#thing2 and /thing1#thing3)?

You cannot do this, since the fragment is not transmitted from the browser to the server.
From the server's perspective, the URLs are identical.
This is a common question from GWT users.

[[appendix-faq-request-details-in-user-service]]
=== How do I access the user's IP Address (or other web-request data) in a UserDetailsService?

You cannot (without resorting to something like thread-local variables), since the only information supplied to the interface is the username.
Instead of implementing `UserDetailsService`, you should implement `AuthenticationProvider` directly and extract the information from the supplied `Authentication` token.

In a standard web setup, the `getDetails()` method on the `Authentication` object will return an instance of `WebAuthenticationDetails`. If you need additional information, you can inject a custom `AuthenticationDetailsSource` into the authentication filter you are using.
If you are using the namespace, for example with the `<form-login>` element, then you should remove this element and replace it with a `<custom-filter>` declaration pointing to an explicitly configured `UsernamePasswordAuthenticationFilter`.


[[appendix-faq-access-session-from-user-service]]
=== How do I access the HttpSession from a UserDetailsService?

You cannot, since the `UserDetailsService` has no awareness of the servlet API. If you want to store custom user data, you should customize the `UserDetails` object that is returned.
This can then be accessed at any point, through the thread-local `SecurityContextHolder`. A call to `SecurityContextHolder.getContext().getAuthentication().getPrincipal()` returns this custom object.

If you really need to access the session, you must do so by customizing the web tier.


[[appendix-faq-password-in-user-service]]
=== How do I access the user's password in a UserDetailsService?

You cannot (and should not, even if you find a way to do so). You are probably misunderstanding its purpose.
See "<<appendix-faq-what-is-userdetailservice,What is a UserDetailsService?>>", earlier in the FAQ.


[[appendix-faq-dynamic-url-metadata]]
=== How do I dynamically define the secured URLs within an application?

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.

The first thing you should ask yourself is if you really need to do this.
If an application needs to be secure, it also requires that the security be tested thoroughly based on a defined policy.
It may require auditing and acceptance testing before being rolled out into a production environment.
A security-conscious organization should be aware that the benefits of their diligent testing process could be wiped out instantly by letting the security settings be modified at runtime by changing a row or two in a configuration database.
If you have taken this into account (perhaps by using multiple layers of security within your application), Spring Security lets you fully customize the source of security metadata.
You can make it fully dynamic if you choose.

Both method and web security are protected by implementations of `AuthorizationManager`.
For web security, you can supply your own implementation of `AuthorizationManager<RequestAuthorizationContext>` and supply it to the filter chain DSL like so:

[tabs]
======
Java::
+
[source,java,role="primary"]
----
@Component
public class DynamicAuthorizationManager implements AuthorizationManager<RequestAuthorizationContext> {
	private final MyExternalAuthorizationService authz;

	// ...

    @Override
    public AuthorizationResult authorize(Supplier<Authentication> authentication, RequestAuthorizationContext context) {
		// query the external service
    }
}

// ...

http
    .authorizeHttpRequests((authorize) -> authorize.anyRequest().access(dynamicAuthorizationManager))
----

Kotlin::
+
[source,kotlin,role="secondary"]
----
@Component
class DynamicAuthorizationManager : AuthorizationManager<RequestAuthorizationContext?> {
    private val rules: MyAuthorizationRulesRepository? = null

    // ...

    override fun authorize(authentication: Supplier<Authentication?>?, context: RequestAuthorizationContext?): AuthorizationResult {
		// look up rules from the database
    }
}

// ...

http {
    authorizeHttpRequests {
        authorize(anyRequest, dynamicAuthorizationManager)
    }
}
----
======

For method security, you can supply your own implementation of `AuthorizationManager<MethodInvocation>` and supply it to Spring AOP like so:

[tabs]
======
Java::
+
[source,java,role="primary"]
----
@Component
public class DynamicAuthorizationManager implements AuthorizationManager<MethodInvocation> {
	private final MyExternalAuthorizationService authz;

	// ...

    @Override
    public AuthorizationResult authorize(Supplier<Authentication> authentication, MethodInvocation invocation) {
		// query the external service
    }
}

// ...

@Bean
static Advisor securedAuthorizationAdvisor(DynamicAuthorizationManager dynamicAuthorizationManager) {
    return AuthorizationManagerBeforeMethodInterceptor.secured(dynamicAuthorizationManager)
}
----

Kotlin::
+
[source,kotlin,role="secondary"]
----
@Component
class DynamicAuthorizationManager : AuthorizationManager<MethodInvocation?> {
    private val authz: MyExternalAuthorizationService? = null

     // ...
    override fun authorize(authentication: Supplier<Authentication?>?, invocation: MethodInvocation?): AuthorizationResult {
		// query the external service
    }
}

companion object {
    @Bean
    fun securedAuthorizationAdvisor(dynamicAuthorizationManager: DynamicAuthorizationManager): Advisor {
        return AuthorizationManagerBeforeMethodInterceptor.preAuthorize(dynamicAuthorizationManager)
    }
}
----
======


[[appendix-faq-ldap-authorities]]
=== How do I authenticate against LDAP but load user roles from a database?

The `LdapAuthenticationProvider` bean (which handles normal LDAP authentication in Spring Security) is configured with two separate strategy interfaces, one that performs the authentication and one that loads the user authorities, called `LdapAuthenticator` and `LdapAuthoritiesPopulator`, respectively.
The `DefaultLdapAuthoritiesPopulator` loads the user authorities from the LDAP directory and has various configuration parameters to let you specify how these should be retrieved.

To use JDBC instead, you can implement the interface yourself, by using whatever SQL is appropriate for your schema:

[tabs]
======
Java::
+
[source,java,role="primary"]
----

public class MyAuthoritiesPopulator implements LdapAuthoritiesPopulator {
    @Autowired
    JdbcTemplate template;

    List<GrantedAuthority> getGrantedAuthorities(DirContextOperations userData, String username) {
        return template.query("select role from roles where username = ?",
                new String[] {username},
                new RowMapper<GrantedAuthority>() {
             /**
             *  We're assuming here that you're using the standard convention of using the role
             *  prefix "ROLE_" to mark attributes which are supported by Spring Security's RoleVoter.
             */
            @Override
            public GrantedAuthority mapRow(ResultSet rs, int rowNum) throws SQLException {
                return new SimpleGrantedAuthority("ROLE_" + rs.getString(1));
            }
        });
    }
}

----

Kotlin::
+
[source,kotlin,role="secondary"]
----
class MyAuthoritiesPopulator : LdapAuthoritiesPopulator {
    @Autowired
    lateinit var template: JdbcTemplate

    override fun getGrantedAuthorities(userData: DirContextOperations, username: String): MutableList<GrantedAuthority?> {
        return template.query("select role from roles where username = ?",
            arrayOf(username)
        ) { rs, _ ->
            /**
             * We're assuming here that you're using the standard convention of using the role
             * prefix "ROLE_" to mark attributes which are supported by Spring Security's RoleVoter.
             */
            SimpleGrantedAuthority("ROLE_" + rs.getString(1))
        }
    }
}
----
======

You would then add a bean of this type to your application context and inject it into the `LdapAuthenticationProvider`. This is covered in the section on configuring LDAP by using explicit Spring beans in the LDAP chapter of the reference manual.
Note that you cannot use the namespace for configuration in this case.
You should also consult the {security-api-url}[Javadoc] for the relevant classes and interfaces.


[[appendix-faq-namespace-post-processor]]
=== 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. What can I do short of abandoning namespace use?

The namespace functionality is intentionally limited, so it does not cover everything that you can do with plain beans.
If you want to do something simple, such as modifying a bean or injecting a different dependency, you can do so by adding a `BeanPostProcessor` to your configuration.
You can find more information in the https://docs.spring.io/spring/docs/3.0.x/spring-framework-reference/htmlsingle/spring-framework-reference.html#beans-factory-extension-bpp[Spring Reference Manual]. To do so, you need to know a bit about which beans are created, so you should also read the blog article mentioned in the earlier question on <<appendix-faq-namespace-to-bean-mapping,how the namespace maps to Spring beans>>.

Normally, you would add the functionality you require to the `postProcessBeforeInitialization` method of `BeanPostProcessor`. Suppose that you want to customize the `AuthenticationDetailsSource` used by the `UsernamePasswordAuthenticationFilter` (created by the `form-login` element). You want to extract a particular header called `CUSTOM_HEADER` from the request and use it while authenticating the user.
The processor class would look like the following listing:

[tabs]
======
Java::
+
[source,java,role="primary"]
----
public class CustomBeanPostProcessor implements BeanPostProcessor {

		public Object postProcessAfterInitialization(Object bean, String name) {
				if (bean instanceof UsernamePasswordAuthenticationFilter) {
						System.out.println("********* Post-processing " + name);
						((UsernamePasswordAuthenticationFilter)bean).setAuthenticationDetailsSource(
										new AuthenticationDetailsSource() {
												public Object buildDetails(Object context) {
														return ((HttpServletRequest)context).getHeader("CUSTOM_HEADER");
												}
										});
				}
				return bean;
		}

		public Object postProcessBeforeInitialization(Object bean, String name) {
				return bean;
		}
}
----

Kotlin::
+
[source,kotlin,role="secondary"]
----
class CustomBeanPostProcessor : BeanPostProcessor {
    override fun postProcessAfterInitialization(bean: Any, name: String): Any {
        if (bean is UsernamePasswordAuthenticationFilter) {
            println("********* Post-processing $name")
            bean.setAuthenticationDetailsSource(
                AuthenticationDetailsSource<HttpServletRequest, Any?> { context -> context.getHeader("CUSTOM_HEADER") })
        }
        return bean
    }

    override fun postProcessBeforeInitialization(bean: Any, name: String?): Any {
        return bean
    }
}
----
======

You would then register this bean in your application context.
Spring automatically invoke it on the beans defined in the application context.
