Spring Security Learning (translated official documents)

Spring official document is the translation of this paper introduces the basic concepts and basic interface of the SS and principles.

Two core concepts of Spring Security: Authentication (verification); the Authorization (authorization); Spring Security can be used to achieve such authentication between OAuth, OpenID, LDAP, CAS, JAAS authorization system is like. If we can use Spring Security with OAuth achieve single sign-on.

Authentication verification

Authentication主要的接口是AuthenticationManager public interface AuthenticationManager { Authentication authenticate(Authentication authentication) throws AuthenticationException; }

authenticate () method call in three ways:

  1. Verified, a return to normal Authentication instance
  2. Authentication fails, throw AuthenticationException
  3. Can not decide, the most commonly used AuthenticationManager return null interface class is ProviderManager, internal ProviderManager will be entrusted to a series of verification AuthenticationProvider. AuthenticationProvider the interface a bit like AuthenticationManager interfaces, but he has an extra method allows the caller to determine whether a given Authentication support authentication instance type supports the method is the following method.
public interface AuthenticationProvider {
	Authentication authenticate(Authentication authentication) throws AuthenticationException;
	boolean supports(Class<?> authentication);
}
复制代码

ProviderManager will be entrusted to a series of verification AuthenticationProvider, it is actually a AuthenticationProvider list, so he can support multiple authentication policy in one application. When verification will traverse all AuthenticationProvider verified one by one, calling supports verification method to determine whether the type of Authentication, but in fact verification otherwise skip. If all AUthenticationProvider can not decide to return a null, then call the parent AuthenticationManager verification (if the parent is not empty). Sometimes in the application logic verification packets, each packet has its own the AuthenticationManager (usually is the ProviderManager), the packets that share a parent AuthenticationManager.

Custom AuthenticationManager

SpringSecurity configuration provides some helper classes to go and get AuthenticationManager features, the most commonly used is AuthenticationManagerBuilder, it can be in-memory, JDBC, LDAP configuration mode user details, or add custom UserDetailService. eg.

@Configuration
public class ApplicationSecurity extends WebSecurityConfigurerAdapter {
  @Autowired
  DataSource dataSource;
   ... // web stuff here
  @Override
  public configure(AuthenticationManagerBuilder builder) {
    builder.jdbcAuthentication().dataSource(dataSource).withUser("dave").password("secret").roles("USER");
  }
}
复制代码

??? spring to the official code examples are all right, configure method does not return type

Authorization Authorization

Authorization of authorized primary interface is AccessDecisionManager, provides a framework to achieve three categories: UnanimousBased (all through), ConsensusBased (majority), AffirmativeBased (no hair on through), all of these classes are to achieve a Power of Attorney to series AccessDecisionVoter, it's a bit like ProviderManager kind of verification entrusted to AuthenticationProvider. Here is the abstract AccessDecisionVoter voters.

public interface AccessDecisionVoter<S> {
    boolean supports(ConfigAttribute attribute);    
    boolean supports(Class<?> clazz);
    int vote(Authentication authentication, S object, Collection<ConfigAttribute> attributes);
}
复制代码

AccessDecisionVoter will consider a verification body Authentication and a security object is modified ConfigAttributes Object. Object is completely generic and in AccessDecisionManager AccessDecisionVoter the signature, on behalf of Object all things users might want to access (usually a network resource or Java class method calls in both cases). ConfigAttributes is also common, with some metadata to represent the modification of the security object, such metadata objects needed to determine access security permission levels. ConfigAttribute is an interface, it is only a very general way, and return String, so these strings encoded in some way the intent of the resource owner, express rules on who is allowed to access security objects. A typical ConfigAttribute is the user's role name (such as ROLE_ADMIN or ROLE_AUDIT), and they usually have a special format (such as ROLE_ prefix) or an expression representing the needs assessment. Most people just use the default implementation class AccessDecisionManager AffirmativeBased (no opposition is allowed to pass), any custom voters will happen in the body, or to add new or modify existing work. ConfigAttribute use EL expressions are very common, for example isFullyAuthenticated() && hasRole('FOO'), this is a can handle expression and create a context for their AccessDecisionVoter support. To extend the range of expression that can be handled, you need to customize SecurityExpressionRoot to achieve, and sometimes need SecurityExpressionHandler.

Web Security

Spring Security layer is used in the web-based Servlet filter, the figure shows a typical hierarchical single HTTP request handler.

When the client application sends a request to the application that the containers will be applied to find a filter according to the URI and Servlet route request. Can only have a Servlet to process the request, but is a chain of filters, the filter processing is in order, in fact, a filter if you want to deal with their own request to disconnect the filter chain. Filters can also modify the Request and Response filters used downstream. Order filter chain is important, Spring boot to provide a mechanism in 2: The first is the use of annotations or @Order realization Ordered interface, the other as part of FilterRegistrationBean, FilterRegistrationBean API itself is in order. Some ready-constants defined by the filter, to represent their order relative to one another system (e.g., the constant DEFAULT_ORDER SessionRepositoryFilter = Integer.MIN_VALUE + 50, which tells us that it like earlier in the chain, but it does not exclude other filters in before it). Spring Security filter chain is on a Spring Security access node as the inlet, the filter is the FilterChainProxy, as shown below:
Spring Security inserted in the request processing filter chain in a filter node the FilterChainProxy, At the name is a proxy filter chain, which through the process entrusted to the internal filter (here into the interior of Spring Security, hereinafter called safety filter device). In fact, even layer of security DelegatingFilterProxy in the filter, it is usually the agent between the standard and safety concerns filters, FilterChainProxy entrusted to it, it does not necessarily have to be a Spring bean, which is a Spring bean FilterChainProxy that is generally FilterChainProxy life cycle management to the Spring container. FilterChainProxy chain contains a list of filter, distribute requests to the first filter matched to the chain, the lower figure shows the scheduling requests based on the matching path, which is common, but not the only way to match the request. The scheduling process is the most important feature that only a chain of processing a request.

Create a custom filter chain

The default fallback filter chain (match / **) Spring Boot application predefined sequence (SecurityProperties.BASIC_AUTH_ORDER), you can security.basic.enabled = false to close it and you can use it as a fallback filters you only define filters to match the lower order of the other rules. To do this, simply add a WebSecurityConfigurerAdapter (or WebSecurityConfigurer) type of @Bean, use and modify the Class @Order comment. E.g:

@Configuration
@Order(SecurityProperties.BASIC_AUTH_ORDER - 10)
public class ApplicationConfigurerAdapter extends WebSecurityConfigurerAdapter {
  @Override
  protected void configure(HttpSecurity http) throws Exception {
    http.antMatcher("/foo/**")
     ...;
  }
}
复制代码

And matching the authorization request scheduling

Safety filter chain (or equivalent WebSecurityConfigurerAdapter) there is a matching request, for determining whether to apply a HTTP request. Once the decision to apply a particular filter chain, will not be applied to other filter chain. But in the filter chain, you can set an extra match in HttpSecurity Configurator to more fine-grained control over the authorization. Example:

@Configuration
@Order(SecurityProperties.BASIC_AUTH_ORDER - 10)
public class ApplicationConfigurerAdapter extends WebSecurityConfigurerAdapter {
  @Override
  protected void configure(HttpSecurity http) throws Exception {
    http.antMatcher("/foo/**")
        .authorizeRequests()
        .antMatchers("/foo/bar").hasRole("BAR")
        .antMatchers("/foo/spam").hasRole("SPAM")
       .anyRequest().isAuthenticated();
  }
}
复制代码

A misconfigured Spring Security is most likely to commit forget these matches are suitable for different process, a request is matcher entire filter chain, just select another access rule to apply.

The application of safety rules and the rules for the implementation of the combination involves Spring Boot Actuator content, for the time being skipped

Methods security

In addition to supporting web application, Spring Security also supports Java application access rules to the method of execution. For Sping Security just does not make sense for the type of resource protection. For users, this means using the same format ConfigAttribute strings (such as roles or expression) statement access rules, but in different locations in the code. The first step is to make safe method to take effect, such as:

@SpringBootApplication
@EnableGlobalMethodSecurity(securedEnabled = true)
public class SampleSecureApplication {
}
复制代码

Then we can direct resources modification methods, such as:

@Service
public class MyService {
  @Secured("ROLE_USER")
  public String secure() {
    return "Hello Security";
  }
}
复制代码

This example is a safe method of service. If Spring to create this type of @Bean, it will be the agent, the caller must pass through security interceptors before the actual execution method. If access is denied, the caller will receive AccessDeniedException exception rather than the actual method results. There are other annotation methods can be used to enforce security constraints, especially @PreAuthorize and @PostAuthorize, they allow you to write each contain method parameters and return values ​​of an expression references.

Working with Threads

Spring Security is fundamentally a thread-bound, because it is necessary to subject the current authenticated to a variety of downstream consumers is available, the basic building blocks are SecurityContext, it may contain Authentication (when the user logs in, it is a verification by the Authentication). You can always access and manipulate SecurityContext by the SecurityContextHolder static convenient method. E.g:

SecurityContext context = SecurityContextHolder.getContext();
Authentication authentication = context.getAuthentication();
assert(authentication.isAuthenticated);
复制代码

If you need to access the network endpoint user is currently authenticated, you can use parameters in @RequestMapping, for example:

@RequestMapping("/foo")
public String foo(@AuthenticationPrincipal User user) {
  ... // do stuff with user
}
复制代码

When the comment is drawn from the Authentication SecurityContext and call on their getPrincipal () method to produce a method parameter. Authentication depends on the type of Principal AuthenticationManager used to verify authentication, so this might be a reference to obtain useful tips on the type of user data security. If you are using Spring Security Principal from the HttpServletRequest, it will be Authentication type, so you can use it directly:

@RequestMapping("/foo")
public String foo(Principal principal) {
  Authentication authentication = (Authentication) principal;
  User = (User) authentication.getPrincipal();
  ... // do stuff with user
}
复制代码

Processing Secure Methods Asynchronously

Since SecurityContext is thread-bound, if you want to perform background processing any calls security methods, such as using @Async, you need to make sure that the context be disseminated. This can be attributed to the packaging SecurityContext with the task (Runnable, Callable, etc.), in the background. Spring Security provides a number of assistants to simplify the process, such as Runnable and Callable wrapper. To SecurityContext spread to @Async method, you need to provide a AsyncConfigurer, and indeed Executor of the correct type:

@Configuration
public class ApplicationConfiguration extends AsyncConfigurerSupport {
  @Override
  public Executor getAsyncExecutor() {
    return new DelegatingSecurityContextExecutorService(Executors.newFixedThreadPool(5));
  }
}
复制代码

Reproduced in: https: //juejin.im/post/5cf09fa46fb9a07eaf2b7709

Guess you like

Origin blog.csdn.net/weixin_33912453/article/details/91434321