authorization.adoc 52 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674
  1. = Authorization Migrations
  2. The following steps relate to changes around how authorization is performed.
  3. == Use `AuthorizationManager` for Method Security
  4. xref:servlet/authorization/method-security.adoc[Method Security] has been xref:servlet/authorization/method-security.adoc#jc-enable-method-security[simplified] through {security-api-url}org/springframework/security/authorization/AuthorizationManager.html[the `AuthorizationManager` API] and direct use of Spring AOP.
  5. Should you run into trouble with making these changes, note that `@EnableGlobalMethodSecurity`, while deprecated, will not be removed in 6.0, allowing you to opt out by sticking with the old annotation.
  6. [[servlet-replace-globalmethodsecurity-with-methodsecurity]]
  7. === Replace xref:servlet/authorization/method-security.adoc#jc-enable-global-method-security[global method security] with xref:servlet/authorization/method-security.adoc#jc-enable-method-security[method security]
  8. {security-api-url}org/springframework/security/config/annotation/method/configuration/EnableGlobalMethodSecurity.html[`@EnableGlobalMethodSecurity`] and xref:servlet/appendix/namespace/method-security.adoc#nsa-global-method-security[`<global-method-security>`] are deprecated in favor of {security-api-url}org/springframework/security/config/annotation/method/configuration/EnableMethodSecurity.html[`@EnableMethodSecurity`] and xref:servlet/appendix/namespace/method-security.adoc#nsa-method-security[`<method-security>`], respectively.
  9. The new annotation and XML element activate Spring's xref:servlet/authorization/method-security.adoc#jc-enable-method-security[pre-post annotations] by default and use `AuthorizationManager` internally.
  10. This means that the following two listings are functionally equivalent:
  11. ====
  12. .Java
  13. [source,java,role="primary"]
  14. ----
  15. @EnableGlobalMethodSecurity(prePostEnabled = true)
  16. ----
  17. .Kotlin
  18. [source,kotlin,role="secondary"]
  19. ----
  20. @EnableGlobalMethodSecurity(prePostEnabled = true)
  21. ----
  22. .Xml
  23. [source,xml,role="secondary"]
  24. ----
  25. <global-method-security pre-post-enabled="true"/>
  26. ----
  27. ====
  28. and:
  29. ====
  30. .Java
  31. [source,java,role="primary"]
  32. ----
  33. @EnableMethodSecurity
  34. ----
  35. .Kotlin
  36. [source,kotlin,role="secondary"]
  37. ----
  38. @EnableMethodSecurity
  39. ----
  40. .Xml
  41. [source,xml,role="secondary"]
  42. ----
  43. <method-security/>
  44. ----
  45. ====
  46. For applications not using the pre-post annotations, make sure to turn it off to avoid activating unwanted behavior.
  47. For example, a listing like:
  48. ====
  49. .Java
  50. [source,java,role="primary"]
  51. ----
  52. @EnableGlobalMethodSecurity(securedEnabled = true)
  53. ----
  54. .Kotlin
  55. [source,kotlin,role="secondary"]
  56. ----
  57. @EnableGlobalMethodSecurity(securedEnabled = true)
  58. ----
  59. .Xml
  60. [source,xml,role="secondary"]
  61. ----
  62. <global-method-security secured-enabled="true"/>
  63. ----
  64. ====
  65. should change to:
  66. ====
  67. .Java
  68. [source,java,role="primary"]
  69. ----
  70. @EnableMethodSecurity(securedEnabled = true, prePostEnabled = false)
  71. ----
  72. .Kotlin
  73. [source,kotlin,role="secondary"]
  74. ----
  75. @EnableMethodSecurity(securedEnabled = true, prePostEnabled = false)
  76. ----
  77. .Xml
  78. [source,xml,role="secondary"]
  79. ----
  80. <method-security secured-enabled="true" pre-post-enabled="false"/>
  81. ----
  82. ====
  83. === Use a Custom `@Bean` instead of subclassing `DefaultMethodSecurityExpressionHandler`
  84. As a performance optimization, a new method was introduced to `MethodSecurityExpressionHandler` that takes a `Supplier<Authentication>` instead of an `Authentication`.
  85. This allows Spring Security to defer the lookup of the `Authentication`, and is taken advantage of automatically when you use `@EnableMethodSecurity` instead of `@EnableGlobalMethodSecurity`.
  86. However, let's say that your code extends `DefaultMethodSecurityExpressionHandler` and overrides `createSecurityExpressionRoot(Authentication, MethodInvocation)` to return a custom `SecurityExpressionRoot` instance.
  87. This will no longer work because the arrangement that `@EnableMethodSecurity` sets up calls `createEvaluationContext(Supplier<Authentication>, MethodInvocation)` instead.
  88. Happily, such a level of customization is often unnecessary.
  89. Instead, you can create a custom bean with the authorization methods that you need.
  90. For example, let's say you are wanting a custom evaluation of `@PostAuthorize("hasAuthority('ADMIN')")`.
  91. You can create a custom `@Bean` like this one:
  92. ====
  93. .Java
  94. [source,java,role="primary"]
  95. ----
  96. class MyAuthorizer {
  97. boolean isAdmin(MethodSecurityExpressionOperations root) {
  98. boolean decision = root.hasAuthority("ADMIN");
  99. // custom work ...
  100. return decision;
  101. }
  102. }
  103. ----
  104. .Kotlin
  105. [source,kotlin,role="secondary"]
  106. ----
  107. class MyAuthorizer {
  108. fun isAdmin(val root: MethodSecurityExpressionOperations): boolean {
  109. val decision = root.hasAuthority("ADMIN");
  110. // custom work ...
  111. return decision;
  112. }
  113. }
  114. ----
  115. ====
  116. and then refer to it in the annotation like so:
  117. ====
  118. .Java
  119. [source,java,role="primary"]
  120. ----
  121. @PreAuthorize("@authz.isAdmin(#root)")
  122. ----
  123. .Kotlin
  124. [source,kotlin,role="secondary"]
  125. ----
  126. @PreAuthorize("@authz.isAdmin(#root)")
  127. ----
  128. ====
  129. ==== I'd still prefer to subclass `DefaultMethodSecurityExpressionHandler`
  130. If you must continue subclassing `DefaultMethodSecurityExpressionHandler`, you can still do so.
  131. Instead, override the `createEvaluationContext(Supplier<Authentication>, MethodInvocation)` method like so:
  132. ====
  133. .Java
  134. [source,java,role="primary"]
  135. ----
  136. @Component
  137. class MyExpressionHandler extends DefaultMethodSecurityExpressionHandler {
  138. @Override
  139. public EvaluationContext createEvaluationContext(
  140. Supplier<Authentication> authentication, MethodInvocation mi) {
  141. StandardEvaluationContext context = (StandardEvaluationContext) super.createEvaluationContext(authentication, mi);
  142. MySecurityExpressionRoot root = new MySecurityExpressionRoot(authentication, invocation);
  143. root.setPermissionEvaluator(getPermissionEvaluator());
  144. root.setTrustResolver(new AuthenticationTrustResolverImpl());
  145. root.setRoleHierarchy(getRoleHierarchy());
  146. context.setRootObject(root);
  147. return context;
  148. }
  149. }
  150. ----
  151. .Kotlin
  152. [source,kotlin,role="secondary"]
  153. ----
  154. @Component
  155. class MyExpressionHandler: DefaultMethodSecurityExpressionHandler {
  156. override fun createEvaluationContext(val authentication: Supplier<Authentication>,
  157. val mi: MethodInvocation): EvaluationContext {
  158. val context = super.createEvaluationContext(authentication, mi) as StandardEvaluationContext;
  159. val root = new MySecurityExpressionRoot(authentication, invocation);
  160. root.setPermissionEvaluator(getPermissionEvaluator());
  161. root.setTrustResolver(new AuthenticationTrustResolverImpl());
  162. root.setRoleHierarchy(getRoleHierarchy());
  163. context.setRootObject(root);
  164. return context;
  165. }
  166. }
  167. ----
  168. ====
  169. ==== Opt-out Steps
  170. If you need to opt-out of these changes, you can use `@EnableGlobalMethodSecurity` instead of `@EnableMethodSecurity`
  171. [[servlet-replace-permissionevaluator-bean-with-methodsecurityexpression-handler]]
  172. === Publish a `MethodSecurityExpressionHandler` instead of a `PermissionEvaluator`
  173. `@EnableMethodSecurity` does not pick up a `PermissionEvaluator`.
  174. This helps keep its API simple.
  175. If you have a custom {security-api-url}org/springframework/security/access/PermissionEvaluator.html[`PermissionEvaluator`] `@Bean`, please change it from:
  176. ====
  177. .Java
  178. [source,java,role="primary"]
  179. ----
  180. @Bean
  181. static PermissionEvaluator permissionEvaluator() {
  182. // ... your evaluator
  183. }
  184. ----
  185. .Kotlin
  186. [source,kotlin,role="secondary"]
  187. ----
  188. companion object {
  189. @Bean
  190. fun permissionEvaluator(): PermissionEvaluator {
  191. // ... your evaluator
  192. }
  193. }
  194. ----
  195. ====
  196. to:
  197. ====
  198. .Java
  199. [source,java,role="primary"]
  200. ----
  201. @Bean
  202. static MethodSecurityExpressionHandler expressionHandler() {
  203. var expressionHandler = new DefaultMethodSecurityExpressionHandler();
  204. expressionHandler.setPermissionEvaluator(myPermissionEvaluator);
  205. return expressionHandler;
  206. }
  207. ----
  208. .Kotlin
  209. [source,kotlin,role="secondary"]
  210. ----
  211. companion object {
  212. @Bean
  213. fun expressionHandler(): MethodSecurityExpressionHandler {
  214. val expressionHandler = DefaultMethodSecurityExpressionHandler
  215. expressionHandler.setPermissionEvaluator(myPermissionEvaluator)
  216. return expressionHandler
  217. }
  218. }
  219. ----
  220. ====
  221. === Replace any custom method-security ``AccessDecisionManager``s
  222. Your application may have a custom {security-api-url}org/springframework/security/access/AccessDecisionManager.html[`AccessDecisionManager`] or {security-api-url}org/springframework/security/access/AccessDecisionVoter.html[`AccessDecisionVoter`] arrangement.
  223. The preparation strategy will depend on your reason for each arrangement.
  224. Read on to find the best match for your situation.
  225. ==== I use `UnanimousBased`
  226. If your application uses {security-api-url}org/springframework/security/access/vote/UnanimousBased.html[`UnanimousBased`] with the default voters, you likely need do nothing since unanimous-based is the default behavior with {security-api-url}org/springframework/security/config/annotation/method/configuration/EnableMethodSecurity.html[`@EnableMethodSecurity`].
  227. However, if you do discover that you cannot accept the default authorization managers, you can use `AuthorizationManagers.allOf` to compose your own arrangement.
  228. Having done that, please follow the details in the reference manual for xref:servlet/authorization/method-security.adoc#jc-method-security-custom-authorization-manager[adding a custom `AuthorizationManager`].
  229. ==== I use `AffirmativeBased`
  230. If your application uses {security-api-url}org/springframework/security/access/vote/AffirmativeBased.html[`AffirmativeBased`], then you can construct an equivalent {security-api-url}org/springframework/security/authorization/AuthorizationManager.html[`AuthorizationManager`], like so:
  231. ====
  232. .Java
  233. [source,java,role="primary"]
  234. ----
  235. AuthorizationManager<MethodInvocation> authorization = AuthorizationManagers.anyOf(
  236. // ... your list of authorization managers
  237. )
  238. ----
  239. .Kotlin
  240. [source,kotlin,role="secondary"]
  241. ----
  242. val authorization = AuthorizationManagers.anyOf(
  243. // ... your list of authorization managers
  244. )
  245. ----
  246. ====
  247. Once you have implemented `AuthorizationManager`, please follow the details in the reference manual for xref:servlet/authorization/method-security.adoc#jc-method-security-custom-authorization-manager[adding a custom `AuthorizationManager`].
  248. ==== I use `ConsensusBased`
  249. There is no framework-provided equivalent for {security-api-url}org/springframework/security/access/vote/ConsensusBased.html[`ConsensusBased`].
  250. In that case, please implement a composite {security-api-url}org/springframework/security/authorization/AuthorizationManager.html[`AuthorizationManager`] that takes the set of delegate ``AuthorizationManager``s into account.
  251. Once you have implemented `AuthorizationManager`, please follow the details in the reference manual for xref:servlet/authorization/method-security.adoc#jc-method-security-custom-authorization-manager[adding a custom `AuthorizationManager`].
  252. ==== I use a custom `AccessDecisionVoter`
  253. You should either change the class to implement {security-api-url}org/springframework/security/authorization/AuthorizationManager.html[`AuthorizationManager`] or create an adapter.
  254. Without knowing what your custom voter is doing, it is impossible to recommend a general-purpose solution.
  255. By way of example, though, here is what adapting {security-api-url}org/springframework/security/access/SecurityMetadataSource.html[`SecurityMetadataSource`] and {security-api-url}org/springframework/security/access/AccessDecisionVoter.html[`AccessDecisionVoter`] for `@PreAuthorize` would look like:
  256. ====
  257. .Java
  258. [source,java,role="primary"]
  259. ----
  260. public final class PreAuthorizeAuthorizationManagerAdapter implements AuthorizationManager<MethodInvocation> {
  261. private final SecurityMetadataSource metadata;
  262. private final AccessDecisionVoter voter;
  263. public PreAuthorizeAuthorizationManagerAdapter(MethodSecurityExpressionHandler expressionHandler) {
  264. ExpressionBasedAnnotationAttributeFactory attributeFactory =
  265. new ExpressionBasedAnnotationAttributeFactory(expressionHandler);
  266. this.metadata = new PrePostAnnotationSecurityMetadataSource(attributeFactory);
  267. ExpressionBasedPreInvocationAdvice expressionAdvice = new ExpressionBasedPreInvocationAdvice();
  268. expressionAdvice.setExpressionHandler(expressionHandler);
  269. this.voter = new PreInvocationAuthorizationAdviceVoter(expressionAdvice);
  270. }
  271. public AuthorizationDecision check(Supplier<Authentication> authentication, MethodInvocation invocation) {
  272. List<ConfigAttribute> attributes = this.metadata.getAttributes(invocation, AopUtils.getTargetClass(invocation.getThis()));
  273. int decision = this.voter.vote(authentication.get(), invocation, attributes);
  274. if (decision == ACCESS_GRANTED) {
  275. return new AuthorizationDecision(true);
  276. }
  277. if (decision == ACCESS_DENIED) {
  278. return new AuthorizationDecision(false);
  279. }
  280. return null; // abstain
  281. }
  282. }
  283. ----
  284. ====
  285. Once you have implemented `AuthorizationManager`, please follow the details in the reference manual for xref:servlet/authorization/method-security.adoc#jc-method-security-custom-authorization-manager[adding a custom `AuthorizationManager`].
  286. ==== I use `AfterInvocationManager` or `AfterInvocationProvider`
  287. {security-api-url}org/springframework/security/access/intercept/AfterInvocationManager.html;[`AfterInvocationManager`] and {security-api-url}org/springframework/security/access/intercept/AfterInvocationProvider.html[`AfterInvocationProvider`] make an authorization decision about an invocation's result.
  288. For example, in the case of method invocation, these make an authorization decision about a method's return value.
  289. In Spring Security 3.0, authorization decision-making was standardized into the xref:servlet/authorization/method-security.adoc[`@PostAuthorize` and `@PostFilter` annotations].
  290. `@PostAuthorize` is for deciding whether the return value as a whole was permitted to be returned.
  291. `@PostFilter` is for filtering individual entries from a returned collection, array, or stream.
  292. These two annotations should serve most needs, and you are encouraged to migrate to one or both of them since `AfterInvocationProvider` and `AfterInvocationManager` are now deprecated.
  293. If you've implemented your own `AfterInvocationManager` or `AfterInvocationProvider`, you should first ask yourself what it is trying to do.
  294. If it is trying to authorize the return type, <<_i_use_a_custom_accessdecisionvoter,consider implementing `AuthorizationManager<MethodInvocationResult>` and using `AfterMethodAuthorizationManagerInterceptor`>>. Or publishing a custom bean and using `@PostAuthorize("@myBean.authorize(#root)")`.
  295. If it is trying to filter, then consider publishing a custom bean and using `@PostFilter("@mybean.authorize(#root)")`.
  296. Or, if needed, you can implement your own `MethodInterceptor`, taking a look at `PostFilterAuthorizationMethodInterceptor` and `PrePostMethodSecurityConfiguration` for an example.
  297. ==== I use `RunAsManager`
  298. There is currently https://github.com/spring-projects/spring-security/issues/11331[no replacement for `RunAsManager`] though one is being considered.
  299. It is quite straightforward to adapt a `RunAsManager`, though, to the `AuthorizationManager` API, if needed.
  300. Here is some pseudocode to get you started:
  301. ====
  302. .Java
  303. [source,java,role="primary"]
  304. ----
  305. public final class RunAsAuthorizationManagerAdapter<T> implements AuthorizationManager<T> {
  306. private final RunAsManager runAs = new RunAsManagerImpl();
  307. private final SecurityMetadataSource metadata;
  308. private final AuthorizationManager<T> authorization;
  309. // ... constructor
  310. public AuthorizationDecision check(Supplier<Authentication> authentication, T object) {
  311. Supplier<Authentication> wrapped = (auth) -> {
  312. List<ConfigAttribute> attributes = this.metadata.getAttributes(object);
  313. return this.runAs.buildRunAs(auth, object, attributes);
  314. };
  315. return this.authorization.check(wrapped, object);
  316. }
  317. }
  318. ----
  319. ====
  320. Once you have implemented `AuthorizationManager`, please follow the details in the reference manual for xref:servlet/authorization/method-security.adoc#jc-method-security-custom-authorization-manager[adding a custom `AuthorizationManager`].
  321. [[servlet-check-for-annotationconfigurationexceptions]]
  322. === Check for ``AnnotationConfigurationException``s
  323. `@EnableMethodSecurity` and `<method-security>` activate stricter enforcement of Spring Security's non-repeatable or otherwise incompatible annotations.
  324. If after moving to either you see ``AnnotationConfigurationException``s in your logs, follow the instructions in the exception message to clean up your application's method security annotation usage.
  325. == Use `AuthorizationManager` for Message Security
  326. xref:servlet/integrations/websocket.adoc[Message Security] has been xref:servlet/integrations/websocket.adoc#websocket-configuration[improved] through {security-api-url}org/springframework/security/authorization/AuthorizationManager.html[the `AuthorizationManager` API] and direct use of Spring AOP.
  327. Should you run into trouble with making these changes, you can follow the <<servlet-authorizationmanager-messages-opt-out,opt out steps>> at the end of this section.
  328. === Ensure all messages have defined authorization rules
  329. The now-deprecated {security-api-url}org/springframework/security/config/annotation/web/socket/AbstractSecurityWebSocketMessageBrokerConfigurer.html[message security support] permits all messages by default.
  330. xref:servlet/integrations/websocket.adoc[The new support] has the stronger default of denying all messages.
  331. To prepare for this, ensure that authorization rules exist are declared for every request.
  332. For example, an application configuration like:
  333. ====
  334. .Java
  335. [source,java,role="primary"]
  336. ----
  337. @Override
  338. protected void configureInbound(MessageSecurityMetadataSourceRegistry messages) {
  339. messages
  340. .simpDestMatchers("/user/queue/errors").permitAll()
  341. .simpDestMatchers("/admin/**").hasRole("ADMIN");
  342. }
  343. ----
  344. .Kotlin
  345. [source,kotlin,role="secondary"]
  346. ----
  347. override fun configureInbound(messages: MessageSecurityMetadataSourceRegistry) {
  348. messages
  349. .simpDestMatchers("/user/queue/errors").permitAll()
  350. .simpDestMatchers("/admin/**").hasRole("ADMIN")
  351. }
  352. ----
  353. .Xml
  354. [source,xml,role="secondary"]
  355. ----
  356. <websocket-message-broker>
  357. <intercept-message pattern="/user/queue/errors" access="permitAll"/>
  358. <intercept-message pattern="/admin/**" access="hasRole('ADMIN')"/>
  359. </websocket-message-broker>
  360. ----
  361. ====
  362. should change to:
  363. ====
  364. .Java
  365. [source,java,role="primary"]
  366. ----
  367. @Override
  368. protected void configureInbound(MessageSecurityMetadataSourceRegistry messages) {
  369. messages
  370. .simpTypeMatchers(CONNECT, DISCONNECT, UNSUBSCRIBE).permitAll()
  371. .simpDestMatchers("/user/queue/errors").permitAll()
  372. .simpDestMatchers("/admin/**").hasRole("ADMIN")
  373. .anyMessage().denyAll();
  374. }
  375. ----
  376. .Kotlin
  377. [source,kotlin,role="secondary"]
  378. ----
  379. override fun configureInbound(messages: MessageSecurityMetadataSourceRegistry) {
  380. messages
  381. .simpTypeMatchers(CONNECT, DISCONNECT, UNSUBSCRIBE).permitAll()
  382. .simpDestMatchers("/user/queue/errors").permitAll()
  383. .simpDestMatchers("/admin/**").hasRole("ADMIN")
  384. .anyMessage().denyAll()
  385. }
  386. ----
  387. .Xml
  388. [source,xml,role="secondary"]
  389. ----
  390. <websocket-message-broker>
  391. <intercept-message type="CONNECT" access="permitAll"/>
  392. <intercept-message type="DISCONNECT" access="permitAll"/>
  393. <intercept-message type="UNSUBSCRIBE" access="permitAll"/>
  394. <intercept-message pattern="/user/queue/errors" access="permitAll"/>
  395. <intercept-message pattern="/admin/**" access="hasRole('ADMIN')"/>
  396. <intercept-message pattern="/**" access="denyAll"/>
  397. </websocket-message-broker>
  398. ----
  399. ====
  400. === Add `@EnableWebSocketSecurity`
  401. [NOTE]
  402. ====
  403. If you want to have CSRF disabled and you are using Java configuration, the migration steps are slightly different.
  404. Instead of using `@EnableWebSocketSecurity`, you will override the appropriate methods in `WebSocketMessageBrokerConfigurer` yourself.
  405. Please see xref:servlet/integrations/websocket.adoc#websocket-sameorigin-disable[the reference manual] for details about this step.
  406. ====
  407. If you are using Java Configuration, add {security-api-url}org/springframework/security/config/annotation/web/socket/EnableWebSocketSecurity.html[`@EnableWebSocketSecurity`] to your application.
  408. For example, you can add it to your websocket security configuration class, like so:
  409. ====
  410. .Java
  411. [source,java,role="primary"]
  412. ----
  413. @EnableWebSocketSecurity
  414. @Configuration
  415. public class WebSocketSecurityConfig extends AbstractSecurityWebSocketMessageBrokerConfigurer {
  416. // ...
  417. }
  418. ----
  419. .Kotlin
  420. [source,kotlin,role="secondary"]
  421. ----
  422. @EnableWebSocketSecurity
  423. @Configuration
  424. class WebSocketSecurityConfig: AbstractSecurityWebSocketMessageBrokerConfigurer() {
  425. // ...
  426. }
  427. ----
  428. ====
  429. This will make a prototype instance of `MessageMatcherDelegatingAuthorizationManager.Builder` available to encourage configuration by composition instead of extension.
  430. === Use an `AuthorizationManager<Message<?>>` instance
  431. To start using `AuthorizationManager`, you can set the `use-authorization-manager` attribute in XML or you can publish an `AuthorizationManager<Message<?>>` `@Bean` in Java.
  432. For example, the following application configuration:
  433. ====
  434. .Java
  435. [source,java,role="primary"]
  436. ----
  437. @Override
  438. protected void configureInbound(MessageSecurityMetadataSourceRegistry messages) {
  439. messages
  440. .simpTypeMatchers(CONNECT, DISCONNECT, UNSUBSCRIBE).permitAll()
  441. .simpDestMatchers("/user/queue/errors").permitAll()
  442. .simpDestMatchers("/admin/**").hasRole("ADMIN")
  443. .anyMessage().denyAll();
  444. }
  445. ----
  446. .Kotlin
  447. [source,kotlin,role="secondary"]
  448. ----
  449. override fun configureInbound(messages: MessageSecurityMetadataSourceRegistry) {
  450. messages
  451. .simpTypeMatchers(CONNECT, DISCONNECT, UNSUBSCRIBE).permitAll()
  452. .simpDestMatchers("/user/queue/errors").permitAll()
  453. .simpDestMatchers("/admin/**").hasRole("ADMIN")
  454. .anyMessage().denyAll()
  455. }
  456. ----
  457. .Xml
  458. [source,xml,role="secondary"]
  459. ----
  460. <websocket-message-broker>
  461. <intercept-message type="CONNECT" access="permitAll"/>
  462. <intercept-message type="DISCONNECT" access="permitAll"/>
  463. <intercept-message type="UNSUBSCRIBE" access="permitAll"/>
  464. <intercept-message pattern="/user/queue/errors" access="permitAll"/>
  465. <intercept-message pattern="/admin/**" access="hasRole('ADMIN')"/>
  466. <intercept-message pattern="/**" access="denyAll"/>
  467. </websocket-message-broker>
  468. ----
  469. ====
  470. changes to:
  471. ====
  472. .Java
  473. [source,java,role="primary"]
  474. ----
  475. @Bean
  476. AuthorizationManager<Message<?>> messageSecurity(MessageMatcherDelegatingAuthorizationManager.Builder messages) {
  477. messages
  478. .simpTypeMatchers(CONNECT, DISCONNECT, UNSUBSCRIBE).permitAll()
  479. .simpDestMatchers("/user/queue/errors").permitAll()
  480. .simpDestMatchers("/admin/**").hasRole("ADMIN")
  481. .anyMessage().denyAll();
  482. return messages.build();
  483. }
  484. ----
  485. .Kotlin
  486. [source,kotlin,role="secondary"]
  487. ----
  488. @Bean
  489. fun messageSecurity(val messages: MessageMatcherDelegatingAuthorizationManager.Builder): AuthorizationManager<Message<?>> {
  490. messages
  491. .simpTypeMatchers(CONNECT, DISCONNECT, UNSUBSCRIBE).permitAll()
  492. .simpDestMatchers("/user/queue/errors").permitAll()
  493. .simpDestMatchers("/admin/**").hasRole("ADMIN")
  494. .anyMessage().denyAll()
  495. return messages.build()
  496. }
  497. ----
  498. .Xml
  499. [source,xml,role="secondary"]
  500. ----
  501. <websocket-message-broker use-authorization-manager="true">
  502. <intercept-message type="CONNECT" access="permitAll"/>
  503. <intercept-message type="DISCONNECT" access="permitAll"/>
  504. <intercept-message type="UNSUBSCRIBE" access="permitAll"/>
  505. <intercept-message pattern="/user/queue/errors" access="permitAll"/>
  506. <intercept-message pattern="/admin/**" access="hasRole('ADMIN')"/>
  507. <intercept-message pattern="/**" access="denyAll"/>
  508. </websocket-message-broker>
  509. ----
  510. ====
  511. === Stop Implementing `AbstractSecurityWebSocketMessageBrokerConfigurer`
  512. If you are using Java configuration, you can now simply extend `WebSocketMessageBrokerConfigurer`.
  513. For example, if your class that extends `AbstractSecurityWebSocketMessageBrokerConfigurer` is called `WebSocketSecurityConfig`, then:
  514. ====
  515. .Java
  516. [source,java,role="primary"]
  517. ----
  518. @EnableWebSocketSecurity
  519. @Configuration
  520. public class WebSocketSecurityConfig extends AbstractSecurityWebSocketMessageBrokerConfigurer {
  521. // ...
  522. }
  523. ----
  524. .Kotlin
  525. [source,kotlin,role="secondary"]
  526. ----
  527. @EnableWebSocketSecurity
  528. @Configuration
  529. class WebSocketSecurityConfig: AbstractSecurityWebSocketMessageBrokerConfigurer() {
  530. // ...
  531. }
  532. ----
  533. ====
  534. changes to:
  535. ====
  536. .Java
  537. [source,java,role="primary"]
  538. ----
  539. @EnableWebSocketSecurity
  540. @Configuration
  541. public class WebSocketSecurityConfig implements WebSocketMessageBrokerConfigurer {
  542. // ...
  543. }
  544. ----
  545. .Kotlin
  546. [source,kotlin,role="secondary"]
  547. ----
  548. @EnableWebSocketSecurity
  549. @Configuration
  550. class WebSocketSecurityConfig: WebSocketMessageBrokerConfigurer {
  551. // ...
  552. }
  553. ----
  554. ====
  555. [[servlet-authorizationmanager-messages-opt-out]]
  556. === Opt-out Steps
  557. In case you had trouble, take a look at these scenarios for optimal opt out behavior:
  558. ==== I cannot declare an authorization rule for all requests
  559. If you are having trouble setting an `anyRequest` authorization rule of `denyAll`, please use {security-api-url}org/springframework/security/messaging/access/intercept/MessageMatcherDelegatingAuthorizationManager.Builder.Constraint.html#permitAll()[`permitAll`] instead, like so:
  560. ====
  561. .Java
  562. [source,java,role="primary"]
  563. ----
  564. @Bean
  565. AuthorizationManager<Message<?>> messageSecurity(MessageMatcherDelegatingAuthorizationManager.Builder messages) {
  566. messages
  567. .simpDestMatchers("/user/queue/errors").permitAll()
  568. .simpDestMatchers("/admin/**").hasRole("ADMIN")
  569. // ...
  570. .anyMessage().permitAll();
  571. return messages.build();
  572. }
  573. ----
  574. .Kotlin
  575. [source,kotlin,role="secondary"]
  576. ----
  577. @Bean
  578. fun messageSecurity(val messages: MessageMatcherDelegatingAuthorizationManager.Builder): AuthorizationManager<Message<?>> {
  579. messages
  580. .simpDestMatchers("/user/queue/errors").permitAll()
  581. .simpDestMatchers("/admin/**").hasRole("ADMIN")
  582. // ...
  583. .anyMessage().permitAll();
  584. return messages.build()
  585. }
  586. ----
  587. .Xml
  588. [source,xml,role="secondary"]
  589. ----
  590. <websocket-message-broker use-authorization-manager="true">
  591. <intercept-message pattern="/user/queue/errors" access="permitAll"/>
  592. <intercept-message pattern="/admin/**" access="hasRole('ADMIN')"/>
  593. <!-- ... -->
  594. <intercept-message pattern="/**" access="permitAll"/>
  595. </websocket-message-broker>
  596. ----
  597. ====
  598. ==== I cannot get CSRF working, need some other `AbstractSecurityWebSocketMessageBrokerConfigurer` feature, or am having trouble with `AuthorizationManager`
  599. In the case of Java, you may continue using `AbstractMessageSecurityWebSocketMessageBrokerConfigurer`.
  600. Even though it is deprecated, it will not be removed in 6.0.
  601. In the case of XML, you can opt out of `AuthorizationManager` by setting `use-authorization-manager="false"`:
  602. ====
  603. .Xml
  604. [source,xml,role="secondary"]
  605. ----
  606. <websocket-message-broker>
  607. <intercept-message pattern="/user/queue/errors" access="permitAll"/>
  608. <intercept-message pattern="/admin/**" access="hasRole('ADMIN')"/>
  609. </websocket-message-broker>
  610. ----
  611. ====
  612. to:
  613. ====
  614. .Xml
  615. [source,xml,role="secondary"]
  616. ----
  617. <websocket-message-broker use-authorization-manager="false">
  618. <intercept-message pattern="/user/queue/errors" access="permitAll"/>
  619. <intercept-message pattern="/admin/**" access="hasRole('ADMIN')"/>
  620. </websocket-message-broker>
  621. ----
  622. ====
  623. == Use `AuthorizationManager` for Request Security
  624. xref:servlet/authorization/authorize-requests.adoc[HTTP Request Security] has been xref:servlet/authorization/authorize-http-requests.adoc[simplified] through {security-api-url}org/springframework/security/authorization/AuthorizationManager.html[the `AuthorizationManager` API].
  625. Should you run into trouble with making these changes, you can follow the <<servlet-authorizationmanager-requests-opt-out,opt out steps>> at the end of this section.
  626. === Ensure that all requests have defined authorization rules
  627. In Spring Security 5.8 and earlier, requests with no authorization rule are permitted by default.
  628. It is a stronger security position to deny by default, thus requiring that authorization rules be clearly defined for every endpoint.
  629. As such, in 6.0, Spring Security by default denies any request that is missing an authorization rule.
  630. The simplest way to prepare for this change is to introduce an appropriate {security-api-url}org/springframework/security/config/annotation/web/AbstractRequestMatcherRegistry.html#anyRequest()[`anyRequest`] rule as the last authorization rule.
  631. The recommendation is {security-api-url}org/springframework/security/config/annotation/web/configurers/ExpressionUrlAuthorizationConfigurer.AuthorizedUrl.html#denyAll()[`denyAll`] since that is the implied 6.0 default.
  632. [NOTE]
  633. ====
  634. You may already have an `anyRequest` rule defined that you are happy with in which case this step can be skipped.
  635. ====
  636. Adding `denyAll` to the end looks like changing:
  637. ====
  638. .Java
  639. [source,java,role="primary"]
  640. ----
  641. http
  642. .authorizeRequests((authorize) -> authorize
  643. .filterSecurityInterceptorOncePerRequest(true)
  644. .mvcMatchers("/app/**").hasRole("APP")
  645. // ...
  646. )
  647. // ...
  648. ----
  649. .Kotlin
  650. [source,kotlin,role="secondary"]
  651. ----
  652. http {
  653. authorizeRequests {
  654. filterSecurityInterceptorOncePerRequest = true
  655. authorize("/app/**", hasRole("APP"))
  656. // ...
  657. }
  658. }
  659. ----
  660. .Xml
  661. [source,xml,role="secondary"]
  662. ----
  663. <http once-per-request="true">
  664. <intercept-url pattern="/app/*" access="hasRole('APP')"/>
  665. <!-- ... -->
  666. </http>
  667. ----
  668. ====
  669. to:
  670. ====
  671. .Java
  672. [source,java,role="primary"]
  673. ----
  674. http
  675. .authorizeRequests((authorize) -> authorize
  676. .filterSecurityInterceptorOncePerRequest(true)
  677. .mvcMatchers("/app/**").hasRole("APP")
  678. // ...
  679. .anyRequest().denyAll()
  680. )
  681. // ...
  682. ----
  683. .Kotlin
  684. [source,kotlin,role="secondary"]
  685. ----
  686. http {
  687. authorizeRequests {
  688. filterSecurityInterceptorOncePerRequest = true
  689. authorize("/app/**", hasRole("APP"))
  690. // ...
  691. authorize(anyRequest, denyAll)
  692. }
  693. }
  694. ----
  695. .Xml
  696. [source,xml,role="secondary"]
  697. ----
  698. <http once-per-request="true">
  699. <intercept-url pattern="/app/*" access="hasRole('APP')"/>
  700. <!-- ... -->
  701. <intercept-url pattern="/**" access="denyAll"/>
  702. </http>
  703. ----
  704. ====
  705. If you have already migrated to `authorizeHttpRequests`, the recommended change is the same.
  706. === Switch to `AuthorizationManager`
  707. To opt in to using `AuthorizationManager`, you can use `authorizeHttpRequests` or xref:servlet/appendix/namespace/http.adoc#nsa-http-use-authorization-manager[`use-authorization-manager`] for Java or XML, respectively.
  708. Change:
  709. ====
  710. .Java
  711. [source,java,role="primary"]
  712. ----
  713. http
  714. .authorizeRequests((authorize) -> authorize
  715. .filterSecurityInterceptorOncePerRequest(true)
  716. .mvcMatchers("/app/**").hasRole("APP")
  717. // ...
  718. .anyRequest().denyAll()
  719. )
  720. // ...
  721. ----
  722. .Kotlin
  723. [source,kotlin,role="secondary"]
  724. ----
  725. http {
  726. authorizeRequests {
  727. filterSecurityInterceptorOncePerRequest = true
  728. authorize("/app/**", hasRole("APP"))
  729. // ...
  730. authorize(anyRequest, denyAll)
  731. }
  732. }
  733. ----
  734. .Xml
  735. [source,xml,role="secondary"]
  736. ----
  737. <http once-per-request="true">
  738. <intercept-url pattern="/app/*" access="hasRole('APP')"/>
  739. <!-- ... -->
  740. <intercept-url pattern="/**" access="denyAll"/>
  741. </http>
  742. ----
  743. ====
  744. to:
  745. ====
  746. .Java
  747. [source,java,role="primary"]
  748. ----
  749. http
  750. .authorizeHttpRequests((authorize) -> authorize
  751. .shouldFilterAllDispatcherTypes(false)
  752. .mvcMatchers("/app/**").hasRole("APP")
  753. // ...
  754. .anyRequest().denyAll()
  755. )
  756. // ...
  757. ----
  758. .Kotlin
  759. [source,kotlin,role="secondary"]
  760. ----
  761. http {
  762. authorizeHttpRequests {
  763. shouldFilterAllDispatcherTypes = false
  764. authorize("/app/**", hasRole("APP"))
  765. // ...
  766. authorize(anyRequest, denyAll)
  767. }
  768. }
  769. ----
  770. .Xml
  771. [source,xml,role="secondary"]
  772. ----
  773. <http filter-all-dispatcher-types="false" use-authorization-manager="true">
  774. <intercept-url pattern="/app/*" access="hasRole('APP')"/>
  775. <!-- ... -->
  776. <intercept-url pattern="/**" access="denyAll"/>
  777. </http>
  778. ----
  779. ====
  780. === Migrate SpEL expressions to `AuthorizationManager`
  781. For authorization rules, Java tends to be easier to test and maintain than SpEL.
  782. As such, `authorizeHttpRequests` does not have a method for declaring a `String` SpEL.
  783. Instead, you can implement your own `AuthorizationManager` implementation or use `WebExpressionAuthorizationManager`.
  784. For completeness, both options will be demonstrated.
  785. First, if you have the following SpEL:
  786. ====
  787. .Java
  788. [source,java,role="primary"]
  789. ----
  790. http
  791. .authorizeRequests((authorize) -> authorize
  792. .filterSecurityInterceptorOncePerRequest(true)
  793. .mvcMatchers("/complicated/**").access("hasRole('ADMIN') || hasAuthority('SCOPE_read')")
  794. // ...
  795. .anyRequest().denyAll()
  796. )
  797. // ...
  798. ----
  799. .Kotlin
  800. [source,kotlin,role="secondary"]
  801. ----
  802. http {
  803. authorizeRequests {
  804. filterSecurityInterceptorOncePerRequest = true
  805. authorize("/complicated/**", access("hasRole('ADMIN') || hasAuthority('SCOPE_read')"))
  806. // ...
  807. authorize(anyRequest, denyAll)
  808. }
  809. }
  810. ----
  811. ====
  812. Then you can compose your own `AuthorizationManager` with Spring Security authorization primitives like so:
  813. ====
  814. .Java
  815. [source,java,role="primary"]
  816. ----
  817. http
  818. .authorizeHttpRequests((authorize) -> authorize
  819. .shouldFilterAllDispatcherTypes(false)
  820. .mvcMatchers("/complicated/**").access(anyOf(hasRole("ADMIN"), hasAuthority("SCOPE_read"))
  821. // ...
  822. .anyRequest().denyAll()
  823. )
  824. // ...
  825. ----
  826. .Kotlin
  827. [source,kotlin,role="secondary"]
  828. ----
  829. http {
  830. authorizeHttpRequests {
  831. shouldFilterAllDispatcherTypes = false
  832. authorize("/complicated/**", access(anyOf(hasRole("ADMIN"), hasAuthority("SCOPE_read"))
  833. // ...
  834. authorize(anyRequest, denyAll)
  835. }
  836. }
  837. ----
  838. ====
  839. Or you can use `WebExpressionAuthorizationManager` in the following way:
  840. ====
  841. .Java
  842. [source,java,role="primary"]
  843. ----
  844. http
  845. .authorizeRequests((authorize) -> authorize
  846. .filterSecurityInterceptorOncePerRequest(true)
  847. .mvcMatchers("/complicated/**").access(
  848. new WebExpressionAuthorizationManager("hasRole('ADMIN') || hasAuthority('SCOPE_read')")
  849. )
  850. // ...
  851. .anyRequest().denyAll()
  852. )
  853. // ...
  854. ----
  855. .Kotlin
  856. [source,kotlin,role="secondary"]
  857. ----
  858. http {
  859. authorizeRequests {
  860. filterSecurityInterceptorOncePerRequest = true
  861. authorize("/complicated/**", access(
  862. WebExpressionAuthorizationManager("hasRole('ADMIN') || hasAuthority('SCOPE_read')"))
  863. )
  864. // ...
  865. authorize(anyRequest, denyAll)
  866. }
  867. }
  868. ----
  869. ====
  870. [[switch-filter-all-dispatcher-types]]
  871. === Switch to filter all dispatcher types
  872. Spring Security 5.8 and earlier only xref:servlet/authorization/architecture.adoc[perform authorization] once per request.
  873. This means that dispatcher types like `FORWARD` and `INCLUDE` that run after `REQUEST` are not secured by default.
  874. It's recommended that Spring Security secure all dispatch types.
  875. As such, in 6.0, Spring Security changes this default.
  876. So, finally, change your authorization rules to filter all dispatcher types.
  877. To do this, you should change:
  878. ====
  879. .Java
  880. [source,java,role="primary"]
  881. ----
  882. http
  883. .authorizeHttpRequests((authorize) -> authorize
  884. .shouldFilterAllDispatcherTypes(false)
  885. .mvcMatchers("/app/**").hasRole("APP")
  886. // ...
  887. .anyRequest().denyAll()
  888. )
  889. // ...
  890. ----
  891. .Kotlin
  892. [source,kotlin,role="secondary"]
  893. ----
  894. http {
  895. authorizeHttpRequests {
  896. shouldFilterAllDispatcherTypes = false
  897. authorize("/app/**", hasRole("APP"))
  898. // ...
  899. authorize(anyRequest, denyAll)
  900. }
  901. }
  902. ----
  903. .Xml
  904. [source,xml,role="secondary"]
  905. ----
  906. <http filter-all-dispatcher-types="false" use-authorization-manager="true">
  907. <intercept-url pattern="/app/*" access="hasRole('APP')"/>
  908. <!-- ... -->
  909. <intercept-url pattern="/**" access="denyAll"/>
  910. </http>
  911. ----
  912. ====
  913. to:
  914. ====
  915. .Java
  916. [source,java,role="primary"]
  917. ----
  918. http
  919. .authorizeHttpRequests((authorize) -> authorize
  920. .shouldFilterAllDispatcherTypes(true)
  921. .mvcMatchers("/app/**").hasRole("APP")
  922. // ...
  923. .anyRequest().denyAll()
  924. )
  925. // ...
  926. ----
  927. .Kotlin
  928. [source,kotlin,role="secondary"]
  929. ----
  930. http {
  931. authorizeHttpRequests {
  932. shouldFilterAllDispatcherTypes = true
  933. authorize("/app/**", hasRole("APP"))
  934. // ...
  935. authorize(anyRequest, denyAll)
  936. }
  937. }
  938. ----
  939. .Xml
  940. [source,xml,role="secondary"]
  941. ----
  942. <http filter-all-dispatcher-types="true" use-authorization-manager="true">
  943. <intercept-url pattern="/app/*" access="hasRole('APP')"/>
  944. <!-- ... -->
  945. <intercept-url pattern="/**" access="denyAll"/>
  946. </http>
  947. ----
  948. ====
  949. And, the `FilterChainProxy` should be registered for all dispatcher types as well.
  950. If you are using Spring Boot, https://docs.spring.io/spring-boot/docs/current/reference/html/application-properties.html#application-properties.security.spring.security.filter.dispatcher-types[you have to change the `spring.security.filter.dispatcher-types` property] to include all dispatcher types:
  951. ====
  952. .application.properties
  953. [source,properties,role="primary"]
  954. ----
  955. spring.security.filter.dispatcher-types=request,async,error,forward,include
  956. ----
  957. ====
  958. If you are xref:servlet/configuration/java.adoc#_abstractsecuritywebapplicationinitializer[using the `AbstractSecurityWebApplicationInitializer`] you should override the `getSecurityDispatcherTypes` method and return all dispatcher types:
  959. ====
  960. .Java
  961. [source,java,role="primary"]
  962. ----
  963. import org.springframework.security.web.context.*;
  964. public class SecurityWebApplicationInitializer extends AbstractSecurityWebApplicationInitializer {
  965. @Override
  966. protected EnumSet<DispatcherType> getSecurityDispatcherTypes() {
  967. return EnumSet.of(DispatcherType.REQUEST, DispatcherType.ERROR, DispatcherType.ASYNC,
  968. DispatcherType.FORWARD, DispatcherType.INCLUDE);
  969. }
  970. }
  971. ----
  972. ====
  973. ==== Permit `FORWARD` when using Spring MVC
  974. If you are using {spring-framework-reference-url}/web.html#mvc-viewresolver[Spring MVC to resolve view names], you will need to permit `FORWARD` requests.
  975. This is because when Spring MVC detects a mapping between view name and the actual views, it will perform a forward to the view.
  976. As we saw on the <<switch-filter-all-dispatcher-types,previous section>>, Spring Security 6.0 will apply authorization to `FORWARD` requests by default.
  977. Consider the following common configuration:
  978. ====
  979. .Java
  980. [source,java,role="primary"]
  981. ----
  982. @Bean
  983. public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
  984. http
  985. .authorizeHttpRequests((authorize) -> authorize
  986. .shouldFilterAllDispatcherTypes(true)
  987. .requestMatchers("/").authenticated()
  988. .anyRequest().denyAll()
  989. )
  990. .formLogin((form) -> form
  991. .loginPage("/login")
  992. .permitAll()
  993. ));
  994. return http.build();
  995. }
  996. ----
  997. ====
  998. and one of the following equivalents MVC view mapping configurations:
  999. ====
  1000. .Java
  1001. [source,java,role="primary"]
  1002. ----
  1003. @Controller
  1004. public class MyController {
  1005. @GetMapping("/login")
  1006. public String login() {
  1007. return "login";
  1008. }
  1009. }
  1010. ----
  1011. ====
  1012. ====
  1013. .Java
  1014. [source,java,role="primary"]
  1015. ----
  1016. @Configuration
  1017. public class MyWebMvcConfigurer implements WebMvcConfigurer {
  1018. @Override
  1019. public void addViewControllers(ViewControllerRegistry registry) {
  1020. registry.addViewController("/login").setViewName("login");
  1021. }
  1022. }
  1023. ----
  1024. ====
  1025. With either configuration, when there is a request to `/login`, Spring MVC will perform a *forward* to the view `login`, which, with the default configuration, is under `src/main/resources/templates/login.html` path.
  1026. The security configuration permits requests to `/login` but every other request will be denied, including the `FORWARD` request to the view under `/templates/login.html`.
  1027. To fix this, you should configure Spring Security to permit `FORWARD` requests:
  1028. ====
  1029. .Java
  1030. [source,java,role="primary"]
  1031. ----
  1032. http
  1033. .authorizeHttpRequests((authorize) -> authorize
  1034. .shouldFilterAllDispatcherTypes(true)
  1035. .dispatcherTypeMatchers(DispatcherType.FORWARD).permitAll()
  1036. .anyRequest().denyAll()
  1037. )
  1038. // ...
  1039. ----
  1040. .Kotlin
  1041. [source,kotlin,role="secondary"]
  1042. ----
  1043. http {
  1044. authorizeHttpRequests {
  1045. shouldFilterAllDispatcherTypes = true
  1046. authorize(DispatcherTypeRequestMatcher(DispatcherType.FORWARD), permitAll)
  1047. authorize(anyRequest, denyAll)
  1048. }
  1049. }
  1050. ----
  1051. .Xml
  1052. [source,xml,role="secondary"]
  1053. ----
  1054. <http filter-all-dispatcher-types="true" use-authorization-manager="true">
  1055. <intercept-url request-matcher-ref="forwardRequestMatcher" access="permitAll()" />
  1056. <!-- ... -->
  1057. <intercept-url pattern="/**" access="denyAll"/>
  1058. </http>
  1059. <bean name="forwardRequestMatcher" class="org.springframework.security.web.util.matcher.DispatcherTypeRequestMatcher">
  1060. <constructor-arg value="FORWARD"/>
  1061. </bean>
  1062. ----
  1063. ====
  1064. === Replace any custom filter-security ``AccessDecisionManager``s
  1065. Your application may have a custom {security-api-url}org/springframework/security/access/AccessDecisionManager.html[`AccessDecisionManager`] or {security-api-url}org/springframework/security/access/AccessDecisionVoter.html[`AccessDecisionVoter`] arrangement.
  1066. The preparation strategy will depend on your reason for each arrangement.
  1067. Read on to find the best match for your situation.
  1068. ==== I use `UnanimousBased`
  1069. If your application uses {security-api-url}org/springframework/security/access/vote/UnanimousBased.html[`UnanimousBased`], you should first adapt or replace any ``AccessDecisionVoter``s and then you can construct an `AuthorizationManager` like so:
  1070. ====
  1071. .Java
  1072. [source,java,role="primary"]
  1073. ----
  1074. @Bean
  1075. AuthorizationManager<RequestAuthorizationContext> requestAuthorization() {
  1076. PolicyAuthorizationManager policy = ...;
  1077. LocalAuthorizationManager local = ...;
  1078. return AuthorizationMangers.allOf(policy, local);
  1079. }
  1080. ----
  1081. .Kotlin
  1082. [source,kotlin,role="secondary"]
  1083. ----
  1084. @Bean
  1085. fun requestAuthorization(): AuthorizationManager<RequestAuthorizationContext> {
  1086. val policy: PolicyAuthorizationManager = ...
  1087. val local: LocalAuthorizationManager = ...
  1088. return AuthorizationMangers.allOf(policy, local)
  1089. }
  1090. ----
  1091. .Xml
  1092. [source,xml,role="secondary"]
  1093. ----
  1094. <bean id="requestAuthorization" class="org.springframework.security.authorization.AuthorizationManagers"
  1095. factory-method="allOf">
  1096. <constructor-arg>
  1097. <util:list>
  1098. <bean class="my.PolicyAuthorizationManager"/>
  1099. <bean class="my.LocalAuthorizationManager"/>
  1100. </util:list>
  1101. </constructor-arg>
  1102. </bean>
  1103. ----
  1104. ====
  1105. then, wire it into the DSL like so:
  1106. ====
  1107. .Java
  1108. [source,java,role="primary"]
  1109. ----
  1110. http
  1111. .authorizeHttpRequests((authorize) -> authorize.anyRequest().access(requestAuthorization))
  1112. // ...
  1113. ----
  1114. .Kotlin
  1115. [source,kotlin,role="secondary"]
  1116. ----
  1117. http {
  1118. authorizeHttpRequests {
  1119. authorize(anyRequest, requestAuthorization)
  1120. }
  1121. // ...
  1122. }
  1123. ----
  1124. .Xml
  1125. [source,xml,role="secondary"]
  1126. ----
  1127. <http authorization-manager-ref="requestAuthorization"/>
  1128. ----
  1129. ====
  1130. [NOTE]
  1131. ====
  1132. `authorizeHttpRequests` is designed so that you can apply a custom `AuthorizationManager` to any url pattern.
  1133. See xref:servlet/authorization/authorize-http-requests.adoc#custom-authorization-manager[the reference] for more details.
  1134. ====
  1135. ==== I use `AffirmativeBased`
  1136. If your application uses {security-api-url}org/springframework/security/access/vote/AffirmativeBased.html[`AffirmativeBased`], then you can construct an equivalent {security-api-url}org/springframework/security/authorization/AuthorizationManager.html[`AuthorizationManager`], like so:
  1137. ====
  1138. .Java
  1139. [source,java,role="primary"]
  1140. ----
  1141. @Bean
  1142. AuthorizationManager<RequestAuthorizationContext> requestAuthorization() {
  1143. PolicyAuthorizationManager policy = ...;
  1144. LocalAuthorizationManager local = ...;
  1145. return AuthorizationMangers.anyOf(policy, local);
  1146. }
  1147. ----
  1148. .Kotlin
  1149. [source,kotlin,role="secondary"]
  1150. ----
  1151. @Bean
  1152. fun requestAuthorization(): AuthorizationManager<RequestAuthorizationContext> {
  1153. val policy: PolicyAuthorizationManager = ...
  1154. val local: LocalAuthorizationManager = ...
  1155. return AuthorizationMangers.anyOf(policy, local)
  1156. }
  1157. ----
  1158. .Xml
  1159. [source,xml,role="secondary"]
  1160. ----
  1161. <bean id="requestAuthorization" class="org.springframework.security.authorization.AuthorizationManagers"
  1162. factory-method="anyOf">
  1163. <constructor-arg>
  1164. <util:list>
  1165. <bean class="my.PolicyAuthorizationManager"/>
  1166. <bean class="my.LocalAuthorizationManager"/>
  1167. </util:list>
  1168. </constructor-arg>
  1169. </bean>
  1170. ----
  1171. ====
  1172. then, wire it into the DSL like so:
  1173. ====
  1174. .Java
  1175. [source,java,role="primary"]
  1176. ----
  1177. http
  1178. .authorizeHttpRequests((authorize) -> authorize.anyRequest().access(requestAuthorization))
  1179. // ...
  1180. ----
  1181. .Kotlin
  1182. [source,kotlin,role="secondary"]
  1183. ----
  1184. http {
  1185. authorizeHttpRequests {
  1186. authorize(anyRequest, requestAuthorization)
  1187. }
  1188. // ...
  1189. }
  1190. ----
  1191. .Xml
  1192. [source,xml,role="secondary"]
  1193. ----
  1194. <http authorization-manager-ref="requestAuthorization"/>
  1195. ----
  1196. ====
  1197. [NOTE]
  1198. ====
  1199. `authorizeHttpRequests` is designed so that you can apply a custom `AuthorizationManager` to any url pattern.
  1200. See xref:servlet/authorization/authorize-http-requests.adoc#custom-authorization-manager[the reference] for more details.
  1201. ====
  1202. ==== I use `ConsensusBased`
  1203. There is no framework-provided equivalent for {security-api-url}org/springframework/security/access/vote/ConsensusBased.html[`ConsensusBased`].
  1204. In that case, please implement a composite {security-api-url}org/springframework/security/authorization/AuthorizationManager.html[`AuthorizationManager`] that takes the set of delegate ``AuthorizationManager``s into account.
  1205. Once you have implemented `AuthorizationManager`, please follow the details in the reference manual for xref:servlet/authorization/authorize-http-requests.adoc#custom-authorization-manager[adding a custom `AuthorizationManager`].
  1206. ==== I use a custom `AccessDecisionVoter`
  1207. You should either change the class to implement {security-api-url}org/springframework/security/authorization/AuthorizationManager.html[`AuthorizationManager`] or create an adapter.
  1208. Without knowing what your custom voter is doing, it is impossible to recommend a general-purpose solution.
  1209. By way of example, though, here is what adapting {security-api-url}org/springframework/security/access/SecurityMetadataSource.html[`SecurityMetadataSource`] and {security-api-url}org/springframework/security/access/AccessDecisionVoter.html[`AccessDecisionVoter`] for `anyRequest().authenticated()` would look like:
  1210. ====
  1211. .Java
  1212. [source,java,role="primary"]
  1213. ----
  1214. public final class AnyRequestAuthenticatedAuthorizationManagerAdapter implements AuthorizationManager<RequestAuthorizationContext> {
  1215. private final SecurityMetadataSource metadata;
  1216. private final AccessDecisionVoter voter;
  1217. public PreAuthorizeAuthorizationManagerAdapter(SecurityExpressionHandler expressionHandler) {
  1218. Map<RequestMatcher, List<ConfigAttribute>> requestMap = Collections.singletonMap(
  1219. AnyRequestMatcher.INSTANCE, Collections.singletonList(new SecurityConfig("authenticated")));
  1220. this.metadata = new DefaultFilterInvocationSecurityMetadataSource(requestMap);
  1221. WebExpressionVoter voter = new WebExpressionVoter();
  1222. voter.setExpressionHandler(expressionHandler);
  1223. this.voter = voter;
  1224. }
  1225. public AuthorizationDecision check(Supplier<Authentication> authentication, RequestAuthorizationContext context) {
  1226. List<ConfigAttribute> attributes = this.metadata.getAttributes(context);
  1227. int decision = this.voter.vote(authentication.get(), invocation, attributes);
  1228. if (decision == ACCESS_GRANTED) {
  1229. return new AuthorizationDecision(true);
  1230. }
  1231. if (decision == ACCESS_DENIED) {
  1232. return new AuthorizationDecision(false);
  1233. }
  1234. return null; // abstain
  1235. }
  1236. }
  1237. ----
  1238. ====
  1239. Once you have implemented `AuthorizationManager`, please follow the details in the reference manual for xref:servlet/authorization/authorize-http-requests.adoc#custom-authorization-manager[adding a custom `AuthorizationManager`].
  1240. [[servlet-authorizationmanager-requests-opt-out]]
  1241. === Opt-out Steps
  1242. In case you had trouble, take a look at these scenarios for optimal opt out behavior:
  1243. ==== I cannot secure all dispatcher types
  1244. If you cannot secure all dispatcher types, first try and declare which dispatcher types should not require authorization like so:
  1245. ====
  1246. .Java
  1247. [source,java,role="primary"]
  1248. ----
  1249. http
  1250. .authorizeHttpRequests((authorize) -> authorize
  1251. .shouldFilterAllDispatcherTypes(true)
  1252. .dispatcherTypeMatchers(FORWARD, INCLUDE).permitAll()
  1253. .mvcMatchers("/app/**").hasRole("APP")
  1254. // ...
  1255. .anyRequest().denyAll()
  1256. )
  1257. // ...
  1258. ----
  1259. .Kotlin
  1260. [source,kotlin,role="secondary"]
  1261. ----
  1262. http {
  1263. authorizeHttpRequests {
  1264. shouldFilterAllDispatcherTypes = true
  1265. authorize(DispatcherTypeRequestMatcher(FORWARD, INCLUDE), permitAll)
  1266. authorize("/app/**", hasRole("APP"))
  1267. // ...
  1268. authorize(anyRequest, denyAll)
  1269. }
  1270. }
  1271. ----
  1272. .Xml
  1273. [source,xml,role="secondary"]
  1274. ----
  1275. <http filter-all-dispatcher-types="true" use-authorization-manager="true">
  1276. <intercept-url request-matcher-ref="dispatchers"/>
  1277. <intercept-url pattern="/app/*" access="hasRole('APP')"/>
  1278. <!-- ... -->
  1279. <intercept-url pattern="/**" access="denyAll"/>
  1280. </http>
  1281. <bean id="dispatchers" class="org.springframework.security.web.util.matcher.DispatcherTypeRequestMatcher">
  1282. <constructor-arg>
  1283. <util:list value-type="javax.servlet.DispatcherType">
  1284. <value>FORWARD</value>
  1285. <value>INCLUDE</value>
  1286. </util:list>
  1287. </constructor-arg>
  1288. </bean>
  1289. ----
  1290. ====
  1291. Or, if that doesn't work, then you can explicitly opt out of the behavior by setting `filter-all-dispatcher-types` and `filterAllDispatcherTypes` to `false`:
  1292. ====
  1293. .Java
  1294. [source,java,role="primary"]
  1295. ----
  1296. http
  1297. .authorizeHttpRequests((authorize) -> authorize
  1298. .filterAllDispatcherTypes(false)
  1299. .mvcMatchers("/app/**").hasRole("APP")
  1300. // ...
  1301. )
  1302. // ...
  1303. ----
  1304. .Kotlin
  1305. [source,kotlin,role="secondary"]
  1306. ----
  1307. http {
  1308. authorizeHttpRequests {
  1309. filterAllDispatcherTypes = false
  1310. authorize("/messages/**", hasRole("APP"))
  1311. // ...
  1312. }
  1313. }
  1314. ----
  1315. .Xml
  1316. [source,xml,role="secondary"]
  1317. ----
  1318. <http filter-all-dispatcher-types="false" use-authorization-manager="true">
  1319. <intercept-url pattern="/app/*" access="hasRole('APP')"/>
  1320. <!-- ... -->
  1321. </http>
  1322. ----
  1323. ====
  1324. or, if you are still using `authorizeRequests` or `use-authorization-manager="false"`, set `oncePerRequest` to `true`:
  1325. ====
  1326. .Java
  1327. [source,java,role="primary"]
  1328. ----
  1329. http
  1330. .authorizeRequests((authorize) -> authorize
  1331. .filterSecurityInterceptorOncePerRequest(true)
  1332. .mvcMatchers("/app/**").hasRole("APP")
  1333. // ...
  1334. )
  1335. // ...
  1336. ----
  1337. .Kotlin
  1338. [source,kotlin,role="secondary"]
  1339. ----
  1340. http {
  1341. authorizeRequests {
  1342. filterSecurityInterceptorOncePerRequest = true
  1343. authorize("/messages/**", hasRole("APP"))
  1344. // ...
  1345. }
  1346. }
  1347. ----
  1348. .Xml
  1349. [source,xml,role="secondary"]
  1350. ----
  1351. <http once-per-request="true" use-authorization-manager="false">
  1352. <intercept-url pattern="/app/*" access="hasRole('APP')"/>
  1353. <!-- ... -->
  1354. </http>
  1355. ----
  1356. ====
  1357. ==== I cannot declare an authorization rule for all requests
  1358. If you are having trouble setting an `anyRequest` authorization rule of `denyAll`, please use {security-api-url}org/springframework/security/config/annotation/web/configurers/ExpressionUrlAuthorizationConfigurer.AuthorizedUrl.html#permitAll()[`permitAll`] instead, like so:
  1359. ====
  1360. .Java
  1361. [source,java,role="primary"]
  1362. ----
  1363. http
  1364. .authorizeHttpReqeusts((authorize) -> authorize
  1365. .mvcMatchers("/app/*").hasRole("APP")
  1366. // ...
  1367. .anyRequest().permitAll()
  1368. )
  1369. ----
  1370. .Kotlin
  1371. [source,kotlin,role="secondary"]
  1372. ----
  1373. http {
  1374. authorizeHttpRequests {
  1375. authorize("/app*", hasRole("APP"))
  1376. // ...
  1377. authorize(anyRequest, permitAll)
  1378. }
  1379. }
  1380. ----
  1381. .Xml
  1382. [source,xml,role="secondary"]
  1383. ----
  1384. <http>
  1385. <intercept-url pattern="/app/*" access="hasRole('APP')"/>
  1386. <!-- ... -->
  1387. <intercept-url pattern="/**" access="permitAll"/>
  1388. </http>
  1389. ----
  1390. ====
  1391. ==== I cannot migrate my SpEL or my `AccessDecisionManager`
  1392. If you are having trouble with SpEL, `AccessDecisionManager`, or there is some other feature that you are needing to keep using in `<http>` or `authorizeRequests`, try the following.
  1393. First, if you still need `authorizeRequests`, you are welcome to keep using it. Even though it is deprecated, it is not removed in 6.0.
  1394. Second, if you still need your custom `access-decision-manager-ref` or have some other reason to opt out of `AuthorizationManager`, do:
  1395. ====
  1396. .Xml
  1397. [source,xml,role="secondary"]
  1398. ----
  1399. <http use-authorization-manager="false">
  1400. <intercept-url pattern="/app/*" access="hasRole('APP')"/>
  1401. <!-- ... -->
  1402. </http>
  1403. ----
  1404. ====