Extract Preface

Issue: gh-5836
This commit is contained in:
Rob Winch 2018-09-11 22:39:02 -05:00
parent 57359058dd
commit 5b8d66e911
17 changed files with 458 additions and 639 deletions

View File

@ -0,0 +1,40 @@
[[community]]
== Spring Security Community
Welcome to the Spring Security Community!
This section discusses how you to make the most of our vast community.
[[community-help]]
=== Getting Help
If you need help with Spring Security, we are here to help.
Below are some of the best steps to getting help:
* Read our reference documentation
* Try one of our many sample applications
// FIXME: Add a link to the samples section
* Ask a question on https://stackoverflow.com with the tag `spring-security`
* Report a bugs and enhancement requests at https://github.com/spring-projects/spring-security/issues
[[community-becoming-involved]]
=== Becoming Involved
We welcome your involvement in the Spring Security project.
There are many ways of contributing, including answering questions on StackOverflow, writing new code, improving existing code, assisting with documentation, developing samples or tutorials, reporting bugs, or simply making suggestions.
[[community-source]]
=== Source Code
Spring Security's source code can be found on GitHub at https://github.com/spring-projects/spring-security/
[[community-license]]
=== Apache 2 License
Spring Security is Open Source software released under the http://www.apache.org/licenses/LICENSE-2.0.html[Apache 2.0 license].
=== Social Media
You may follow https://twitter.com/SpringSecurity[@SpringSecurity] and https://twitter.com/SpringSecurity/lists/team[Spring Security team] on Twitter to stay up to date with the latest news.
You can also follow https://twitter.com/SpringCentral[@SpringCentral] to keep up to date with the entire Spring portfolio.
// == Getting Started
// FIXME: Add links to samples

View File

@ -0,0 +1,179 @@
[[get-spring-security]]
= Getting Spring Security
You can get hold of Spring Security in several ways.
You can download a packaged distribution from the main http://spring.io/spring-security[Spring Security] page, download individual jars from the Maven Central repository (or a Spring Maven repository for snapshot and milestone releases) or, alternatively, you can build the project from source yourself.
== Release Numbering
Spring Security versions are formatted as MAJOR.MINOR.PATCH such that
* MAJOR versions may contain breaking changes.
Typically these are done to provide improved security to match modern security practices.
* MINOR versions contain enhancements, but are considered passive updates
* PATCH level should be perfectly compatible, forwards and backwards, with the possible exception of changes which are to fix bugs
[[maven]]
== Usage with Maven
A minimal Spring Security Maven set of dependencies typically looks like the following:
.pom.xml
[source,xml]
[subs="verbatim,attributes"]
----
<dependencies>
<!-- ... other dependency elements ... -->
<dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-web</artifactId>
<version>{spring-security-version}</version>
</dependency>
<dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-config</artifactId>
<version>{spring-security-version}</version>
</dependency>
</dependencies>
----
If you are using additional features like LDAP, OpenID, etc. you will need to also include the appropriate <<modules>>.
[[maven-repositories]]
=== Maven Repositories
All GA releases (i.e. versions ending in .RELEASE) are deployed to Maven Central, so no additional Maven repositories need to be declared in your pom.
If you are using a SNAPSHOT version, you will need to ensure you have the Spring Snapshot repository defined as shown below:
.pom.xml
[source,xml]
----
<repositories>
<!-- ... possibly other repository elements ... -->
<repository>
<id>spring-snapshot</id>
<name>Spring Snapshot Repository</name>
<url>http://repo.spring.io/snapshot</url>
</repository>
</repositories>
----
If you are using a milestone or release candidate version, you will need to ensure you have the Spring Milestone repository defined as shown below:
.pom.xml
[source,xml]
----
<repositories>
<!-- ... possibly other repository elements ... -->
<repository>
<id>spring-milestone</id>
<name>Spring Milestone Repository</name>
<url>http://repo.spring.io/milestone</url>
</repository>
</repositories>
----
[[maven-bom]]
=== Spring Framework BOM
Spring Security builds against Spring Framework {spring-version}, but should work with 5
The problem that many users will have is that Spring Security's transitive dependencies resolve Spring Framework {spring-version} which can cause strange classpath problems.
One (tedious) way to circumvent this issue would be to include all the Spring Framework modules in a http://maven.apache.org/guides/introduction/introduction-to-dependency-mechanism.html#Dependency_Management[<dependencyManagement>] section of your pom.
An alternative approach is to include the `spring-framework-bom` within your `<dependencyManagement>` section of your `pom.xml` as shown below:
.pom.xml
[source,xml]
[subs="verbatim,attributes"]
----
<dependencyManagement>
<dependencies>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-framework-bom</artifactId>
<version>{spring-version}</version>
<type>pom</type>
<scope>import</scope>
</dependency>
</dependencies>
</dependencyManagement>
----
This will ensure that all the transitive dependencies of Spring Security use the Spring {spring-version} modules.
NOTE: This approach uses Maven's "bill of materials" (BOM) concept and is only available in Maven 2.0.9+.
For additional details about how dependencies are resolved refer to http://maven.apache.org/guides/introduction/introduction-to-dependency-mechanism.html[Maven's Introduction to the Dependency Mechanism documentation].
[[gradle]]
== Gradle
A minimal Spring Security Gradle set of dependencies typically looks like the following:
.build.gradle
[source,groovy]
[subs="verbatim,attributes"]
----
dependencies {
compile 'org.springframework.security:spring-security-web:{spring-security-version}'
compile 'org.springframework.security:spring-security-config:{spring-security-version}'
}
----
If you are using additional features like LDAP, OpenID, etc. you will need to also include the appropriate <<modules>>.
[[gradle-repositories]]
=== Gradle Repositories
All GA releases (i.e. versions ending in .RELEASE) are deployed to Maven Central, so using the mavenCentral() repository is sufficient for GA releases.
.build.gradle
[source,groovy]
----
repositories {
mavenCentral()
}
----
If you are using a SNAPSHOT version, you will need to ensure you have the Spring Snapshot repository defined as shown below:
.build.gradle
[source,groovy]
----
repositories {
maven { url 'https://repo.spring.io/snapshot' }
}
----
If you are using a milestone or release candidate version, you will need to ensure you have the Spring Milestone repository defined as shown below:
.build.gradle
[source,groovy]
----
repositories {
maven { url 'https://repo.spring.io/milestone' }
}
----
[[gradle-resolutionStrategy]]
=== Using Spring 4.0.x and Gradle
By default Gradle will use the newest version when resolving transitive versions.
This means that often times no additional work is necessary when running Spring Security {spring-security-version} with Spring Framework {spring-version}.
However, at times there can be issues that come up so it is best to mitigate this using http://www.gradle.org/docs/current/dsl/org.gradle.api.artifacts.ResolutionStrategy.html[Gradle's ResolutionStrategy] as shown below:
.build.gradle
[source,groovy]
[subs="verbatim,attributes"]
----
configurations.all {
resolutionStrategy.eachDependency { DependencyResolveDetails details ->
if (details.requested.group == 'org.springframework') {
details.useVersion '{spring-version}'
}
}
}
----
This will ensure that all the transitive dependencies of Spring Security use the Spring {spring-version} modules.
NOTE: This example uses Gradle 1.9, but may need modifications to work in future versions of Gradle since this is an incubating feature within Gradle.

View File

@ -0,0 +1,13 @@
= Preface
This section discusses the logistics of Spring Security.
include::community.adoc[]
include::whats-new.adoc[]
include::getting-spring-security.adoc[leveloffset=+1]
include::modules.adoc[leveloffset=+1]
include::samples.adoc[]

View File

@ -0,0 +1,114 @@
[[modules]]
= Project Modules
In Spring Security 3.0, the codebase has been sub-divided into separate jars which more clearly separate different functionality areas and third-party dependencies.
If you are using Maven to build your project, then these are the modules you will add to your `pom.xml`.
Even if you're not using Maven, we'd recommend that you consult the `pom.xml` files to get an idea of third-party dependencies and versions.
Alternatively, a good idea is to examine the libraries that are included in the sample applications.
[[spring-security-core]]
== Core - spring-security-core.jar
Contains core authentication and access-contol classes and interfaces, remoting support and basic provisioning APIs.
Required by any application which uses Spring Security.
Supports standalone applications, remote clients, method (service layer) security and JDBC user provisioning.
Contains the top-level packages:
* `org.springframework.security.core`
* `org.springframework.security.access`
* `org.springframework.security.authentication`
* `org.springframework.security.provisioning`
[[spring-security-remoting]]
== Remoting - spring-security-remoting.jar
Provides intergration with Spring Remoting.
You don't need this unless you are writing a remote client which uses Spring Remoting.
The main package is `org.springframework.security.remoting`.
[[spring-security-web]]
== Web - spring-security-web.jar
Contains filters and related web-security infrastructure code.
Anything with a servlet API dependency.
You'll need it if you require Spring Security web authentication services and URL-based access-control.
The main package is `org.springframework.security.web`.
[[spring-security-config]]
== Config - spring-security-config.jar
Contains the security namespace parsing code & Java configuration code.
You need it if you are using the Spring Security XML namespace for configuration or Spring Security's Java Configuration support.
The main package is `org.springframework.security.config`.
None of the classes are intended for direct use in an application.
[[spring-security-ldap]]
== LDAP - spring-security-ldap.jar
LDAP authentication and provisioning code.
Required if you need to use LDAP authentication or manage LDAP user entries.
The top-level package is `org.springframework.security.ldap`.
[[spring-security-oauth2-core]]
== OAuth 2.0 Core - spring-security-oauth2-core.jar
`spring-security-oauth2-core.jar` contains core classes and interfaces that provide support for the _OAuth 2.0 Authorization Framework_ and for _OpenID Connect Core 1.0_.
It is required by applications that use _OAuth 2.0_ or _OpenID Connect Core 1.0_, such as Client, Resource Server, and Authorization Server.
The top-level package is `org.springframework.security.oauth2.core`.
[[spring-security-oauth2-client]]
== OAuth 2.0 Client - spring-security-oauth2-client.jar
`spring-security-oauth2-client.jar` is Spring Security's client support for _OAuth 2.0 Authorization Framework_ and _OpenID Connect Core 1.0_.
Required by applications leveraging *OAuth 2.0 Login* and/or OAuth Client support.
The top-level package is `org.springframework.security.oauth2.client`.
[[spring-security-oauth2-jose]]
== OAuth 2.0 JOSE - spring-security-oauth2-jose.jar
`spring-security-oauth2-jose.jar` contains Spring Security's support for the _JOSE_ (Javascript Object Signing and Encryption) framework.
The _JOSE_ framework is intended to provide a method to securely transfer claims between parties.
It is built from a collection of specifications:
* JSON Web Token (JWT)
* JSON Web Signature (JWS)
* JSON Web Encryption (JWE)
* JSON Web Key (JWK)
It contains the top-level packages:
* `org.springframework.security.oauth2.jwt`
* `org.springframework.security.oauth2.jose`
[[spring-security-acl]]
== ACL - spring-security-acl.jar
Specialized domain object ACL implementation.
Used to apply security to specific domain object instances within your application.
The top-level package is `org.springframework.security.acls`.
[[spring-security-cas]]
== CAS - spring-security-cas.jar
Spring Security's CAS client integration.
If you want to use Spring Security web authentication with a CAS single sign-on server.
The top-level package is `org.springframework.security.cas`.
[[spring-security-openid]]
== OpenID - spring-security-openid.jar
OpenID web authentication support.
Used to authenticate users against an external OpenID server.
`org.springframework.security.openid`.
Requires OpenID4Java.
[[spring-security-test]]
== Test - spring-security-test.jar
Support for testing with Spring Security.

View File

@ -4,4 +4,4 @@ include::webflux.adoc[leveloffset=+1]
include::method.adoc[leveloffset=+1]
include::webtestclient.adoc[leveloffset=+1]
include::test.adoc[leveloffset=+1]

View File

@ -44,8 +44,14 @@ public class SecurityConfig {
@Bean
public MapReactiveUserDetailsService userDetailsService() {
User.UserBuilder userBuilder = User.withDefaultPasswordEncoder();
UserDetails rob = userBuilder.username("rob").password("rob").roles("USER").build();
UserDetails admin = userBuilder.username("admin").password("admin").roles("USER","ADMIN").build();
UserDetails rob = userBuilder.username("rob")
.password("rob")
.roles("USER")
.build();
UserDetails admin = userBuilder.username("admin")
.password("admin")
.roles("USER","ADMIN")
.build();
return new MapReactiveUserDetailsService(rob, admin);
}
}
@ -92,8 +98,14 @@ public class SecurityConfig {
@Bean
MapReactiveUserDetailsService userDetailsService() {
User.UserBuilder userBuilder = User.withDefaultPasswordEncoder();
UserDetails rob = userBuilder.username("rob").password("rob").roles("USER").build();
UserDetails admin = userBuilder.username("admin").password("admin").roles("USER","ADMIN").build();
UserDetails rob = userBuilder.username("rob")
.password("rob")
.roles("USER")
.build();
UserDetails admin = userBuilder.username("admin")
.password("admin")
.roles("USER","ADMIN")
.build();
return new MapReactiveUserDetailsService(rob, admin);
}
}

View File

@ -1,8 +1,8 @@
[[test-webflux]]
= WebFlux Support
= Reactive Test Support
[[test-erms]]
== Reactive Method Security
== Testing Reactive Method Security
For example, we can test our example from <<jc-erms>> using the same setup and annotations we did in <<test-method>>.
Here is a minimal sample of what we can do:

View File

@ -1,31 +0,0 @@
[[community]]
== Spring Security Community
[[jira]]
=== Issue Tracking
Spring Security uses JIRA to manage bug reports and enhancement requests.
If you find a bug, please log a report using JIRA.
Do not log it on the support forum, mailing list or by emailing the project's developers.
Such approaches are ad-hoc and we prefer to manage bugs using a more formal process.
If possible, in your issue report please provide a JUnit test that demonstrates any incorrect behaviour.
Or, better yet, provide a patch that corrects the issue.
Similarly, enhancements are welcome to be logged in the issue tracker, although we only accept enhancement requests if you include corresponding unit tests.
This is necessary to ensure project test coverage is adequately maintained.
You can access the issue tracker at https://github.com/spring-projects/spring-security/issues.
[[becoming-involved]]
=== Becoming Involved
We welcome your involvement in the Spring Security project.
There are many ways of contributing, including reading the forum and responding to questions from other people, writing new code, improving existing code, assisting with documentation, developing samples or tutorials, or simply making suggestions.
[[further-info]]
=== Further Information
Questions and comments on Spring Security are welcome.
You can use the Spring at Stack Overflow web site at http://spring.io/questions[http://spring.io/questions] to discuss Spring Security with other users of the framework.
Remember to use JIRA for bug reports, as explained above.

View File

@ -1,10 +0,0 @@
[[getting-started]]
== Getting Started
The later parts of this guide provide an in-depth discussion of the framework architecture and implementation classes, which you need to understand if you want to do any serious customization.
In this part, we'll introduce Spring Security 5, give a brief overview of the project's history and take a slightly gentler look at how to get started using the framework.
In particular, we'll look at namespace configuration which provides a much simpler way of securing your application compared to the traditional Spring bean approach where you have to wire up all the implementation classes individually.
We'll also take a look at the sample applications that are available.
It's worth trying to run these and experimenting with them a bit even before you read the later sections - you can dip back into them as your understanding of the framework increases.
Please also check out the [http://spring.io/spring-security](http://spring.io/spring-security) as it has useful information on building the project, plus links to articles, videos and tutorials.

View File

@ -1,56 +1,3 @@
[[preface]]
= Preface
Spring Security provides a comprehensive security solution for Java EE-based enterprise software applications.
As you will discover as you venture through this reference guide, we have tried to provide you a useful and highly configurable security system.
Security is an ever-moving target, and it's important to pursue a comprehensive, system-wide approach.
In security circles we encourage you to adopt "layers of security", so that each layer tries to be as secure as possible in its own right, with successive layers providing additional security.
The "tighter" the security of each layer, the more robust and safe your application will be.
At the bottom level you'll need to deal with issues such as transport security and system identification, in order to mitigate man-in-the-middle attacks.
Next you'll generally utilise firewalls, perhaps with VPNs or IP security to ensure only authorised systems can attempt to connect.
In corporate environments you may deploy a DMZ to separate public-facing servers from backend database and application servers.
Your operating system will also play a critical part, addressing issues such as running processes as non-privileged users and maximising file system security.
An operating system will usually also be configured with its own firewall.
Hopefully somewhere along the way you'll be trying to prevent denial of service and brute force attacks against the system.
An intrusion detection system will also be especially useful for monitoring and responding to attacks, with such systems able to take protective action such as blocking offending TCP/IP addresses in real-time.
Moving to the higher layers, your Java Virtual Machine will hopefully be configured to minimize the permissions granted to different Java types, and then your application will add its own problem domain-specific security configuration.
Spring Security makes this latter area - application security - much easier.
Of course, you will need to properly address all security layers mentioned above, together with managerial factors that encompass every layer.
A non-exhaustive list of such managerial factors would include security bulletin monitoring, patching, personnel vetting, audits, change control, engineering management systems, data backup, disaster recovery, performance benchmarking, load monitoring, centralised logging, incident response procedures etc.
With Spring Security being focused on helping you with the enterprise application security layer, you will find that there are as many different requirements as there are business problem domains.
A banking application has different needs from an ecommerce application.
An ecommerce application has different needs from a corporate sales force automation tool.
These custom requirements make application security interesting, challenging and rewarding.
Please read <<getting-started>>, in its entirety to begin with.
This will introduce you to the framework and the namespace-based configuration system with which you can get up and running quite quickly.
To get more of an understanding of how Spring Security works, and some of the classes you might need to use, you should then read <<overall-architecture>>.
The remaining parts of this guide are structured in a more traditional reference style, designed to be read on an as-required basis.
We'd also recommend that you read up as much as possible on application security issues in general.
Spring Security is not a panacea which will solve all security issues.
It is important that the application is designed with security in mind from the start.
Attempting to retrofit it is not a good idea.
In particular, if you are building a web application, you should be aware of the many potential vulnerabilities such as cross-site scripting, request-forgery and session-hijacking which you should be taking into account from the start.
The OWASP web site (http://www.owasp.org/) maintains a top ten list of web application vulnerabilities as well as a lot of useful reference information.
We hope that you find this reference guide useful, and we welcome your feedback and <<jira,suggestions>>.
Finally, welcome to the Spring Security <<community,community>>.
include::getting-started.adoc[]
include::introduction.adoc[]
include::whats-new.adoc[]
include::guides.adoc[]
include::java-configuration.adoc[]
include::namespace.adoc[]
include::samples.adoc[]
include::community.adoc[]

View File

@ -1,446 +0,0 @@
[[introduction]]
== Introduction
[[what-is-acegi-security]]
=== What is Spring Security?
Spring Security provides comprehensive security services for Java EE-based enterprise software applications.
There is a particular emphasis on supporting projects built using The Spring Framework, which is the leading Java EE solution for enterprise software development.
If you're not using Spring for developing enterprise applications, we warmly encourage you to take a closer look at it.
Some familiarity with Spring - and in particular dependency injection principles - will help you get up to speed with Spring Security more easily.
People use Spring Security for many reasons, but most are drawn to the project after finding the security features of Java EE's Servlet Specification or EJB Specification lack the depth required for typical enterprise application scenarios.
Whilst mentioning these standards, it's important to recognise that they are not portable at a WAR or EAR level.
Therefore, if you switch server environments, it is typically a lot of work to reconfigure your application's security in the new target environment.
Using Spring Security overcomes these problems, and also brings you dozens of other useful, customisable security features.
As you probably know two major areas of application security are _authentication_ and _authorization_ (or _access-control_).
These are the two main areas that Spring Security targets.
"Authentication" is the process of establishing a principal is who they claim to be (a "principal" generally means a user, device or some other system which can perform an action in your application).
"Authorization" refers to the process of deciding whether a principal is allowed to perform an action within your application.
To arrive at the point where an authorization decision is needed, the identity of the principal has already been established by the authentication process.
These concepts are common, and not at all specific to Spring Security.
At an authentication level, Spring Security supports a wide range of authentication models.
Most of these authentication models are either provided by third parties, or are developed by relevant standards bodies such as the Internet Engineering Task Force.
In addition, Spring Security provides its own set of authentication features.
Specifically, Spring Security currently supports authentication integration with all of these technologies:
* HTTP BASIC authentication headers (an IETF RFC-based standard)
* HTTP Digest authentication headers (an IETF RFC-based standard)
* HTTP X.509 client certificate exchange (an IETF RFC-based standard)
* LDAP (a very common approach to cross-platform authentication needs, especially in large environments)
* Form-based authentication (for simple user interface needs)
* OpenID authentication
* Authentication based on pre-established request headers (such as Computer Associates Siteminder)
* Jasig Central Authentication Service (otherwise known as CAS, which is a popular open source single sign-on system)
* Transparent authentication context propagation for Remote Method Invocation (RMI) and HttpInvoker (a Spring remoting protocol)
* Automatic "remember-me" authentication (so you can tick a box to avoid re-authentication for a predetermined period of time)
* Anonymous authentication (allowing every unauthenticated call to automatically assume a particular security identity)
* Run-as authentication (which is useful if one call should proceed with a different security identity)
* Java Authentication and Authorization Service (JAAS)
* Java EE container authentication (so you can still use Container Managed Authentication if desired)
* Kerberos
* Java Open Source Single Sign-On (JOSSO) *
* OpenNMS Network Management Platform *
* AppFuse *
* AndroMDA *
* Mule ESB *
* Direct Web Request (DWR) *
* Grails *
* Tapestry *
* JTrac *
* Jasypt *
* Roller *
* Elastic Path *
* Atlassian Crowd *
* Your own authentication systems (see below)
(* Denotes provided by a third party)
Many independent software vendors (ISVs) adopt Spring Security because of this significant choice of flexible authentication models.
Doing so allows them to quickly integrate their solutions with whatever their end clients need, without undertaking a lot of engineering or requiring the client to change their environment.
If none of the above authentication mechanisms suit your needs, Spring Security is an open platform and it is quite simple to write your own authentication mechanism.
Many corporate users of Spring Security need to integrate with "legacy" systems that don't follow any particular security standards, and Spring Security is happy to "play nicely" with such systems.
Irrespective of the authentication mechanism, Spring Security provides a deep set of authorization capabilities.
There are three main areas of interest: authorizing web requests, authorizing whether methods can be invoked and authorizing access to individual domain object instances.
To help you understand the differences, consider the authorization capabilities found in the Servlet Specification web pattern security, EJB Container Managed Security and file system security respectively.
Spring Security provides deep capabilities in all of these important areas, which we'll explore later in this reference guide.
[[history]]
=== History
Spring Security began in late 2003 as "The Acegi Security System for Spring".
A question was posed on the Spring Developers' mailing list asking whether there had been any consideration given to a Spring-based security implementation.
At the time the Spring community was relatively small (especially compared with the size today!), and indeed Spring itself had only existed as a SourceForge project from early 2003.
The response to the question was that it was a worthwhile area, although a lack of time currently prevented its exploration.
With that in mind, a simple security implementation was built and not released.
A few weeks later another member of the Spring community inquired about security, and at the time this code was offered to them.
Several other requests followed, and by January 2004 around twenty people were using the code.
These pioneering users were joined by others who suggested a SourceForge project was in order, which was duly established in March 2004.
In those early days, the project didn't have any of its own authentication modules.
Container Managed Security was relied upon for the authentication process, with Acegi Security instead focusing on authorization.
This was suitable at first, but as more and more users requested additional container support, the fundamental limitation of container-specific authentication realm interfaces became clear.
There was also a related issue of adding new JARs to the container's classpath, which was a common source of end user confusion and misconfiguration.
Acegi Security-specific authentication services were subsequently introduced.
Around a year later, Acegi Security became an official Spring Framework subproject.
The 1.0.0 final release was published in May 2006 - after more than two and a half years of active use in numerous production software projects and many hundreds of improvements and community contributions.
Acegi Security became an official Spring Portfolio project towards the end of 2007 and was rebranded as _Spring Security_.
Today Spring Security enjoys a strong and active open source community.
There are thousands of messages about Spring Security on the support forums.
There is an active core of developers who work on the code itself and an active community which also regularly share patches and support their peers.
[[release-numbering]]
=== Release Numbering
It is useful to understand how Spring Security release numbers work, as it will help you identify the effort (or lack thereof) involved in migrating to future releases of the project.
Each release uses a standard triplet of integers: MAJOR.MINOR.PATCH.
The intent is that MAJOR versions are incompatible, large-scale upgrades of the API.
MINOR versions should largely retain source and binary compatibility with older minor versions, thought there may be some design changes and incompatible updates.
PATCH level should be perfectly compatible, forwards and backwards, with the possible exception of changes which are to fix bugs and defects.
The extent to which you are affected by changes will depend on how tightly integrated your code is.
If you are doing a lot of customization you are more likely to be affected than if you are using a simple namespace configuration.
You should always test your application thoroughly before rolling out a new version.
[[get-spring-security]]
=== Getting Spring Security
You can get hold of Spring Security in several ways.
You can download a packaged distribution from the main http://spring.
io/spring-security[Spring Security] page, download individual jars from the Maven Central repository (or a Spring Maven repository for snapshot and milestone releases) or, alternatively, you can build the project from source yourself.
[[maven]]
==== Usage with Maven
A minimal Spring Security Maven set of dependencies typically looks like the following:
.pom.xml
[source,xml]
[subs="verbatim,attributes"]
----
<dependencies>
<!-- ... other dependency elements ... -->
<dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-web</artifactId>
<version>{spring-security-version}</version>
</dependency>
<dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-config</artifactId>
<version>{spring-security-version}</version>
</dependency>
</dependencies>
----
If you are using additional features like LDAP, OpenID, etc. you will need to also include the appropriate <<modules>>.
[[maven-repositories]]
===== Maven Repositories
All GA releases (i.e. versions ending in .RELEASE) are deployed to Maven Central, so no additional Maven repositories need to be declared in your pom.
If you are using a SNAPSHOT version, you will need to ensure you have the Spring Snapshot repository defined as shown below:
.pom.xml
[source,xml]
----
<repositories>
<!-- ... possibly other repository elements ... -->
<repository>
<id>spring-snapshot</id>
<name>Spring Snapshot Repository</name>
<url>http://repo.spring.io/snapshot</url>
</repository>
</repositories>
----
If you are using a milestone or release candidate version, you will need to ensure you have the Spring Milestone repository defined as shown below:
.pom.xml
[source,xml]
----
<repositories>
<!-- ... possibly other repository elements ... -->
<repository>
<id>spring-milestone</id>
<name>Spring Milestone Repository</name>
<url>http://repo.spring.io/milestone</url>
</repository>
</repositories>
----
[[maven-bom]]
===== Spring Framework BOM
Spring Security builds against Spring Framework {spring-version}, but should work with 5
The problem that many users will have is that Spring Security's transitive dependencies resolve Spring Framework {spring-version} which can cause strange classpath problems.
One (tedious) way to circumvent this issue would be to include all the Spring Framework modules in a http://maven.apache.org/guides/introduction/introduction-to-dependency-mechanism.html#Dependency_Management[<dependencyManagement>] section of your pom.
An alternative approach is to include the `spring-framework-bom` within your `<dependencyManagement>` section of your `pom.xml` as shown below:
.pom.xml
[source,xml]
[subs="verbatim,attributes"]
----
<dependencyManagement>
<dependencies>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-framework-bom</artifactId>
<version>{spring-version}</version>
<type>pom</type>
<scope>import</scope>
</dependency>
</dependencies>
</dependencyManagement>
----
This will ensure that all the transitive dependencies of Spring Security use the Spring {spring-version} modules.
NOTE: This approach uses Maven's "bill of materials" (BOM) concept and is only available in Maven 2.0.9+.
For additional details about how dependencies are resolved refer to http://maven.apache.org/guides/introduction/introduction-to-dependency-mechanism.html[Maven's Introduction to the Dependency Mechanism documentation].
[[gradle]]
==== Gradle
A minimal Spring Security Gradle set of dependencies typically looks like the following:
.build.gradle
[source,groovy]
[subs="verbatim,attributes"]
----
dependencies {
compile 'org.springframework.security:spring-security-web:{spring-security-version}'
compile 'org.springframework.security:spring-security-config:{spring-security-version}'
}
----
If you are using additional features like LDAP, OpenID, etc. you will need to also include the appropriate <<modules>>.
[[gradle-repositories]]
===== Gradle Repositories
All GA releases (i.e. versions ending in .RELEASE) are deployed to Maven Central, so using the mavenCentral() repository is sufficient for GA releases.
.build.gradle
[source,groovy]
----
repositories {
mavenCentral()
}
----
If you are using a SNAPSHOT version, you will need to ensure you have the Spring Snapshot repository defined as shown below:
.build.gradle
[source,groovy]
----
repositories {
maven { url 'https://repo.spring.io/snapshot' }
}
----
If you are using a milestone or release candidate version, you will need to ensure you have the Spring Milestone repository defined as shown below:
.build.gradle
[source,groovy]
----
repositories {
maven { url 'https://repo.spring.io/milestone' }
}
----
[[gradle-resolutionStrategy]]
===== Using Spring 4.0.x and Gradle
By default Gradle will use the newest version when resolving transitive versions.
This means that often times no additional work is necessary when running Spring Security {spring-security-version} with Spring Framework {spring-version}.
However, at times there can be issues that come up so it is best to mitigate this using http://www.gradle.org/docs/current/dsl/org.gradle.api.artifacts.ResolutionStrategy.html[Gradle's ResolutionStrategy] as shown below:
.build.gradle
[source,groovy]
[subs="verbatim,attributes"]
----
configurations.all {
resolutionStrategy.eachDependency { DependencyResolveDetails details ->
if (details.requested.group == 'org.springframework') {
details.useVersion '{spring-version}'
}
}
}
----
This will ensure that all the transitive dependencies of Spring Security use the Spring {spring-version} modules.
NOTE: This example uses Gradle 1.9, but may need modifications to work in future versions of Gradle since this is an incubating feature within Gradle.
[[modules]]
==== Project Modules
In Spring Security 3.0, the codebase has been sub-divided into separate jars which more clearly separate different functionality areas and third-party dependencies.
If you are using Maven to build your project, then these are the modules you will add to your `pom.xml`.
Even if you're not using Maven, we'd recommend that you consult the `pom.xml` files to get an idea of third-party dependencies and versions.
Alternatively, a good idea is to examine the libraries that are included in the sample applications.
[[spring-security-core]]
===== Core - spring-security-core.jar
Contains core authentication and access-contol classes and interfaces, remoting support and basic provisioning APIs.
Required by any application which uses Spring Security.
Supports standalone applications, remote clients, method (service layer) security and JDBC user provisioning.
Contains the top-level packages:
* `org.springframework.security.core`
* `org.springframework.security.access`
* `org.springframework.security.authentication`
* `org.springframework.security.provisioning`
[[spring-security-remoting]]
===== Remoting - spring-security-remoting.jar
Provides intergration with Spring Remoting.
You don't need this unless you are writing a remote client which uses Spring Remoting.
The main package is `org.springframework.security.remoting`.
[[spring-security-web]]
===== Web - spring-security-web.jar
Contains filters and related web-security infrastructure code.
Anything with a servlet API dependency.
You'll need it if you require Spring Security web authentication services and URL-based access-control.
The main package is `org.springframework.security.web`.
[[spring-security-config]]
===== Config - spring-security-config.jar
Contains the security namespace parsing code & Java configuration code.
You need it if you are using the Spring Security XML namespace for configuration or Spring Security's Java Configuration support.
The main package is `org.springframework.security.config`.
None of the classes are intended for direct use in an application.
[[spring-security-ldap]]
===== LDAP - spring-security-ldap.jar
LDAP authentication and provisioning code.
Required if you need to use LDAP authentication or manage LDAP user entries.
The top-level package is `org.springframework.security.ldap`.
[[spring-security-oauth2-core]]
===== OAuth 2.0 Core - spring-security-oauth2-core.jar
`spring-security-oauth2-core.jar` contains core classes and interfaces that provide support for the _OAuth 2.0 Authorization Framework_ and for _OpenID Connect Core 1.0_.
It is required by applications that use _OAuth 2.0_ or _OpenID Connect Core 1.0_, such as Client, Resource Server, and Authorization Server.
The top-level package is `org.springframework.security.oauth2.core`.
[[spring-security-oauth2-client]]
===== OAuth 2.0 Client - spring-security-oauth2-client.jar
`spring-security-oauth2-client.jar` is Spring Security's client support for _OAuth 2.0 Authorization Framework_ and _OpenID Connect Core 1.0_.
Required by applications leveraging *OAuth 2.0 Login* and/or OAuth Client support.
The top-level package is `org.springframework.security.oauth2.client`.
[[spring-security-oauth2-jose]]
===== OAuth 2.0 JOSE - spring-security-oauth2-jose.jar
`spring-security-oauth2-jose.jar` contains Spring Security's support for the _JOSE_ (Javascript Object Signing and Encryption) framework.
The _JOSE_ framework is intended to provide a method to securely transfer claims between parties.
It is built from a collection of specifications:
* JSON Web Token (JWT)
* JSON Web Signature (JWS)
* JSON Web Encryption (JWE)
* JSON Web Key (JWK)
It contains the top-level packages:
* `org.springframework.security.oauth2.jwt`
* `org.springframework.security.oauth2.jose`
[[spring-security-acl]]
===== ACL - spring-security-acl.jar
Specialized domain object ACL implementation.
Used to apply security to specific domain object instances within your application.
The top-level package is `org.springframework.security.acls`.
[[spring-security-cas]]
===== CAS - spring-security-cas.jar
Spring Security's CAS client integration.
If you want to use Spring Security web authentication with a CAS single sign-on server.
The top-level package is `org.springframework.security.cas`.
[[spring-security-openid]]
===== OpenID - spring-security-openid.jar
OpenID web authentication support.
Used to authenticate users against an external OpenID server.
`org.springframework.security.openid`.
Requires OpenID4Java.
[[spring-security-test]]
===== Test - spring-security-test.jar
Support for testing with Spring Security.
[[get-source]]
==== Checking out the Source
Since Spring Security is an Open Source project, we'd strongly encourage you to check out the source code using git.
This will give you full access to all the sample applications and you can build the most up to date version of the project easily.
Having the source for a project is also a huge help in debugging.
Exception stack traces are no longer obscure black-box issues but you can get straight to the line that's causing the problem and work out what's happening.
The source is the ultimate documentation for a project and often the simplest place to find out how something actually works.
To obtain the source for the project, use the following git command:
[source,txt]
----
git clone https://github.com/spring-projects/spring-security.git
----
This will give you access to the entire project history (including all releases and branches) on your local machine.

View File

@ -1,6 +1,6 @@
[[jc]]
== Java Configuration
= Java Configuration
General support for http://docs.spring.io/spring/docs/3.1.x/spring-framework-reference/html/beans.html#beans-java[Java Configuration] was added to Spring Framework in Spring 3.1.
Since Spring Security 3.2 there has been Spring Security Java Configuration support which enables users to easily configure Spring Security without the use of any XML.
@ -9,7 +9,7 @@ If you are familiar with the <<ns-config>> then you should find quite a few simi
NOTE: Spring Security provides https://github.com/spring-projects/spring-security/tree/master/samples/javaconfig[lots of sample applications] which demonstrate the use of Spring Security Java Configuration.
=== Hello Web Security Java Configuration
== Hello Web Security Java Configuration
The first step is to create our Spring Security Java Configuration.
The configuration creates a Servlet Filter known as the `springSecurityFilterChain` which is responsible for all the security (protecting the application URLs, validating submitted username and passwords, redirecting to the log in form, etc) within your application.
@ -58,7 +58,7 @@ You can find a summary of the features below:
** http://docs.oracle.com/javaee/6/api/javax/servlet/http/HttpServletRequest.html#login(java.lang.String,%20java.lang.String)[HttpServletRequest.html#login(java.lang.String, java.lang.String)]
** http://docs.oracle.com/javaee/6/api/javax/servlet/http/HttpServletRequest.html#logout()[HttpServletRequest.html#logout()]
==== AbstractSecurityWebApplicationInitializer
=== AbstractSecurityWebApplicationInitializer
The next step is to register the `springSecurityFilterChain` with the war.
This can be done in Java Configuration with http://docs.spring.io/spring/docs/3.2.x/spring-framework-reference/html/mvc.html#mvc-container-config[Spring's WebApplicationInitializer support] in a Servlet 3.0+ environment.
@ -68,7 +68,7 @@ The way in which we use `AbstractSecurityWebApplicationInitializer` differs depe
* <<abstractsecuritywebapplicationinitializer-without-existing-spring>> - Use these instructions if you are not using Spring already
* <<abstractsecuritywebapplicationinitializer-with-spring-mvc>> - Use these instructions if you are already using Spring
==== AbstractSecurityWebApplicationInitializer without Existing Spring
=== AbstractSecurityWebApplicationInitializer without Existing Spring
If you are not using Spring or Spring MVC, you will need to pass in the `WebSecurityConfig` into the superclass to ensure the configuration is picked up.
You can find an example below:
@ -91,7 +91,7 @@ The `SecurityWebApplicationInitializer` will do the following things:
* Automatically register the springSecurityFilterChain Filter for every URL in your application
* Add a ContextLoaderListener that loads the <<jc-hello-wsca,WebSecurityConfig>>.
==== AbstractSecurityWebApplicationInitializer with Spring MVC
=== AbstractSecurityWebApplicationInitializer with Spring MVC
If we were using Spring elsewhere in our application we probably already had a `WebApplicationInitializer` that is loading our Spring Configuration.
If we use the previous configuration we would get an error.
@ -128,7 +128,7 @@ public class MvcWebApplicationInitializer extends
----
[[jc-httpsecurity]]
=== HttpSecurity
== HttpSecurity
Thus far our <<jc-hello-wsca,WebSecurityConfig>> only contains information about how to authenticate our users.
How does Spring Security know that we want to require all users to be authenticated? How does Spring Security know we want to support form based authentication? The reason for this is that the `WebSecurityConfigurerAdapter` provides a default configuration in the `configure(HttpSecurity http)` method that looks like:
@ -168,7 +168,7 @@ If you read the code it also makes sense.
I want to configure authorized requests __and__ configure form login __and__ configure HTTP Basic authentication.
[[jc-form]]
=== Java Configuration and Form Login
== Java Configuration and Form Login
You might be wondering where the login form came from when you were prompted to log in, since we made no mention of any HTML files or JSPs.
Since Spring Security's default configuration does not explicitly set a URL for the login page, Spring Security generates one automatically, based on the features that are enabled and using standard values for the URL which processes the submitted login, the default target URL the user will be sent to after logging in and so on.
@ -235,7 +235,7 @@ We could easily update our configuration if some of the defaults do not meet our
<6> We must <<csrf-include-csrf-token>> To learn more read the <<csrf>> section of the reference
[[jc-authorize-requests]]
=== Authorize Requests
== Authorize Requests
Our examples have only required users to be authenticated and have done so for every URL in our application.
We can specify custom requirements for our URLs by adding multiple children to our `http.authorizeRequests()` method.
For example:
@ -266,7 +266,7 @@ You will notice that since we are using the `hasRole` expression we do not need
<5> Any URL that has not already been matched on only requires that the user be authenticated
[[jc-logout]]
=== Handling Logouts
== Handling Logouts
When using the `{security-api-url}org/springframework/security/config/annotation/web/configuration/WebSecurityConfigurerAdapter.html[WebSecurityConfigurerAdapter]`, logout capabilities are automatically applied.
The default is that accessing the URL `/logout` will log the user out by:
@ -315,10 +315,10 @@ For more information, please consult the {security-api-url}org/springframework/s
This is a shortcut for adding a `CookieClearingLogoutHandler` explicitly.
[NOTE]
====
===
Logouts can of course also be configured using the XML Namespace notation.
Please see the documentation for the <<nsa-logout, logout element>> in the Spring Security XML Namespace section for further details.
====
===
Generally, in order to customize logout functionality, you can add
`{security-api-url}org/springframework/security/web/authentication/logout/LogoutHandler.html[LogoutHandler]`
@ -329,7 +329,7 @@ For many common scenarios, these handlers are applied under the
covers when using the fluent API.
[[jc-logout-handler]]
==== LogoutHandler
=== LogoutHandler
Generally, `{security-api-url}org/springframework/security/web/authentication/logout/LogoutHandler.html[LogoutHandler]`
implementations indicate classes that are able to participate in logout handling.
@ -351,7 +351,7 @@ E.g. `deleteCookies()` allows specifying the names of one or more cookies to be
This is a shortcut compared to adding a `CookieClearingLogoutHandler`.
[[jc-logout-success-handler]]
==== LogoutSuccessHandler
=== LogoutSuccessHandler
The `LogoutSuccessHandler` is called after a successful logout by the `LogoutFilter`, to handle e.g.
redirection or forwarding to the appropriate destination.
@ -373,7 +373,7 @@ Instead of redirecting to a URL upon the successful logout, this `LogoutSuccessH
If not configured a status code 200 will be returned by default.
[[jc-logout-references]]
==== Further Logout-Related References
=== Further Logout-Related References
- <<ns-logout, Logout Handling>>
- <<test-logout, Testing Logout>>
@ -385,7 +385,7 @@ If not configured a status code 200 will be returned by default.
[[jc-oauth2login]]
=== OAuth 2.0 Login
== OAuth 2.0 Login
The OAuth 2.0 Login feature provides an application with the capability to have users log in to the application by using their existing account at an OAuth 2.0 Provider (e.g.
GitHub) or OpenID Connect 1.0 Provider (such as Google).
@ -394,7 +394,7 @@ OAuth 2.0 Login implements the use cases: "Login with Google" or "Login with Git
NOTE: OAuth 2.0 Login is implemented by using the *Authorization Code Grant*, as specified in the https://tools.ietf.org/html/rfc6749#section-4.1[OAuth 2.0 Authorization Framework] and http://openid.net/specs/openid-connect-core-1_0.html#CodeFlowAuth[OpenID Connect Core 1.0].
[[jc-oauth2login-sample-boot]]
==== Spring Boot 2.0 Sample
=== Spring Boot 2.0 Sample
Spring Boot 2.0 brings full auto-configuration capabilities for OAuth 2.0 Login.
@ -407,7 +407,7 @@ This section shows how to configure the {gh-samples-url}/boot/oauth2login[*OAuth
[[jc-oauth2login-sample-initial-setup]]
===== Initial setup
==== Initial setup
To use Google's OAuth 2.0 authentication system for login, you must set up a project in the Google API Console to obtain OAuth 2.0 credentials.
@ -418,7 +418,7 @@ Follow the instructions on the https://developers.google.com/identity/protocols/
After completing the "Obtain OAuth 2.0 credentials" instructions, you should have a new OAuth Client with credentials consisting of a Client ID and a Client Secret.
[[jc-oauth2login-sample-redirect-uri]]
===== Setting the redirect URI
==== Setting the redirect URI
The redirect URI is the path in the application that the end-user's user-agent is redirected back to after they have authenticated with Google and have granted access to the OAuth Client _(<<jc-oauth2login-sample-initial-setup,created in the previous step>>)_ on the Consent page.
@ -428,7 +428,7 @@ TIP: The default redirect URI template is `{baseUrl}/login/oauth2/code/{registra
The *_registrationId_* is a unique identifier for the <<jc-oauth2login-client-registration,ClientRegistration>>.
[[jc-oauth2login-sample-application-config]]
===== Configure `application.yml`
==== Configure `application.yml`
Now that you have a new OAuth Client with Google, you need to configure the application to use the OAuth Client for the _authentication flow_.
To do so:
@ -448,16 +448,16 @@ spring:
----
+
.OAuth Client properties
====
===
<1> `spring.security.oauth2.client.registration` is the base property prefix for OAuth Client properties.
<2> Following the base property prefix is the ID for the <<jc-oauth2login-client-registration,ClientRegistration>>, such as google.
====
===
. Replace the values in the `client-id` and `client-secret` property with the OAuth 2.0 credentials you created earlier.
[[jc-oauth2login-sample-boot-application]]
===== Boot up the application
==== Boot up the application
Launch the Spring Boot 2.0 sample and go to `http://localhost:8080`.
You are then redirected to the default _auto-generated_ login page, which displays a link for Google.
@ -471,7 +471,7 @@ Click *Allow* to authorize the OAuth Client to access your email address and bas
At this point, the OAuth Client retrieves your email address and basic profile information from the http://openid.net/specs/openid-connect-core-1_0.html#UserInfo[UserInfo Endpoint] and establishes an authenticated session.
[[jc-oauth2login-client-registration]]
==== ClientRegistration
=== ClientRegistration
`ClientRegistration` is a representation of a client registered with an OAuth 2.0 or OpenID Connect 1.0 Provider.
@ -528,7 +528,7 @@ The name may be used in certain scenarios, such as when displaying the name of t
<13> `userNameAttributeName`: The name of the attribute returned in the UserInfo Response that references the Name or Identifier of the end-user.
[[jc-oauth2login-boot-property-mappings]]
==== Spring Boot 2.0 Property Mappings
=== Spring Boot 2.0 Property Mappings
The following table outlines the mapping of the Spring Boot 2.0 OAuth Client properties to the `ClientRegistration` properties.
@ -576,7 +576,7 @@ The following table outlines the mapping of the Spring Boot 2.0 OAuth Client pro
|===
[[jc-oauth2login-client-registration-repo]]
==== ClientRegistrationRepository
=== ClientRegistrationRepository
The `ClientRegistrationRepository` serves as a repository for OAuth 2.0 / OpenID Connect 1.0 `ClientRegistration`(s).
@ -617,7 +617,7 @@ public class OAuth2LoginController {
----
[[jc-oauth2login-common-oauth2-provider]]
==== CommonOAuth2Provider
=== CommonOAuth2Provider
`CommonOAuth2Provider` pre-defines a set of default client properties for a number of well known providers: Google, GitHub, Facebook, and Okta.
@ -664,7 +664,7 @@ spring:
<2> The `provider` property is set to `google`, which will leverage the auto-defaulting of client properties set in `CommonOAuth2Provider.GOOGLE.getBuilder()`.
[[jc-oauth2login-custom-provider-properties]]
==== Configuring Custom Provider Properties
=== Configuring Custom Provider Properties
There are some OAuth 2.0 Providers that support multi-tenancy, which results in different protocol endpoints for each tenant (or sub-domain).
@ -696,7 +696,7 @@ spring:
<1> The base property (`spring.security.oauth2.client.provider.okta`) allows for custom configuration of protocol endpoint locations.
[[jc-oauth2login-override-boot-autoconfig]]
==== Overriding Spring Boot 2.0 Auto-configuration
=== Overriding Spring Boot 2.0 Auto-configuration
The Spring Boot 2.0 Auto-configuration class for OAuth Client support is `OAuth2ClientAutoConfiguration`.
@ -713,7 +713,7 @@ If you need to override the auto-configuration based on your specific requiremen
[[jc-oauth2login-register-clientregistrationrepository-bean]]
===== Register a `ClientRegistrationRepository` `@Bean`
==== Register a `ClientRegistrationRepository` `@Bean`
The following example shows how to register a `ClientRegistrationRepository` `@Bean`:
@ -748,7 +748,7 @@ public class OAuth2LoginConfig {
[[jc-oauth2login-provide-websecurityconfigureradapter]]
===== Provide a `WebSecurityConfigurerAdapter`
==== Provide a `WebSecurityConfigurerAdapter`
The following example shows how to provide a `WebSecurityConfigurerAdapter` with `@EnableWebSecurity` and enable OAuth 2.0 login through `httpSecurity.oauth2Login()`:
@ -770,7 +770,7 @@ public class OAuth2LoginSecurityConfig extends WebSecurityConfigurerAdapter {
[[jc-oauth2login-completely-override-autoconfiguration]]
===== Completely Override the Auto-configuration
==== Completely Override the Auto-configuration
The following example shows how to completely override the auto-configuration by both registering a `ClientRegistrationRepository` `@Bean` and providing a `WebSecurityConfigurerAdapter`, both of which were described in the two preceding sections.
@ -817,7 +817,7 @@ public class OAuth2LoginConfig {
----
[[jc-oauth2login-javaconfig-wo-boot]]
==== Java Configuration without Spring Boot 2.0
=== Java Configuration without Spring Boot 2.0
If you are not able to use Spring Boot 2.0 and would like to configure one of the pre-defined providers in `CommonOAuth2Provider` (for example, Google), apply the following configuration:
@ -859,7 +859,7 @@ public class OAuth2LoginConfig {
----
[[jc-oauth2login-authorized-client]]
==== OAuth2AuthorizedClient / OAuth2AuthorizedClientService
=== OAuth2AuthorizedClient / OAuth2AuthorizedClientService
`OAuth2AuthorizedClient` is a representation of an Authorized Client.
A client is considered to be authorized when the end-user (Resource Owner) has granted authorization to the client to access its protected resources.
@ -904,7 +904,7 @@ public class OAuth2LoginController {
[[jc-oauth2login-resources]]
==== Additional Resources
=== Additional Resources
The following additional resources describe advanced configuration options:
@ -921,13 +921,13 @@ The following additional resources describe advanced configuration options:
** <<oauth2login-advanced-oidc-user-service, OpenID Connect 1.0 UserService>>
[[jc-authentication]]
=== Authentication
== Authentication
Thus far we have only taken a look at the most basic authentication configuration.
Let's take a look at a few slightly more advanced options for configuring authentication.
[[jc-authentication-inmemory]]
==== In-Memory Authentication
=== In-Memory Authentication
We have already seen an example of configuring in-memory authentication for a single user.
Below is an example to configure multiple users:
@ -946,7 +946,7 @@ public UserDetailsService userDetailsService() throws Exception {
----
[[jc-authentication-jdbc]]
==== JDBC Authentication
=== JDBC Authentication
You can find the updates to support JDBC based authentication.
The example below assumes that you have already defined a `DataSource` within your application.
@ -970,7 +970,7 @@ public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception
}
----
==== LDAP Authentication
=== LDAP Authentication
You can find the updates to support LDAP based authentication.
The https://github.com/spring-projects/spring-security/tree/master/samples/javaconfig/ldap[ldap-javaconfig] sample provides a complete example of using LDAP based authentication.
@ -1038,7 +1038,7 @@ uniqueMember: uid=admin,ou=people,dc=springframework,dc=org
----
[[jc-authentication-authenticationprovider]]
==== AuthenticationProvider
=== AuthenticationProvider
You can define custom authentication by exposing a custom `AuthenticationProvider` as a bean.
For example, the following will customize authentication assuming that `SpringAuthenticationProvider` implements `AuthenticationProvider`:
@ -1054,7 +1054,7 @@ public SpringAuthenticationProvider springAuthenticationProvider() {
----
[[jc-authentication-userdetailsservice]]
==== UserDetailsService
=== UserDetailsService
You can define custom authentication by exposing a custom `UserDetailsService` as a bean.
For example, the following will customize authentication assuming that `SpringDataUserDetailsService` implements `UserDetailsService`:
@ -1080,7 +1080,7 @@ public BCryptPasswordEncoder passwordEncoder() {
}
----
=== Multiple HttpSecurity
== Multiple HttpSecurity
We can configure multiple HttpSecurity instances just as we can have multiple `<http>` blocks.
The key is to extend the `WebSecurityConfigurationAdapter` multiple times.
@ -1137,14 +1137,14 @@ This configuration is considered after `ApiWebSecurityConfigurationAdapter` sinc
[[jc-method]]
=== Method Security
== Method Security
From version 2.0 onwards Spring Security has improved support substantially for adding security to your service layer methods.
It provides support for JSR-250 annotation security as well as the framework's original `@Secured` annotation.
From 3.0 you can also make use of new <<el-access,expression-based annotations>>.
You can apply security to a single bean, using the `intercept-methods` element to decorate the bean declaration, or you can secure multiple beans across the entire service layer using the AspectJ style pointcuts.
==== EnableGlobalMethodSecurity
=== EnableGlobalMethodSecurity
We can enable annotation-based security using the `@EnableGlobalMethodSecurity` annotation on any `@Configuration` instance.
For example, the following would enable Spring Security's `@Secured` annotation.
@ -1214,7 +1214,7 @@ public Account post(Account account, double amount);
}
----
==== GlobalMethodSecurityConfiguration
=== GlobalMethodSecurityConfiguration
Sometimes you may need to perform operations that are more complicated than are possible with the `@EnableGlobalMethodSecurity` annotation allow.
For these instances, you can extend the `GlobalMethodSecurityConfiguration` ensuring that the `@EnableGlobalMethodSecurity` annotation is present on your subclass.
@ -1234,7 +1234,7 @@ public class MethodSecurityConfig extends GlobalMethodSecurityConfiguration {
For additional information about methods that can be overridden, refer to the `GlobalMethodSecurityConfiguration` Javadoc.
=== Post Processing Configured Objects
== Post Processing Configured Objects
Spring Security's Java Configuration does not expose every property of every object that it configures.
This simplifies the configuration for a majority of users.
@ -1262,7 +1262,7 @@ protected void configure(HttpSecurity http) throws Exception {
----
[[jc-custom-dsls]]
=== Custom DSLs
== Custom DSLs
You can provide your own custom DSLs in Spring Security.
For example, you might have something that looks like this:

View File

@ -1,9 +1,9 @@
[[ns-config]]
== Security Namespace Configuration
= Security Namespace Configuration
=== Introduction
== Introduction
Namespace configuration has been available since version 2.0 of the Spring Framework.
It allows you to supplement the traditional Spring beans application context syntax with elements from additional XML schema.
You can find more information in the Spring http://docs.spring.io/spring/docs/current/spring-framework-reference/htmlsingle/[Reference Documentation].
@ -59,7 +59,7 @@ xsi:schemaLocation="http://www.springframework.org/schema/beans
We'll assume this syntax is being used from now on in this chapter.
==== Design of the Namespace
=== Design of the Namespace
The namespace is designed to capture the most common uses of the framework and provide a simplified and concise syntax for enabling them within an application.
The design is based around the large-scale dependencies within the framework, and can be divided up into the following areas:
@ -81,14 +81,14 @@ The namespace provides supports for several standard options and also a means of
We'll see how to configure these in the following sections.
[[ns-getting-started]]
=== Getting Started with Security Namespace Configuration
== Getting Started with Security Namespace Configuration
In this section, we'll look at how you can build up a namespace configuration to use some of the main features of the framework.
Let's assume you initially want to get up and running as quickly as possible and add authentication support and access control to an existing web application, with a few test logins.
Then we'll look at how to change over to authenticating against a database or other security repository.
In later sections we'll introduce more advanced namespace configuration options.
[[ns-web-xml]]
==== web.xml Configuration
=== web.xml Configuration
The first thing you need to do is add the following filter declaration to your `web.xml` file:
[source,xml]
@ -112,7 +112,7 @@ Once you've added this to your `web.xml`, you're ready to start editing your app
Web security services are configured using the `<http>` element.
[[ns-minimal]]
==== A Minimal <http> Configuration
=== A Minimal <http> Configuration
All you need to enable web security to begin with is
[source,xml]
@ -138,13 +138,13 @@ In Spring Security 3.0, the attribute can also be populated with an pass:special
[NOTE]
====
===
You can use multiple `<intercept-url>` elements to define different access requirements for different sets of URLs, but they will be evaluated in the order listed and the first match will be used.
So you must put the most specific matches at the top.
You can also add a `method` attribute to limit the match to a particular HTTP method (`GET`, `POST`, `PUT` etc.).
====
===
To add some users, you can define a set of test data directly in the namespace:
@ -207,7 +207,7 @@ Try it out, or try experimenting with the "tutorial" sample application that com
[[ns-form-and-basic]]
==== Form and Basic Login Options
=== Form and Basic Login Options
You might be wondering where the login form came from when you were prompted to log in, since we made no mention of any HTML files or JSPs.
In fact, since we didn't explicitly set a URL for the login page, Spring Security generates one automatically, based on the features that are enabled and using standard values for the URL which processes the submitted login, the default target URL the user will be sent to after logging in and so on.
However, the namespace offers plenty of support to allow you to customize these options.
@ -263,7 +263,7 @@ Basic authentication will then take precedence and will be used to prompt for a
Form login is still available in this configuration if you wish to use it, for example through a login form embedded in another web page.
[[ns-form-target]]
===== Setting a Default Post-Login Destination
==== Setting a Default Post-Login Destination
If a form login isn't prompted by an attempt to access a protected resource, the `default-target-url` option comes into play.
This is the URL the user will be taken to after successfully logging in, and defaults to "/".
You can also configure things so that the user __always__ ends up at this page (regardless of whether the login was "on-demand" or they explicitly chose to log in) by setting the `always-use-default-target` attribute to "true".
@ -284,13 +284,13 @@ The referenced bean should be an instance of `AuthenticationSuccessHandler`.
You'll find more on this in the <<form-login-flow-handling,Core Filters>> chapter and also in the namespace appendix, as well as information on how to customize the flow when authentication fails.
[[ns-logout]]
==== Logout Handling
=== Logout Handling
The `logout` element adds support for logging out by navigating to a particular URL.
The default logout URL is `/logout`, but you can set it to something else using the `logout-url` attribute.
More information on other available attributes may be found in the namespace appendix.
[[ns-auth-providers]]
==== Using other Authentication Providers
=== Using other Authentication Providers
In practice you will need a more scalable source of user information than a few names added to the application context file.
Most likely you will want to store your user information in something like a database or an LDAP server.
LDAP namespace configuration is dealt with in the <<ldap,LDAP chapter>>, so we won't cover it here.
@ -347,7 +347,7 @@ You can use multiple `authentication-provider` elements, in which case the provi
See <<ns-auth-manager>> for more information on how the Spring Security `AuthenticationManager` is configured using the namespace.
[[ns-password-encoder]]
===== Adding a Password Encoder
==== Adding a Password Encoder
Passwords should always be encoded using a secure hashing algorithm designed for the purpose (not a standard algorithm like SHA or MD5).
This is supported by the `<password-encoder>` element.
With bcrypt encoded passwords, the original authentication provider configuration would look like this:
@ -377,14 +377,14 @@ bcrypt is a good choice for most cases, unless you have a legacy system which fo
If you are using a simple hashing algorithm or, even worse, storing plain text passwords, then you should consider migrating to a more secure option like bcrypt.
[[ns-web-advanced]]
=== Advanced Web Features
== Advanced Web Features
[[ns-remember-me]]
==== Remember-Me Authentication
=== Remember-Me Authentication
See the separate <<remember-me,Remember-Me chapter>> for information on remember-me namespace configuration.
[[ns-requires-channel]]
==== Adding HTTP/HTTPS Channel Security
=== Adding HTTP/HTTPS Channel Security
If your application supports both HTTP and HTTPS, and you require that particular URLs can only be accessed over HTTPS, then this is directly supported using the `requires-channel` attribute on `<intercept-url>`:
[source,xml]
@ -416,9 +416,9 @@ Note that in order to be truly secure, an application should not use HTTP at all
It should start in HTTPS (with the user entering an HTTPS URL) and use a secure connection throughout to avoid any possibility of man-in-the-middle attacks.
[[ns-session-mgmt]]
==== Session Management
=== Session Management
===== Detecting Timeouts
==== Detecting Timeouts
You can configure Spring Security to detect the submission of an invalid session ID and redirect the user to an appropriate URL.
This is achieved through the `session-management` element:
@ -444,7 +444,7 @@ You may be able to explicitly delete the JSESSIONID cookie on logging out, for e
Unfortunately this can't be guaranteed to work with every servlet container, so you will need to test it in your environment
[NOTE]
====
===
If you are running your application behind a proxy, you may also be able to remove the session cookie by configuring the proxy server.
For example, using Apache HTTPD's mod_headers, the following directive would delete the `JSESSIONID` cookie by expiring it in the response to a logout request (assuming the application is deployed under the path `/tutorial`):
@ -454,11 +454,11 @@ For example, using Apache HTTPD's mod_headers, the following directive would del
Header always set Set-Cookie "JSESSIONID=;Path=/tutorial;Expires=Thu, 01 Jan 1970 00:00:00 GMT"
</LocationMatch>
----
====
===
[[ns-concurrent-sessions]]
===== Concurrent Session Control
==== Concurrent Session Control
If you wish to place constraints on a single user's ability to log in to your application, Spring Security supports this out of the box with the following simple additions.
First you need to add the following listener to your `web.xml` file to keep Spring Security updated about session lifecycle events:
@ -505,7 +505,7 @@ If you are using a customized authentication filter for form-based login, then y
More details can be found in the <<session-mgmt,Session Management chapter>>.
[[ns-session-fixation]]
===== Session Fixation Attack Protection
==== Session Fixation Attack Protection
http://en.wikipedia.org/wiki/Session_fixation[Session fixation] attacks are a potential risk where it is possible for a malicious attacker to create a session by accessing a site, then persuade another user to log in with the same session (by sending them a link containing the session identifier as a parameter, for example).
Spring Security protects against this automatically by creating a new session or otherwise changing the session ID when a user logs in.
If you don't require this protection, or it conflicts with some other requirement, you can control the behavior using the `session-fixation-protection` attribute on `<session-management>`, which has four options
@ -531,7 +531,7 @@ See the <<session-mgmt,Session Management>> chapter for additional information.
[[ns-openid]]
==== OpenID Support
=== OpenID Support
The namespace supports http://openid.net/[OpenID] login either instead of, or in addition to normal form-based login, with a simple change:
[source,xml]
@ -556,7 +556,7 @@ Note that we have omitted the password attribute from the above user configurati
A random password will be generated internally, preventing you from accidentally using this user data as an authentication source elsewhere in your configuration.
===== Attribute Exchange
==== Attribute Exchange
Support for OpenID http://openid.net/specs/openid-attribute-exchange-1_0.html[attribute exchange].
As an example, the following configuration would attempt to retrieve the email and full name from the OpenID provider, for use by the application:
@ -591,12 +591,12 @@ See the OpenID sample application in the codebase for an example configuration,
[[ns-headers]]
==== Response Headers
=== Response Headers
For additional information on how to customize the headers element refer to the <<headers>> section of the reference.
[[ns-custom-filters]]
==== Adding in Your Own Filters
=== Adding in Your Own Filters
If you've used Spring Security before, you'll know that the framework maintains a chain of filters in order to apply its services.
You may want to add your own filters to the stack at particular locations or use a Spring Security filter for which there isn't currently a namespace configuration option (CAS, for example).
Or you might want to use a customized version of a standard namespace filter, such as the `UsernamePasswordAuthenticationFilter` which is created by the `<form-login>` element, taking advantage of some of the extra configuration options which are available by using the bean explicitly.
@ -606,11 +606,11 @@ The order of the filters is always strictly enforced when using the namespace.
When the application context is being created, the filter beans are sorted by the namespace handling code and the standard Spring Security filters each have an alias in the namespace and a well-known position.
[NOTE]
====
===
In previous versions, the sorting took place after the filter instances had been created, during post-processing of the application context.
In version 3.0+ the sorting is now done at the bean metadata level, before the classes have been instantiated.
This has implications for how you add your own filters to the stack as the entire filter list must be known during the parsing of the `<http>` element, so the syntax has changed slightly in 3.0.
====
===
The filters, aliases and namespace elements/attributes which create the filters are shown in <<filter-stack>>.
The filters are listed in the order in which they occur in the filter chain.
@ -713,7 +713,7 @@ The names "FIRST" and "LAST" can be used with the `position` attribute to indica
.Avoiding filter position conflicts
[TIP]
====
===
If you are inserting a custom filter which may occupy the same position as one of the standard filters created by the namespace then it's important that you don't include the namespace versions by mistake.
Remove any elements which create filters whose functionality you want to replace.
@ -722,13 +722,13 @@ Note that you can't replace filters which are created by the use of the `<http>`
Some other filters are added by default, but you can disable them.
An `AnonymousAuthenticationFilter` is added by default and unless you have <<ns-session-fixation,session-fixation protection>> disabled, a `SessionManagementFilter` will also be added to the filter chain.
====
===
If you're replacing a namespace filter which requires an authentication entry point (i.e. where the authentication process is triggered by an attempt by an unauthenticated user to access to a secured resource), you will need to add a custom entry point bean too.
[[ns-entry-point-ref]]
===== Setting a Custom AuthenticationEntryPoint
==== Setting a Custom AuthenticationEntryPoint
If you aren't using form login, OpenID or basic authentication through the namespace, you may want to define an authentication filter and entry point using a traditional bean syntax and link them into the namespace, as we've just seen.
The corresponding `AuthenticationEntryPoint` can be set using the `entry-point-ref` attribute on the `<http>` element.
@ -737,7 +737,7 @@ If you aren't familiar with authentication entry points, they are discussed in t
[[ns-method-security]]
=== Method Security
== Method Security
From version 2.0 onwards Spring Security has improved support substantially for adding security to your service layer methods.
It provides support for JSR-250 annotation security as well as the framework's original `@Secured` annotation.
From 3.0 you can also make use of new <<el-access,expression-based annotations>>.
@ -745,7 +745,7 @@ You can apply security to a single bean, using the `intercept-methods` element t
[[ns-global-method]]
==== The <global-method-security> Element
=== The <global-method-security> Element
This element is used to enable annotation-based security in your application (by setting the appropriate attributes on the element), and also to group together security pointcut declarations which will be applied across your entire application context.
You should only declare one `<global-method-security>` element.
The following declaration would enable support for Spring Security's `@Secured`:
@ -809,19 +809,19 @@ public Account post(Account account, double amount);
Expression-based annotations are a good choice if you need to define simple rules that go beyond checking the role names against the user's list of authorities.
[NOTE]
====
===
The annotated methods will only be secured for instances which are defined as Spring beans (in the same application context in which method-security is enabled).
If you want to secure instances which are not created by Spring (using the `new` operator, for example) then you need to use AspectJ.
====
===
[NOTE]
====
===
You can enable more than one type of annotation in the same application, but only one type should be used for any interface or class as the behaviour will not be well-defined otherwise.
If two annotations are found which apply to a particular method, then only one of them will be applied.
====
===
[[ns-protect-pointcut]]
===== Adding Security Pointcuts using protect-pointcut
==== Adding Security Pointcuts using protect-pointcut
The use of `protect-pointcut` is particularly powerful, as it allows you to apply security to many beans with only a simple declaration.
Consider the following example:
@ -840,7 +840,7 @@ As with URL matching, the most specific matches must come first in the list of p
Security annotations take precedence over pointcuts.
[[ns-access-manager]]
=== The Default AccessDecisionManager
== The Default AccessDecisionManager
This section assumes you have some knowledge of the underlying architecture for access-control within Spring Security.
If you don't you can skip it and come back to it later, as this section is only really relevant for people who need to do some customization in order to use more than simple role-based security.
@ -851,7 +851,7 @@ You can find out more about these in the chapter on <<authz-arch,authorization>>
[[ns-custom-access-mgr]]
==== Customizing the AccessDecisionManager
=== Customizing the AccessDecisionManager
If you need to use a more complicated access control strategy then it is easy to set an alternative for both method and web security.
For method security, you do this by setting the `access-decision-manager-ref` attribute on `global-method-security` to the `id` of the appropriate `AccessDecisionManager` bean in the application context:
@ -873,7 +873,7 @@ The syntax for web security is the same, but on the `http` element:
----
[[ns-auth-manager]]
=== The Authentication Manager and the Namespace
== The Authentication Manager and the Namespace
The main interface which provides authentication services in Spring Security is the `AuthenticationManager`.
This is usually an instance of Spring Security's `ProviderManager` class, which you may already be familiar with if you've used the framework before.
If not, it will be covered later, in the <<tech-intro-authentication,technical overview chapter>>.

View File

@ -11,5 +11,3 @@ To use the Spring Security test support, you must include `spring-security-test-
include::method.adoc[]
include::mockmvc.adoc[]
include::webtestclient.adoc[]

View File

@ -3,11 +3,14 @@ Ben Alex; Luke Taylor; Rob Winch; Gunnar Hillert; Joe Grandja; Jay Bryant
:include-dir: _includes
:security-api-url: http://docs.spring.io/spring-security/site/docs/current/apidocs/
:source-indent: 0
:tabsize: 2
:tabsize: 4
Spring Security is a powerful and highly customizable authentication and access-control framework.
It is the de-facto standard for securing Spring-based applications.
// FIXME: Add links for authentication, authorization, common attacks
Spring Security is a framework that provides authentication, authorization, and protection against common attacks.
// FIXME: Add links for imperative and reactive applications
With first class support for both imperative and reactive applications, it is the de-facto standard for securing Spring-based applications.
include::{include-dir}/preface/index.adoc[]
include::{include-dir}/servlet/index.adoc[]