Security Core

The main class that keeps authorization data is SecurityContextHolder, saves the detail of Principal object.

Object principal = SecurityContextHolder.getContext().getAuthentication().getPrincipal();

if (principal instanceof UserDetails) {
String username = ((UserDetails)principal).getUsername();
} else {
String username = principal.toString();
}

The method Authentication.getAuthorities() returns an array of GrantedAuthorities, that consists on an authorization granted to the Principal.

Access-control decisions are made by AccessDecisionManager decide(Authentication authentication, Object object, Collection<ConfigAttribute> configAttributes) this object contains references to Authentication, secure object and security metadata.

Simple authentication example

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<GrantedAuthority> AUTHORITIES = new ArrayList<GrantedAuthority>();

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");
}
}

UserDetails/UserDetailsService

UserDetails user-specific data, if a DaoAuthenticatorProvider is available, it’s retrieved using a implement of UserDetailsService.

UserDetails loadUserByUsername(String username) throws UsernameNotFoundException;

AuthenticationManager

AuthenticationManager is the interface that provides authentication services in Spring Security, the default is ProviderManager.

Authentication authenticate(Authentication)

ProviderManager run a list of access manager strategies until it finds one suitable (DaoAuthenticationProvider, LdapAuthentication, ..).

DaoAuthenticationProvider has two main attributes: userDetailsService and passwordEncoder.

Session Management

Session authentication management is made upon a SessionAuthenticationStrategy, that contains two filters:

a. SessionManagementFilter that manages HttpSession.

b. AbstractAuthenticationProcessingFilter that can be customized for each request. e.g. UsernamePasswordAuthenticationFilter extends AbstractAuthenticationProcessingFilter overriding methods:

public Authentication attemptAuthentication(HttpServletRequest request, HttpServletResponse response) throws AuthenticationException

void successfulAuthentication(HttpServletRequest request, HttpServletResponse response, FilterChain chain, Authentication authResult)

SpringBoot Security

The annotation @EnableWebSecurity allows the configuration of a WebSecurityConfigureInstance.

A WebSecurityAdapter contains configuration for two filters:

configure(HttpSecurity) – configuration of web based resources.

configure(WebSecurity) – settings that implement global security settings that override resource lever configuration, used for example to allow access to static resources in the overall application.