### Example properties file entries
Source: https://docs.spring.io/spring-security/site/docs/3.1.x/reference/springsecurity-single.html
Example entries for the properties file, showing enabled users with roles.
```text
jimi=jimispassword,ROLE_USER,ROLE_ADMIN,enabled
bob=bobspassword,ROLE_USER,enabled
```
--------------------------------
### Example Output - Authentication Success and Failure
Source: https://docs.spring.io/spring-security/site/docs/3.1.x/reference/springsecurity-single.html
This is the console output from running the AuthenticationExample program. It shows a failed authentication with 'Bad Credentials' and a successful authentication with the security context containing the principal, protected password, and ROLE_USER authority.
```text
Please enter your username:
bob
Please enter your password:
password
Authentication failed: Bad Credentials
Please enter your username:
bob
Please enter your password:
bob
Successfully authenticated. Security context contains: \
org.springframework.security.authentication.UsernamePasswordAuthenticationToken@441d0230: \
Principal: bob; Password: [PROTECTED]; \
Authenticated: true; Details: null; \
Granted Authorities: ROLE_USER
```
--------------------------------
### Call a stateless service using a proxy ticket
Source: https://docs.spring.io/spring-security/site/docs/3.1.x/reference/springsecurity-single.html
Java servlet example showing how to obtain a proxy ticket from the CasAuthenticationToken and use it to call a stateless service. The proxy ticket can be reused for different target URLs.
```java
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
// NOTE: The CasAuthenticationToken can also be obtained using
// SecurityContextHolder.getContext().getAuthentication()
final CasAuthenticationToken token = (CasAuthenticationToken) request.getUserPrincipal();
// proxyTicket could be reused to make calls to the CAS service even if the
// target url differs
final String proxyTicket = token.getAssertion().getPrincipal().getProxyTicketFor(targetUrl);
// Make a remote call using the proxy ticket
final String serviceUrl = targetUrl+"?ticket="+URLEncoder.encode(proxyTicket, "UTF-8");
String proxyResponse = CommonUtils.getResponseFromServer(serviceUrl, "UTF-8");
...
}
```
--------------------------------
### Configure port mappings for non-standard HTTP/HTTPS ports
Source: https://docs.spring.io/spring-security/site/docs/3.1.x/reference/springsecurity-single.html
Use port-mappings to specify non-standard ports for HTTP and HTTPS. The example maps HTTP port 9080 to HTTPS port 9443.
```xml
...
```
--------------------------------
### BankService interface with @Secured annotations
Source: https://docs.spring.io/spring-security/site/docs/3.1.x/reference/springsecurity-single.html
Example interface showing @Secured annotations on methods. The annotations define access attributes passed to the AccessDecisionManager.
```java
public interface BankService {
@Secured("IS_AUTHENTICATED_ANONYMOUSLY")
public Account readAccount(Long id);
@Secured("IS_AUTHENTICATED_ANONYMOUSLY")
public Account[] findAccounts();
@Secured("ROLE_TELLER")
public Account post(Account account, double amount);
}
```
--------------------------------
### accesscontrollist tag example
Source: https://docs.spring.io/spring-security/site/docs/3.1.x/reference/springsecurity-single.html
Example of the `` tag. It checks if the current user has any of the permissions '1' or '2' on the given domain object. The tag body is evaluated if the user has any of the permissions. The permissions are converted to ACL `Permission` instances by the `PermissionFactory`.
```jsp
This will be shown if the user has either of the permissions
represented by the values "1" or "2" on the given object.
```
--------------------------------
### AuthenticationExample.java - Custom AuthenticationManager
Source: https://docs.spring.io/spring-security/site/docs/3.1.x/reference/springsecurity-single.html
This Java program demonstrates the authentication flow: it creates a UsernamePasswordAuthenticationToken, passes it to an AuthenticationManager, and sets the security context on success. The SampleAuthenticationManager accepts any username and password that are equal, assigning a single ROLE_USER authority. The output shows a failed and a successful authentication.
```java
import org.springframework.security.authentication.*;
import org.springframework.security.core.*;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.context.SecurityContextHolder;
public class AuthenticationExample {
private static AuthenticationManager am = new SampleAuthenticationManager();
public static void main(String[] args) throws Exception {
BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
while(true) {
System.out.println("Please enter your username:");
String name = in.readLine();
System.out.println("Please enter your password:");
String password = in.readLine();
try {
Authentication request = new UsernamePasswordAuthenticationToken(name, password);
Authentication result = am.authenticate(request);
SecurityContextHolder.getContext().setAuthentication(result);
break;
} catch(AuthenticationException e) {
System.out.println("Authentication failed: " + e.getMessage());
}
}
System.out.println("Successfully authenticated. Security context contains: " +
SecurityContextHolder.getContext().getAuthentication());
}
}
class SampleAuthenticationManager implements AuthenticationManager {
static final List AUTHORITIES = new ArrayList();
static {
AUTHORITIES.add(new SimpleGrantedAuthority("ROLE_USER"));
}
public Authentication authenticate(Authentication auth) throws AuthenticationException {
if (auth.getName().equals(auth.getCredentials())) {
return new UsernamePasswordAuthenticationToken(auth.getName(),
auth.getCredentials(), AUTHORITIES);
}
throw new BadCredentialsException("Bad Credentials");
}
}
```
--------------------------------
### Enable pre/post annotations with global-method-security
Source: https://docs.spring.io/spring-security/site/docs/3.1.x/reference/springsecurity-single.html
XML configuration element to enable @Pre and @Post annotations for method security.
```xml
```
--------------------------------
### Password Encoder with Salt Source
Source: https://docs.spring.io/spring-security/site/docs/3.1.x/reference/springsecurity-single.html
Shows how to configure a password encoder with a salt source using the username property.
```xml
```
--------------------------------
### FilterSecurityInterceptor with anonymous access for all URI patterns
Source: https://docs.spring.io/spring-security/site/docs/3.1.x/reference/springsecurity-single.html
Example of using FilterSecurityInterceptor to apply security to all URI patterns, allowing anonymous access to specific paths and requiring ROLE_USER for the rest. The 'securityMetadata' property defines intercept-url patterns.
```xml
" +
```
--------------------------------
### Configure BasicAuthenticationFilter and BasicAuthenticationEntryPoint
Source: https://docs.spring.io/spring-security/site/docs/3.1.x/reference/springsecurity-single.html
Adds a BasicAuthenticationFilter to the filter chain with an authenticationManager and an authenticationEntryPoint. The entry point is a BasicAuthenticationEntryPoint with a realmName. If authentication fails, the entry point returns a 401 response to retry authentication.
```xml
```
--------------------------------
### Enable remember-me with element
Source: https://docs.spring.io/spring-security/site/docs/3.1.x/reference/springsecurity-single.html
Adds the `` element inside the `` configuration to enable remember-me authentication. The UserDetailsService is normally selected automatically; if multiple exist, use the `user-service-ref` attribute to specify which bean to use.
```xml
...
```
--------------------------------
### Obtain current user name from SecurityContextHolder
Source: https://docs.spring.io/spring-security/site/docs/3.1.x/reference/springsecurity-single.html
Use this code anywhere in your application to get the name of the currently authenticated user. It retrieves the principal from the SecurityContextHolder and checks if it is a UserDetails instance to extract the username, otherwise falls back to the principal's toString().
```java
Object principal = SecurityContextHolder.getContext().getAuthentication().getPrincipal();
if (principal instanceof UserDetails) {
String username = ((UserDetails)principal).getUsername();
} else {
String username = principal.toString();
}
```
--------------------------------
### In-memory user-service with external properties file
Source: https://docs.spring.io/spring-security/site/docs/3.1.x/reference/springsecurity-single.html
Configures the user-service to load user definitions from an external properties file.
```xml
```
--------------------------------
### Load authorities with group-search-base
Source: https://docs.spring.io/spring-security/site/docs/3.1.x/reference/springsecurity-single.html
Configure authority loading from groups by using `group-search-base` along with `user-dn-pattern`. After successful authentication, a search is performed under the group base for entries with `uniqueMember` matching the user's DN. Authority names get `ROLE_` prefix by default.
```xml
```
--------------------------------
### Define users with authentication-manager and user-service
Source: https://docs.spring.io/spring-security/site/docs/3.1.x/reference/springsecurity-single.html
Adds test users directly in the namespace. The creates a DaoAuthenticationProvider and creates an InMemoryDaoImpl. All authentication-provider elements must be children of , which creates a ProviderManager.
```xml
```
--------------------------------
### JdbcDaoImpl Bean with user-service-ref
Source: https://docs.spring.io/spring-security/site/docs/3.1.x/reference/springsecurity-single.html
Shows how to define a JdbcDaoImpl bean and reference it via user-service-ref in the authentication provider.
```xml
```
--------------------------------
### Configure concurrency-control with error-if-maximum-exceeded=true
Source: https://docs.spring.io/spring-security/site/docs/3.1.x/reference/springsecurity-single.html
Adds concurrency-control with max-sessions="1" and error-if-maximum-exceeded="true" to reject a second login. The user is sent to the authentication-failure-url if form-based login is used, or an unauthorized (402) error is sent for non-interactive mechanisms like remember-me.
```xml
...
```
--------------------------------
### JdbcDaoImpl configuration with data source
Source: https://docs.spring.io/spring-security/site/docs/3.1.x/reference/springsecurity-single.html
Spring bean configuration for a JDBC-based UserDetailsService using JdbcDaoImpl and a DriverManagerDataSource.
```xml
```
--------------------------------
### Password Encoder with SHA and User Service
Source: https://docs.spring.io/spring-security/site/docs/3.1.x/reference/springsecurity-single.html
Shows how to add a password encoder with SHA hashing to an authentication provider that uses an in-memory user service.
```xml
```
--------------------------------
### JAAS login configuration file (/WEB-INF/login.conf)
Source: https://docs.spring.io/spring-security/site/docs/3.1.x/reference/springsecurity-single.html
Defines a JAAS login module configuration named 'JAASTest' that uses the sample.SampleLoginModule as required. This file is referenced by the JaasAuthenticationProvider's loginConfig property.
```plaintext
JAASTest {
sample.SampleLoginModule required;
};
```
--------------------------------
### auto-config shorthand expansion
Source: https://docs.spring.io/spring-security/site/docs/3.1.x/reference/springsecurity-single.html
Shows what the auto-config attribute expands to: form-login, http-basic, and logout elements. In anything other than very basic scenarios, it is better to omit auto-config and configure these explicitly.
```xml
```
--------------------------------
### Properties file format for user-service
Source: https://docs.spring.io/spring-security/site/docs/3.1.x/reference/springsecurity-single.html
The format for entries in the properties file: username=password,grantedAuthority[,grantedAuthority][,enabled|disabled]
```text
username=password,grantedAuthority[,grantedAuthority][,enabled|disabled]
```
--------------------------------
### CasAuthenticationProvider and user service configuration
Source: https://docs.spring.io/spring-security/site/docs/3.1.x/reference/springsecurity-single.html
Sets up the authentication manager with the CAS provider, the CasAuthenticationProvider with its ticket validator and user details service, and an in-memory user service. The provider uses the UserDetailsService for authorities, not for password authentication.
```xml
...
```
--------------------------------
### Bean configuration for TokenBasedRememberMeServices
Source: https://docs.spring.io/spring-security/site/docs/3.1.x/reference/springsecurity-single.html
XML bean definitions for enabling remember-me services with TokenBasedRememberMeServices. Includes RememberMeAuthenticationFilter, TokenBasedRememberMeServices, and RememberMeAuthenticationProvider. The key must match between the services and provider.
```xml
```
--------------------------------
### Configure external LDAP server with url attribute
Source: https://docs.spring.io/spring-security/site/docs/3.1.x/reference/springsecurity-single.html
Use the `` element with the `url` attribute to point to an external LDAP server. The URL includes the protocol, host, port, and base DN.
```xml
```
--------------------------------
### SQL to create persistent_logins table
Source: https://docs.spring.io/spring-security/site/docs/3.1.x/reference/springsecurity-single.html
The database must contain a 'persistent_logins' table with the specified columns. This SQL creates the table with username, series (primary key), token, and last_used timestamp.
```sql
create table persistent_logins (username varchar(64) not null,
series varchar(64) primary key,
token varchar(64) not null,
last_used timestamp not null)
```
--------------------------------
### CAS filter and entry point configuration
Source: https://docs.spring.io/spring-security/site/docs/3.1.x/reference/springsecurity-single.html
Configures the HTTP security to use the CAS entry point and adds the CAS filter. The CasAuthenticationFilter uses the authentication manager, and the CasAuthenticationEntryPoint points to the CAS login URL and the ServiceProperties bean.
```xml
...
```
--------------------------------
### User and Authorities Schema (HSQLDB)
Source: https://docs.spring.io/spring-security/site/docs/3.1.x/reference/springsecurity-single.html
DDL for the standard JDBC UserDetailsService (JdbcDaoImpl) to load passwords, account status, and authorities. Requires the users and authorities tables with a foreign key constraint and a unique index on username and authority.
```sql
create table users(
username varchar_ignorecase(50) not null primary key,
password varchar_ignorecase(50) not null,
enabled boolean not null);
create table authorities (
username varchar_ignorecase(50) not null,
authority varchar_ignorecase(50) not null,
constraint fk_authorities_users foreign key(username) references users(username));
create unique index ix_auth_username on authorities (username,authority);
```