In depth understanding of httpsecurity

depth understanding httpsecurity


HttpSecurity It's also Spring Security An important part of . Most of what we usually do Spring Security Configuration is also based on HttpSecurity To configure the . Therefore, we need to understand from the perspective of source code HttpSecurity What did you do ?

1. The whole

So let's look at this first HttpSecurity The inheritance diagram of :

You can see ,HttpSecurity Inherited from AbstractConfiguredSecurityBuilder, At the same time SecurityBuilder and HttpSecurityBuilder Two interfaces .

Let's see HttpSecurity The definition of :

public final class HttpSecurity extends
AbstractConfiguredSecurityBuilder<DefaultSecurityFilterChain, HttpSecurity>
implements SecurityBuilder<DefaultSecurityFilterChain>,
HttpSecurityBuilder<HttpSecurity> {

//...
}

Every class here has generics , It's a bit dazzled .

I'll take this generic class and tell you about it , My friends will understand .

Generics are mainly two ,DefaultSecurityFilterChain and HttpSecurity,HttpSecurity Not to mention , This is our leading role today , that DefaultSecurityFilterChain do ?

So we have to start with SecurityFilterChain Speaking of it .

1.1 SecurityFilterChain

Let's look at the definition first :

public interface SecurityFilterChain {

boolean matches(HttpServletRequest request);
List<Filter> getFilters();
}

SecurityFilterChain In fact, it's what we usually call Spring Security Filter chain in , It defines two methods , One is matches Method is used to match the request , Another one getFilters Method returns a List aggregate , In the collection Filter object , When a request comes , use matches Method to compare whether the request matches the current chain , If it fits , Just go back to getFilters Filter in method , Then the current request will go through List Filters in the collection . This point , Friends can recall the front 【 In depth understanding of FilterChainProxy【 Source article 】】 One article .

SecurityFilterChain Interface has only one implementation class , That's it DefaultSecurityFilterChain:

public final class DefaultSecurityFilterChain implements SecurityFilterChain {

private static final Log logger = LogFactory.getLog(DefaultSecurityFilterChain.class);
private final RequestMatcher requestMatcher;
private final List<Filter> filters;
public DefaultSecurityFilterChain(RequestMatcher requestMatcher, Filter... filters) {

this(requestMatcher, Arrays.asList(filters));
}
public DefaultSecurityFilterChain(RequestMatcher requestMatcher, List<Filter> filters) {

logger.info("Creating filter chain: " + requestMatcher + ", " + filters);
this.requestMatcher = requestMatcher;
this.filters = new ArrayList<>(filters);
}
public RequestMatcher getRequestMatcher() {

return requestMatcher;
}
public List<Filter> getFilters() {

return filters;
}
public boolean matches(HttpServletRequest request) {

return requestMatcher.matches(request);
}
@Override
public String toString() {

return "[ " + requestMatcher + ", " + filters + "]";
}
}

DefaultSecurityFilterChain Just for SecurityFilterChain The method in is implemented , There's nothing special to say , SongGe is no longer wordy .

So from the introduction above , You can see ,DefaultSecurityFilterChain In fact, it's quite so Spring Security Filter chain in , One DefaultSecurityFilterChain Represents a filter chain , If there are multiple filter chains in the system , There will be many DefaultSecurityFilterChain object .

Next, we will HttpSecurity Let's touch these parents .

1.2 SecurityBuilder

public interface SecurityBuilder<O> {

O build() throws Exception;
}

SecurityBuilder Is used to build the filter chain , stay HttpSecurity Realization SecurityBuilder when , The generic type passed in is DefaultSecurityFilterChain, therefore SecurityBuilder#build The function of the method is very clear , It is used to build a filter chain .

1.3 HttpSecurityBuilder

HttpSecurityBuilder The name is used to build HttpSecurity Of . But it's just an interface , The specific implementation is HttpSecurity in , The interface is defined as follows :

public interface HttpSecurityBuilder<H extends HttpSecurityBuilder<H>> extends
SecurityBuilder<DefaultSecurityFilterChain> {

<C extends SecurityConfigurer<DefaultSecurityFilterChain, H>> C getConfigurer(
Class<C> clazz);
<C extends SecurityConfigurer<DefaultSecurityFilterChain, H>> C removeConfigurer(
Class<C> clazz);
<C> void setSharedObject(Class<C> sharedType, C object);
<C> C getSharedObject(Class<C> sharedType);
H authenticationProvider(AuthenticationProvider authenticationProvider);
H userDetailsService(UserDetailsService userDetailsService) throws Exception;
H addFilterAfter(Filter filter, Class<? extends Filter> afterFilter);
H addFilterBefore(Filter filter, Class<? extends Filter> beforeFilter);
H addFilter(Filter filter);
}

The method here is relatively simple :

  1. getConfigurer Get a configuration object .Spring Security All filter objects in the filter chain are created by xxxConfigure To configure , Here's how to get this xxxConfigure object .
  2. removeConfigurer Remove a configuration object .
  3. setSharedObject/getSharedObject To configure / Get by multiple SecurityConfigurer Shared objects .
  4. authenticationProvider Method represents the configuration validator .
  5. userDetailsService Configure the data source interface .
  6. addFilterAfter Add a filter before a filter .
  7. addFilterBefore Add a filter after a filter .
  8. addFilter Add a filter , The filter must be a filter in the existing filter chain or its extension .

This is HttpSecurityBuilder The function of , These interfaces are in HttpSecurity All will be realized .

1.4 AbstractSecurityBuilder

AbstractSecurityBuilder Class implements the SecurityBuilder Interface , One of the main things that this class does , Is to make sure that the entire build is only built once .

public abstract class AbstractSecurityBuilder<O> implements SecurityBuilder<O> {

private AtomicBoolean building = new AtomicBoolean();
private O object;
public final O build() throws Exception {

if (this.building.compareAndSet(false, true)) {

this.object = doBuild();
return this.object;
}
throw new AlreadyBuiltException("This object has already been built");
}
public final O getObject() {

if (!this.building.get()) {

throw new IllegalStateException("This object has not been built");
}
return this.object;
}
protected abstract O doBuild() throws Exception;
}

You can see , This redefines build Method , And set up build Method is final type , Can't be rewritten , stay build In the method , adopt AtomicBoolean The implementation of this method is called only once . The concrete construction logic defines a new abstract method doBuild, In the future, we will use doBuild Method definition build logic .

1.5 AbstractConfiguredSecurityBuilder

AbstractSecurityBuilder The implementation class of the method is AbstractConfiguredSecurityBuilder.

AbstractConfiguredSecurityBuilder There's a lot more to be done in , Let's look at .

First AbstractConfiguredSecurityBuilder An enumeration class is defined in , Divide the whole construction process into 5 States , It can also be understood as the five phases of the construction process life cycle , as follows :

private enum BuildState {

UNBUILT(0),
INITIALIZING(1),
CONFIGURING(2),
BUILDING(3),
BUILT(4);
private final int order;
BuildState(int order) {

this.order = order;
}
public boolean isInitializing() {

return INITIALIZING.order == order;
}
public boolean isConfigured() {

return order >= CONFIGURING.order;
}
}

The five states are UNBUILT、INITIALIZING、CONFIGURING、BUILDING as well as BUILT. There are also two ways to judge ,isInitializing Determine whether initialization is in progress ,isConfigured Indicates whether the configuration has been completed .

AbstractConfiguredSecurityBuilder There are many methods in , SongGe here listed two key methods and everyone's analysis :

private <C extends SecurityConfigurer<O, B>> void add(C configurer) {

Assert.notNull(configurer, "configurer cannot be null");
Class<? extends SecurityConfigurer<O, B>> clazz = (Class<? extends SecurityConfigurer<O, B>>) configurer
.getClass();
synchronized (configurers) {

if (buildState.isConfigured()) {

throw new IllegalStateException("Cannot apply " + configurer
+ " to already built object");
}
List<SecurityConfigurer<O, B>> configs = allowConfigurersOfSameType ? this.configurers
.get(clazz) : null;
if (configs == null) {

configs = new ArrayList<>(1);
}
configs.add(configurer);
this.configurers.put(clazz, configs);
if (buildState.isInitializing()) {

this.configurersAddedInInitializing.add(configurer);
}
}
}
private Collection<SecurityConfigurer<O, B>> getConfigurers() {

List<SecurityConfigurer<O, B>> result = new ArrayList<>();
for (List<SecurityConfigurer<O, B>> configs : this.configurers.values()) {

result.addAll(configs);
}
return result;
}

The first one is this add Method , This is equivalent to collecting all configuration classes . Will all xxxConfigure Collect it and store it in configurers in , In the future, it will be initialized and configured in a unified way ,configurers Itself is a LinkedHashMap ,key It's a configuration class class,value It's a collection , There's... In the collection xxxConfigure Configuration class . When these configuration classes need to be configured centrally , Will pass getConfigurers Method to get the configuration class , This acquisition process is to put LinkedHashMap Medium value Take it out , Put it in a collection and return .

Another way is doBuild Method .

@Override
protected final O doBuild() throws Exception {

synchronized (configurers) {

buildState = BuildState.INITIALIZING;
beforeInit();
init();
buildState = BuildState.CONFIGURING;
beforeConfigure();
configure();
buildState = BuildState.BUILDING;
O result = performBuild();
buildState = BuildState.BUILT;
return result;
}
}
private void init() throws Exception {

Collection<SecurityConfigurer<O, B>> configurers = getConfigurers();
for (SecurityConfigurer<O, B> configurer : configurers) {

configurer.init((B) this);
}
for (SecurityConfigurer<O, B> configurer : configurersAddedInInitializing) {

configurer.init((B) this);
}
}
private void configure() throws Exception {

Collection<SecurityConfigurer<O, B>> configurers = getConfigurers();
for (SecurityConfigurer<O, B> configurer : configurers) {

configurer.configure((B) this);
}
}

stay AbstractSecurityBuilder Class , The construction of filters is transferred to doBuild The method is up to , But in the AbstractSecurityBuilder It just defines abstract doBuild Method , The specific implementation is AbstractConfiguredSecurityBuilder.

doBuild The way to do this is to update the status , To initialize .

beforeInit It's a reserved method , There is no implementation .

init The way is to find all the xxxConfigure, Call them one by one init Method to initialize .

beforeConfigure It's a reserved method , There is no implementation .

configure The way is to find all the xxxConfigure, Call them one by one configure Method to configure .

And finally performBuild Method , It's a real filter chain building method , But in AbstractConfiguredSecurityBuilder in performBuild Method is just an abstract method , The specific implementation is HttpSecurity in .

This is HttpSecurity All parent classes 、 The function of the parent interface .

After watching my parents , Let's go back to the topic of today's article ,HttpSecurity.

2. HttpSecurity

HttpSecurity Do the things , It's all kinds of xxxConfigurer To configure .

Just a few examples :

public CorsConfigurer<HttpSecurity> cors() throws Exception {

return getOrApply(new CorsConfigurer<>());
}
public CsrfConfigurer<HttpSecurity> csrf() throws Exception {

ApplicationContext context = getContext();
return getOrApply(new CsrfConfigurer<>(context));
}
public ExceptionHandlingConfigurer<HttpSecurity> exceptionHandling() throws Exception {

return getOrApply(new ExceptionHandlingConfigurer<>());
}

HttpSecurity There are a lot of similar methods in , The filters in the filter chain are configured one by one . I will not introduce them one by one .

At the end of each configuration method is a sentence getOrApply, What's this for ?

private <C extends SecurityConfigurerAdapter<DefaultSecurityFilterChain, HttpSecurity>> C getOrApply(
C configurer) throws Exception {

C existingConfig = (C) getConfigurer(configurer.getClass());
if (existingConfig != null) {

return existingConfig;
}
return apply(configurer);
}

getConfigurer Method is in its parent class AbstractConfiguredSecurityBuilder As defined in , The goal is to look at the current xxxConfigurer Whether it has been configured .

If at present xxxConfigurer It's already configured , Then return directly , Otherwise, call apply Method , This apply Method will eventually call AbstractConfiguredSecurityBuilder#add Method , Set the current configuration configurer Gather up .

HttpSecurity One more addFilter Method :

public HttpSecurity addFilter(Filter filter) {

Class<? extends Filter> filterClass = filter.getClass();
if (!comparator.isRegistered(filterClass)) {

throw new IllegalArgumentException(
"The Filter class "
+ filterClass.getName()
+ " does not have a registered order and cannot be added without a specified order. Consider using addFilterBefore or addFilterAfter instead.");
}
this.filters.add(filter);
return this;
}

This addFilter The role of methods , Mainly in various xxxConfigurer When configuring , This method will be called ,(xxxConfigurer It is used to configure the filter ), hold Filter All added to fitlers variable .

In the end in HttpSecurity Of performBuild In the method , Build a chain of filters :

@Override
protected DefaultSecurityFilterChain performBuild() {

filters.sort(comparator);
return new DefaultSecurityFilterChain(requestMatcher, filters);
}

Sort the filters first , And then construct DefaultSecurityFilterChain object .

3. Summary

All right. , This is it. HttpSecurity A general workflow of . Grasp the workflow , All that's left is a few simple repetitions xxxConfigurer Configured with , SongGe is no longer wordy .

If you guys think you've got something , Remember to watch and encourage brother song ~

版权声明
本文为[A kind of A little rain in the south of the Yangtze River]所创,转载请带上原文链接,感谢

  1. [front end -- JavaScript] knowledge point (IV) -- memory leakage in the project (I)
  2. This mechanism in JS
  3. Vue 3.0 source code learning 1 --- rendering process of components
  4. Learning the realization of canvas and simple drawing
  5. gin里获取http请求过来的参数
  6. vue3的新特性
  7. Get the parameters from HTTP request in gin
  8. New features of vue3
  9. vue-cli 引入腾讯地图(最新 api,rocketmq原理面试
  10. Vue 学习笔记(3,免费Java高级工程师学习资源
  11. Vue 学习笔记(2,Java编程视频教程
  12. Vue cli introduces Tencent maps (the latest API, rocketmq)
  13. Vue learning notes (3, free Java senior engineer learning resources)
  14. Vue learning notes (2, Java programming video tutorial)
  15. 【Vue】—props属性
  16. 【Vue】—创建组件
  17. [Vue] - props attribute
  18. [Vue] - create component
  19. 浅谈vue响应式原理及发布订阅模式和观察者模式
  20. On Vue responsive principle, publish subscribe mode and observer mode
  21. 浅谈vue响应式原理及发布订阅模式和观察者模式
  22. On Vue responsive principle, publish subscribe mode and observer mode
  23. Xiaobai can understand it. It only takes 4 steps to solve the problem of Vue keep alive cache component
  24. Publish, subscribe and observer of design patterns
  25. Summary of common content added in ES6 + (II)
  26. No.8 Vue element admin learning (III) vuex learning and login method analysis
  27. Write a mini webpack project construction tool
  28. Shopping cart (front-end static page preparation)
  29. Introduction to the fluent platform
  30. Webpack5 cache
  31. The difference between drop-down box select option and datalist
  32. CSS review (III)
  33. Node.js学习笔记【七】
  34. Node.js learning notes [VII]
  35. Vue Router根据后台数据加载不同的组件(思考-&gt;实现-&gt;不止于实现)
  36. Vue router loads different components according to background data (thinking - & gt; Implementation - & gt; (more than implementation)
  37. 【JQuery框架,Java编程教程视频下载
  38. [jQuery framework, Java programming tutorial video download
  39. Vue Router根据后台数据加载不同的组件(思考-&gt;实现-&gt;不止于实现)
  40. Vue router loads different components according to background data (thinking - & gt; Implementation - & gt; (more than implementation)
  41. 【Vue,阿里P8大佬亲自教你
  42. 【Vue基础知识总结 5,字节跳动算法工程师面试经验
  43. [Vue, Ali P8 teaches you personally
  44. [Vue basic knowledge summary 5. Interview experience of byte beating Algorithm Engineer
  45. 【问题记录】- 谷歌浏览器 Html生成PDF
  46. [problem record] - PDF generated by Google browser HTML
  47. 【问题记录】- 谷歌浏览器 Html生成PDF
  48. [problem record] - PDF generated by Google browser HTML
  49. 【JavaScript】查漏补缺 —数组中reduce()方法
  50. [JavaScript] leak checking and defect filling - reduce() method in array
  51. 【重识 HTML (3),350道Java面试真题分享
  52. 【重识 HTML (2),Java并发编程必会的多线程你竟然还不会
  53. 【重识 HTML (1),二本Java小菜鸟4面字节跳动被秒成渣渣
  54. [re recognize HTML (3) and share 350 real Java interview questions
  55. [re recognize HTML (2). Multithreading is a must for Java Concurrent Programming. How dare you not
  56. [re recognize HTML (1), two Java rookies' 4-sided bytes beat and become slag in seconds
  57. 【重识 HTML ,nginx面试题阿里
  58. 【重识 HTML (4),ELK原来这么简单
  59. [re recognize HTML, nginx interview questions]
  60. [re recognize HTML (4). Elk is so simple