123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674 |
- = Authorization Migrations
- The following steps relate to changes around how authorization is performed.
- == Use `AuthorizationManager` for Method Security
- 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.
- 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.
- [[servlet-replace-globalmethodsecurity-with-methodsecurity]]
- === 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]
- {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.
- 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.
- This means that the following two listings are functionally equivalent:
- ====
- .Java
- [source,java,role="primary"]
- ----
- @EnableGlobalMethodSecurity(prePostEnabled = true)
- ----
- .Kotlin
- [source,kotlin,role="secondary"]
- ----
- @EnableGlobalMethodSecurity(prePostEnabled = true)
- ----
- .Xml
- [source,xml,role="secondary"]
- ----
- <global-method-security pre-post-enabled="true"/>
- ----
- ====
- and:
- ====
- .Java
- [source,java,role="primary"]
- ----
- @EnableMethodSecurity
- ----
- .Kotlin
- [source,kotlin,role="secondary"]
- ----
- @EnableMethodSecurity
- ----
- .Xml
- [source,xml,role="secondary"]
- ----
- <method-security/>
- ----
- ====
- For applications not using the pre-post annotations, make sure to turn it off to avoid activating unwanted behavior.
- For example, a listing like:
- ====
- .Java
- [source,java,role="primary"]
- ----
- @EnableGlobalMethodSecurity(securedEnabled = true)
- ----
- .Kotlin
- [source,kotlin,role="secondary"]
- ----
- @EnableGlobalMethodSecurity(securedEnabled = true)
- ----
- .Xml
- [source,xml,role="secondary"]
- ----
- <global-method-security secured-enabled="true"/>
- ----
- ====
- should change to:
- ====
- .Java
- [source,java,role="primary"]
- ----
- @EnableMethodSecurity(securedEnabled = true, prePostEnabled = false)
- ----
- .Kotlin
- [source,kotlin,role="secondary"]
- ----
- @EnableMethodSecurity(securedEnabled = true, prePostEnabled = false)
- ----
- .Xml
- [source,xml,role="secondary"]
- ----
- <method-security secured-enabled="true" pre-post-enabled="false"/>
- ----
- ====
- === Use a Custom `@Bean` instead of subclassing `DefaultMethodSecurityExpressionHandler`
- As a performance optimization, a new method was introduced to `MethodSecurityExpressionHandler` that takes a `Supplier<Authentication>` instead of an `Authentication`.
- This allows Spring Security to defer the lookup of the `Authentication`, and is taken advantage of automatically when you use `@EnableMethodSecurity` instead of `@EnableGlobalMethodSecurity`.
- However, let's say that your code extends `DefaultMethodSecurityExpressionHandler` and overrides `createSecurityExpressionRoot(Authentication, MethodInvocation)` to return a custom `SecurityExpressionRoot` instance.
- This will no longer work because the arrangement that `@EnableMethodSecurity` sets up calls `createEvaluationContext(Supplier<Authentication>, MethodInvocation)` instead.
- Happily, such a level of customization is often unnecessary.
- Instead, you can create a custom bean with the authorization methods that you need.
- For example, let's say you are wanting a custom evaluation of `@PostAuthorize("hasAuthority('ADMIN')")`.
- You can create a custom `@Bean` like this one:
- ====
- .Java
- [source,java,role="primary"]
- ----
- class MyAuthorizer {
- boolean isAdmin(MethodSecurityExpressionOperations root) {
- boolean decision = root.hasAuthority("ADMIN");
- // custom work ...
- return decision;
- }
- }
- ----
- .Kotlin
- [source,kotlin,role="secondary"]
- ----
- class MyAuthorizer {
- fun isAdmin(val root: MethodSecurityExpressionOperations): boolean {
- val decision = root.hasAuthority("ADMIN");
- // custom work ...
- return decision;
- }
- }
- ----
- ====
- and then refer to it in the annotation like so:
- ====
- .Java
- [source,java,role="primary"]
- ----
- @PreAuthorize("@authz.isAdmin(#root)")
- ----
- .Kotlin
- [source,kotlin,role="secondary"]
- ----
- @PreAuthorize("@authz.isAdmin(#root)")
- ----
- ====
- ==== I'd still prefer to subclass `DefaultMethodSecurityExpressionHandler`
- If you must continue subclassing `DefaultMethodSecurityExpressionHandler`, you can still do so.
- Instead, override the `createEvaluationContext(Supplier<Authentication>, MethodInvocation)` method like so:
- ====
- .Java
- [source,java,role="primary"]
- ----
- @Component
- class MyExpressionHandler extends DefaultMethodSecurityExpressionHandler {
- @Override
- public EvaluationContext createEvaluationContext(
- Supplier<Authentication> authentication, MethodInvocation mi) {
- StandardEvaluationContext context = (StandardEvaluationContext) super.createEvaluationContext(authentication, mi);
- MySecurityExpressionRoot root = new MySecurityExpressionRoot(authentication, invocation);
- root.setPermissionEvaluator(getPermissionEvaluator());
- root.setTrustResolver(new AuthenticationTrustResolverImpl());
- root.setRoleHierarchy(getRoleHierarchy());
- context.setRootObject(root);
- return context;
- }
- }
- ----
- .Kotlin
- [source,kotlin,role="secondary"]
- ----
- @Component
- class MyExpressionHandler: DefaultMethodSecurityExpressionHandler {
- override fun createEvaluationContext(val authentication: Supplier<Authentication>,
- val mi: MethodInvocation): EvaluationContext {
- val context = super.createEvaluationContext(authentication, mi) as StandardEvaluationContext;
- val root = new MySecurityExpressionRoot(authentication, invocation);
- root.setPermissionEvaluator(getPermissionEvaluator());
- root.setTrustResolver(new AuthenticationTrustResolverImpl());
- root.setRoleHierarchy(getRoleHierarchy());
- context.setRootObject(root);
- return context;
- }
- }
- ----
- ====
- ==== Opt-out Steps
- If you need to opt-out of these changes, you can use `@EnableGlobalMethodSecurity` instead of `@EnableMethodSecurity`
- [[servlet-replace-permissionevaluator-bean-with-methodsecurityexpression-handler]]
- === Publish a `MethodSecurityExpressionHandler` instead of a `PermissionEvaluator`
- `@EnableMethodSecurity` does not pick up a `PermissionEvaluator`.
- This helps keep its API simple.
- If you have a custom {security-api-url}org/springframework/security/access/PermissionEvaluator.html[`PermissionEvaluator`] `@Bean`, please change it from:
- ====
- .Java
- [source,java,role="primary"]
- ----
- @Bean
- static PermissionEvaluator permissionEvaluator() {
- // ... your evaluator
- }
- ----
- .Kotlin
- [source,kotlin,role="secondary"]
- ----
- companion object {
- @Bean
- fun permissionEvaluator(): PermissionEvaluator {
- // ... your evaluator
- }
- }
- ----
- ====
- to:
- ====
- .Java
- [source,java,role="primary"]
- ----
- @Bean
- static MethodSecurityExpressionHandler expressionHandler() {
- var expressionHandler = new DefaultMethodSecurityExpressionHandler();
- expressionHandler.setPermissionEvaluator(myPermissionEvaluator);
- return expressionHandler;
- }
- ----
- .Kotlin
- [source,kotlin,role="secondary"]
- ----
- companion object {
- @Bean
- fun expressionHandler(): MethodSecurityExpressionHandler {
- val expressionHandler = DefaultMethodSecurityExpressionHandler
- expressionHandler.setPermissionEvaluator(myPermissionEvaluator)
- return expressionHandler
- }
- }
- ----
- ====
- === Replace any custom method-security ``AccessDecisionManager``s
- 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.
- The preparation strategy will depend on your reason for each arrangement.
- Read on to find the best match for your situation.
- ==== I use `UnanimousBased`
- 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`].
- However, if you do discover that you cannot accept the default authorization managers, you can use `AuthorizationManagers.allOf` to compose your own arrangement.
- 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`].
- ==== I use `AffirmativeBased`
- 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:
- ====
- .Java
- [source,java,role="primary"]
- ----
- AuthorizationManager<MethodInvocation> authorization = AuthorizationManagers.anyOf(
- // ... your list of authorization managers
- )
- ----
- .Kotlin
- [source,kotlin,role="secondary"]
- ----
- val authorization = AuthorizationManagers.anyOf(
- // ... your list of authorization managers
- )
- ----
- ====
- 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`].
- ==== I use `ConsensusBased`
- There is no framework-provided equivalent for {security-api-url}org/springframework/security/access/vote/ConsensusBased.html[`ConsensusBased`].
- 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.
- 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`].
- ==== I use a custom `AccessDecisionVoter`
- You should either change the class to implement {security-api-url}org/springframework/security/authorization/AuthorizationManager.html[`AuthorizationManager`] or create an adapter.
- Without knowing what your custom voter is doing, it is impossible to recommend a general-purpose solution.
- 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:
- ====
- .Java
- [source,java,role="primary"]
- ----
- public final class PreAuthorizeAuthorizationManagerAdapter implements AuthorizationManager<MethodInvocation> {
- private final SecurityMetadataSource metadata;
- private final AccessDecisionVoter voter;
- public PreAuthorizeAuthorizationManagerAdapter(MethodSecurityExpressionHandler expressionHandler) {
- ExpressionBasedAnnotationAttributeFactory attributeFactory =
- new ExpressionBasedAnnotationAttributeFactory(expressionHandler);
- this.metadata = new PrePostAnnotationSecurityMetadataSource(attributeFactory);
- ExpressionBasedPreInvocationAdvice expressionAdvice = new ExpressionBasedPreInvocationAdvice();
- expressionAdvice.setExpressionHandler(expressionHandler);
- this.voter = new PreInvocationAuthorizationAdviceVoter(expressionAdvice);
- }
- public AuthorizationDecision check(Supplier<Authentication> authentication, MethodInvocation invocation) {
- List<ConfigAttribute> attributes = this.metadata.getAttributes(invocation, AopUtils.getTargetClass(invocation.getThis()));
- int decision = this.voter.vote(authentication.get(), invocation, attributes);
- if (decision == ACCESS_GRANTED) {
- return new AuthorizationDecision(true);
- }
- if (decision == ACCESS_DENIED) {
- return new AuthorizationDecision(false);
- }
- return null; // abstain
- }
- }
- ----
- ====
- 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`].
- ==== I use `AfterInvocationManager` or `AfterInvocationProvider`
- {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.
- For example, in the case of method invocation, these make an authorization decision about a method's return value.
- In Spring Security 3.0, authorization decision-making was standardized into the xref:servlet/authorization/method-security.adoc[`@PostAuthorize` and `@PostFilter` annotations].
- `@PostAuthorize` is for deciding whether the return value as a whole was permitted to be returned.
- `@PostFilter` is for filtering individual entries from a returned collection, array, or stream.
- 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.
- If you've implemented your own `AfterInvocationManager` or `AfterInvocationProvider`, you should first ask yourself what it is trying to do.
- 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)")`.
- If it is trying to filter, then consider publishing a custom bean and using `@PostFilter("@mybean.authorize(#root)")`.
- Or, if needed, you can implement your own `MethodInterceptor`, taking a look at `PostFilterAuthorizationMethodInterceptor` and `PrePostMethodSecurityConfiguration` for an example.
- ==== I use `RunAsManager`
- There is currently https://github.com/spring-projects/spring-security/issues/11331[no replacement for `RunAsManager`] though one is being considered.
- It is quite straightforward to adapt a `RunAsManager`, though, to the `AuthorizationManager` API, if needed.
- Here is some pseudocode to get you started:
- ====
- .Java
- [source,java,role="primary"]
- ----
- public final class RunAsAuthorizationManagerAdapter<T> implements AuthorizationManager<T> {
- private final RunAsManager runAs = new RunAsManagerImpl();
- private final SecurityMetadataSource metadata;
- private final AuthorizationManager<T> authorization;
- // ... constructor
- public AuthorizationDecision check(Supplier<Authentication> authentication, T object) {
- Supplier<Authentication> wrapped = (auth) -> {
- List<ConfigAttribute> attributes = this.metadata.getAttributes(object);
- return this.runAs.buildRunAs(auth, object, attributes);
- };
- return this.authorization.check(wrapped, object);
- }
- }
- ----
- ====
- 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`].
- [[servlet-check-for-annotationconfigurationexceptions]]
- === Check for ``AnnotationConfigurationException``s
- `@EnableMethodSecurity` and `<method-security>` activate stricter enforcement of Spring Security's non-repeatable or otherwise incompatible annotations.
- 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.
- == Use `AuthorizationManager` for Message Security
- 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.
- 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.
- === Ensure all messages have defined authorization rules
- The now-deprecated {security-api-url}org/springframework/security/config/annotation/web/socket/AbstractSecurityWebSocketMessageBrokerConfigurer.html[message security support] permits all messages by default.
- xref:servlet/integrations/websocket.adoc[The new support] has the stronger default of denying all messages.
- To prepare for this, ensure that authorization rules exist are declared for every request.
- For example, an application configuration like:
- ====
- .Java
- [source,java,role="primary"]
- ----
- @Override
- protected void configureInbound(MessageSecurityMetadataSourceRegistry messages) {
- messages
- .simpDestMatchers("/user/queue/errors").permitAll()
- .simpDestMatchers("/admin/**").hasRole("ADMIN");
- }
- ----
- .Kotlin
- [source,kotlin,role="secondary"]
- ----
- override fun configureInbound(messages: MessageSecurityMetadataSourceRegistry) {
- messages
- .simpDestMatchers("/user/queue/errors").permitAll()
- .simpDestMatchers("/admin/**").hasRole("ADMIN")
- }
- ----
- .Xml
- [source,xml,role="secondary"]
- ----
- <websocket-message-broker>
- <intercept-message pattern="/user/queue/errors" access="permitAll"/>
- <intercept-message pattern="/admin/**" access="hasRole('ADMIN')"/>
- </websocket-message-broker>
- ----
- ====
- should change to:
- ====
- .Java
- [source,java,role="primary"]
- ----
- @Override
- protected void configureInbound(MessageSecurityMetadataSourceRegistry messages) {
- messages
- .simpTypeMatchers(CONNECT, DISCONNECT, UNSUBSCRIBE).permitAll()
- .simpDestMatchers("/user/queue/errors").permitAll()
- .simpDestMatchers("/admin/**").hasRole("ADMIN")
- .anyMessage().denyAll();
- }
- ----
- .Kotlin
- [source,kotlin,role="secondary"]
- ----
- override fun configureInbound(messages: MessageSecurityMetadataSourceRegistry) {
- messages
- .simpTypeMatchers(CONNECT, DISCONNECT, UNSUBSCRIBE).permitAll()
- .simpDestMatchers("/user/queue/errors").permitAll()
- .simpDestMatchers("/admin/**").hasRole("ADMIN")
- .anyMessage().denyAll()
- }
- ----
- .Xml
- [source,xml,role="secondary"]
- ----
- <websocket-message-broker>
- <intercept-message type="CONNECT" access="permitAll"/>
- <intercept-message type="DISCONNECT" access="permitAll"/>
- <intercept-message type="UNSUBSCRIBE" access="permitAll"/>
- <intercept-message pattern="/user/queue/errors" access="permitAll"/>
- <intercept-message pattern="/admin/**" access="hasRole('ADMIN')"/>
- <intercept-message pattern="/**" access="denyAll"/>
- </websocket-message-broker>
- ----
- ====
- === Add `@EnableWebSocketSecurity`
- [NOTE]
- ====
- If you want to have CSRF disabled and you are using Java configuration, the migration steps are slightly different.
- Instead of using `@EnableWebSocketSecurity`, you will override the appropriate methods in `WebSocketMessageBrokerConfigurer` yourself.
- Please see xref:servlet/integrations/websocket.adoc#websocket-sameorigin-disable[the reference manual] for details about this step.
- ====
- If you are using Java Configuration, add {security-api-url}org/springframework/security/config/annotation/web/socket/EnableWebSocketSecurity.html[`@EnableWebSocketSecurity`] to your application.
- For example, you can add it to your websocket security configuration class, like so:
- ====
- .Java
- [source,java,role="primary"]
- ----
- @EnableWebSocketSecurity
- @Configuration
- public class WebSocketSecurityConfig extends AbstractSecurityWebSocketMessageBrokerConfigurer {
- // ...
- }
- ----
- .Kotlin
- [source,kotlin,role="secondary"]
- ----
- @EnableWebSocketSecurity
- @Configuration
- class WebSocketSecurityConfig: AbstractSecurityWebSocketMessageBrokerConfigurer() {
- // ...
- }
- ----
- ====
- This will make a prototype instance of `MessageMatcherDelegatingAuthorizationManager.Builder` available to encourage configuration by composition instead of extension.
- === Use an `AuthorizationManager<Message<?>>` instance
- To start using `AuthorizationManager`, you can set the `use-authorization-manager` attribute in XML or you can publish an `AuthorizationManager<Message<?>>` `@Bean` in Java.
- For example, the following application configuration:
- ====
- .Java
- [source,java,role="primary"]
- ----
- @Override
- protected void configureInbound(MessageSecurityMetadataSourceRegistry messages) {
- messages
- .simpTypeMatchers(CONNECT, DISCONNECT, UNSUBSCRIBE).permitAll()
- .simpDestMatchers("/user/queue/errors").permitAll()
- .simpDestMatchers("/admin/**").hasRole("ADMIN")
- .anyMessage().denyAll();
- }
- ----
- .Kotlin
- [source,kotlin,role="secondary"]
- ----
- override fun configureInbound(messages: MessageSecurityMetadataSourceRegistry) {
- messages
- .simpTypeMatchers(CONNECT, DISCONNECT, UNSUBSCRIBE).permitAll()
- .simpDestMatchers("/user/queue/errors").permitAll()
- .simpDestMatchers("/admin/**").hasRole("ADMIN")
- .anyMessage().denyAll()
- }
- ----
- .Xml
- [source,xml,role="secondary"]
- ----
- <websocket-message-broker>
- <intercept-message type="CONNECT" access="permitAll"/>
- <intercept-message type="DISCONNECT" access="permitAll"/>
- <intercept-message type="UNSUBSCRIBE" access="permitAll"/>
- <intercept-message pattern="/user/queue/errors" access="permitAll"/>
- <intercept-message pattern="/admin/**" access="hasRole('ADMIN')"/>
- <intercept-message pattern="/**" access="denyAll"/>
- </websocket-message-broker>
- ----
- ====
- changes to:
- ====
- .Java
- [source,java,role="primary"]
- ----
- @Bean
- AuthorizationManager<Message<?>> messageSecurity(MessageMatcherDelegatingAuthorizationManager.Builder messages) {
- messages
- .simpTypeMatchers(CONNECT, DISCONNECT, UNSUBSCRIBE).permitAll()
- .simpDestMatchers("/user/queue/errors").permitAll()
- .simpDestMatchers("/admin/**").hasRole("ADMIN")
- .anyMessage().denyAll();
- return messages.build();
- }
- ----
- .Kotlin
- [source,kotlin,role="secondary"]
- ----
- @Bean
- fun messageSecurity(val messages: MessageMatcherDelegatingAuthorizationManager.Builder): AuthorizationManager<Message<?>> {
- messages
- .simpTypeMatchers(CONNECT, DISCONNECT, UNSUBSCRIBE).permitAll()
- .simpDestMatchers("/user/queue/errors").permitAll()
- .simpDestMatchers("/admin/**").hasRole("ADMIN")
- .anyMessage().denyAll()
- return messages.build()
- }
- ----
- .Xml
- [source,xml,role="secondary"]
- ----
- <websocket-message-broker use-authorization-manager="true">
- <intercept-message type="CONNECT" access="permitAll"/>
- <intercept-message type="DISCONNECT" access="permitAll"/>
- <intercept-message type="UNSUBSCRIBE" access="permitAll"/>
- <intercept-message pattern="/user/queue/errors" access="permitAll"/>
- <intercept-message pattern="/admin/**" access="hasRole('ADMIN')"/>
- <intercept-message pattern="/**" access="denyAll"/>
- </websocket-message-broker>
- ----
- ====
- === Stop Implementing `AbstractSecurityWebSocketMessageBrokerConfigurer`
- If you are using Java configuration, you can now simply extend `WebSocketMessageBrokerConfigurer`.
- For example, if your class that extends `AbstractSecurityWebSocketMessageBrokerConfigurer` is called `WebSocketSecurityConfig`, then:
- ====
- .Java
- [source,java,role="primary"]
- ----
- @EnableWebSocketSecurity
- @Configuration
- public class WebSocketSecurityConfig extends AbstractSecurityWebSocketMessageBrokerConfigurer {
- // ...
- }
- ----
- .Kotlin
- [source,kotlin,role="secondary"]
- ----
- @EnableWebSocketSecurity
- @Configuration
- class WebSocketSecurityConfig: AbstractSecurityWebSocketMessageBrokerConfigurer() {
- // ...
- }
- ----
- ====
- changes to:
- ====
- .Java
- [source,java,role="primary"]
- ----
- @EnableWebSocketSecurity
- @Configuration
- public class WebSocketSecurityConfig implements WebSocketMessageBrokerConfigurer {
- // ...
- }
- ----
- .Kotlin
- [source,kotlin,role="secondary"]
- ----
- @EnableWebSocketSecurity
- @Configuration
- class WebSocketSecurityConfig: WebSocketMessageBrokerConfigurer {
- // ...
- }
- ----
- ====
- [[servlet-authorizationmanager-messages-opt-out]]
- === Opt-out Steps
- In case you had trouble, take a look at these scenarios for optimal opt out behavior:
- ==== I cannot declare an authorization rule for all requests
- 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:
- ====
- .Java
- [source,java,role="primary"]
- ----
- @Bean
- AuthorizationManager<Message<?>> messageSecurity(MessageMatcherDelegatingAuthorizationManager.Builder messages) {
- messages
- .simpDestMatchers("/user/queue/errors").permitAll()
- .simpDestMatchers("/admin/**").hasRole("ADMIN")
- // ...
- .anyMessage().permitAll();
- return messages.build();
- }
- ----
- .Kotlin
- [source,kotlin,role="secondary"]
- ----
- @Bean
- fun messageSecurity(val messages: MessageMatcherDelegatingAuthorizationManager.Builder): AuthorizationManager<Message<?>> {
- messages
- .simpDestMatchers("/user/queue/errors").permitAll()
- .simpDestMatchers("/admin/**").hasRole("ADMIN")
- // ...
- .anyMessage().permitAll();
- return messages.build()
- }
- ----
- .Xml
- [source,xml,role="secondary"]
- ----
- <websocket-message-broker use-authorization-manager="true">
- <intercept-message pattern="/user/queue/errors" access="permitAll"/>
- <intercept-message pattern="/admin/**" access="hasRole('ADMIN')"/>
- <!-- ... -->
- <intercept-message pattern="/**" access="permitAll"/>
- </websocket-message-broker>
- ----
- ====
- ==== I cannot get CSRF working, need some other `AbstractSecurityWebSocketMessageBrokerConfigurer` feature, or am having trouble with `AuthorizationManager`
- In the case of Java, you may continue using `AbstractMessageSecurityWebSocketMessageBrokerConfigurer`.
- Even though it is deprecated, it will not be removed in 6.0.
- In the case of XML, you can opt out of `AuthorizationManager` by setting `use-authorization-manager="false"`:
- ====
- .Xml
- [source,xml,role="secondary"]
- ----
- <websocket-message-broker>
- <intercept-message pattern="/user/queue/errors" access="permitAll"/>
- <intercept-message pattern="/admin/**" access="hasRole('ADMIN')"/>
- </websocket-message-broker>
- ----
- ====
- to:
- ====
- .Xml
- [source,xml,role="secondary"]
- ----
- <websocket-message-broker use-authorization-manager="false">
- <intercept-message pattern="/user/queue/errors" access="permitAll"/>
- <intercept-message pattern="/admin/**" access="hasRole('ADMIN')"/>
- </websocket-message-broker>
- ----
- ====
- == Use `AuthorizationManager` for Request Security
- 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].
- 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.
- === Ensure that all requests have defined authorization rules
- In Spring Security 5.8 and earlier, requests with no authorization rule are permitted by default.
- It is a stronger security position to deny by default, thus requiring that authorization rules be clearly defined for every endpoint.
- As such, in 6.0, Spring Security by default denies any request that is missing an authorization rule.
- 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.
- 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.
- [NOTE]
- ====
- You may already have an `anyRequest` rule defined that you are happy with in which case this step can be skipped.
- ====
- Adding `denyAll` to the end looks like changing:
- ====
- .Java
- [source,java,role="primary"]
- ----
- http
- .authorizeRequests((authorize) -> authorize
- .filterSecurityInterceptorOncePerRequest(true)
- .mvcMatchers("/app/**").hasRole("APP")
- // ...
- )
- // ...
- ----
- .Kotlin
- [source,kotlin,role="secondary"]
- ----
- http {
- authorizeRequests {
- filterSecurityInterceptorOncePerRequest = true
- authorize("/app/**", hasRole("APP"))
- // ...
- }
- }
- ----
- .Xml
- [source,xml,role="secondary"]
- ----
- <http once-per-request="true">
- <intercept-url pattern="/app/*" access="hasRole('APP')"/>
- <!-- ... -->
- </http>
- ----
- ====
- to:
- ====
- .Java
- [source,java,role="primary"]
- ----
- http
- .authorizeRequests((authorize) -> authorize
- .filterSecurityInterceptorOncePerRequest(true)
- .mvcMatchers("/app/**").hasRole("APP")
- // ...
- .anyRequest().denyAll()
- )
- // ...
- ----
- .Kotlin
- [source,kotlin,role="secondary"]
- ----
- http {
- authorizeRequests {
- filterSecurityInterceptorOncePerRequest = true
- authorize("/app/**", hasRole("APP"))
- // ...
- authorize(anyRequest, denyAll)
- }
- }
- ----
- .Xml
- [source,xml,role="secondary"]
- ----
- <http once-per-request="true">
- <intercept-url pattern="/app/*" access="hasRole('APP')"/>
- <!-- ... -->
- <intercept-url pattern="/**" access="denyAll"/>
- </http>
- ----
- ====
- If you have already migrated to `authorizeHttpRequests`, the recommended change is the same.
- === Switch to `AuthorizationManager`
- 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.
- Change:
- ====
- .Java
- [source,java,role="primary"]
- ----
- http
- .authorizeRequests((authorize) -> authorize
- .filterSecurityInterceptorOncePerRequest(true)
- .mvcMatchers("/app/**").hasRole("APP")
- // ...
- .anyRequest().denyAll()
- )
- // ...
- ----
- .Kotlin
- [source,kotlin,role="secondary"]
- ----
- http {
- authorizeRequests {
- filterSecurityInterceptorOncePerRequest = true
- authorize("/app/**", hasRole("APP"))
- // ...
- authorize(anyRequest, denyAll)
- }
- }
- ----
- .Xml
- [source,xml,role="secondary"]
- ----
- <http once-per-request="true">
- <intercept-url pattern="/app/*" access="hasRole('APP')"/>
- <!-- ... -->
- <intercept-url pattern="/**" access="denyAll"/>
- </http>
- ----
- ====
- to:
- ====
- .Java
- [source,java,role="primary"]
- ----
- http
- .authorizeHttpRequests((authorize) -> authorize
- .shouldFilterAllDispatcherTypes(false)
- .mvcMatchers("/app/**").hasRole("APP")
- // ...
- .anyRequest().denyAll()
- )
- // ...
- ----
- .Kotlin
- [source,kotlin,role="secondary"]
- ----
- http {
- authorizeHttpRequests {
- shouldFilterAllDispatcherTypes = false
- authorize("/app/**", hasRole("APP"))
- // ...
- authorize(anyRequest, denyAll)
- }
- }
- ----
- .Xml
- [source,xml,role="secondary"]
- ----
- <http filter-all-dispatcher-types="false" use-authorization-manager="true">
- <intercept-url pattern="/app/*" access="hasRole('APP')"/>
- <!-- ... -->
- <intercept-url pattern="/**" access="denyAll"/>
- </http>
- ----
- ====
- === Migrate SpEL expressions to `AuthorizationManager`
- For authorization rules, Java tends to be easier to test and maintain than SpEL.
- As such, `authorizeHttpRequests` does not have a method for declaring a `String` SpEL.
- Instead, you can implement your own `AuthorizationManager` implementation or use `WebExpressionAuthorizationManager`.
- For completeness, both options will be demonstrated.
- First, if you have the following SpEL:
- ====
- .Java
- [source,java,role="primary"]
- ----
- http
- .authorizeRequests((authorize) -> authorize
- .filterSecurityInterceptorOncePerRequest(true)
- .mvcMatchers("/complicated/**").access("hasRole('ADMIN') || hasAuthority('SCOPE_read')")
- // ...
- .anyRequest().denyAll()
- )
- // ...
- ----
- .Kotlin
- [source,kotlin,role="secondary"]
- ----
- http {
- authorizeRequests {
- filterSecurityInterceptorOncePerRequest = true
- authorize("/complicated/**", access("hasRole('ADMIN') || hasAuthority('SCOPE_read')"))
- // ...
- authorize(anyRequest, denyAll)
- }
- }
- ----
- ====
- Then you can compose your own `AuthorizationManager` with Spring Security authorization primitives like so:
- ====
- .Java
- [source,java,role="primary"]
- ----
- http
- .authorizeHttpRequests((authorize) -> authorize
- .shouldFilterAllDispatcherTypes(false)
- .mvcMatchers("/complicated/**").access(anyOf(hasRole("ADMIN"), hasAuthority("SCOPE_read"))
- // ...
- .anyRequest().denyAll()
- )
- // ...
- ----
- .Kotlin
- [source,kotlin,role="secondary"]
- ----
- http {
- authorizeHttpRequests {
- shouldFilterAllDispatcherTypes = false
- authorize("/complicated/**", access(anyOf(hasRole("ADMIN"), hasAuthority("SCOPE_read"))
- // ...
- authorize(anyRequest, denyAll)
- }
- }
- ----
- ====
- Or you can use `WebExpressionAuthorizationManager` in the following way:
- ====
- .Java
- [source,java,role="primary"]
- ----
- http
- .authorizeRequests((authorize) -> authorize
- .filterSecurityInterceptorOncePerRequest(true)
- .mvcMatchers("/complicated/**").access(
- new WebExpressionAuthorizationManager("hasRole('ADMIN') || hasAuthority('SCOPE_read')")
- )
- // ...
- .anyRequest().denyAll()
- )
- // ...
- ----
- .Kotlin
- [source,kotlin,role="secondary"]
- ----
- http {
- authorizeRequests {
- filterSecurityInterceptorOncePerRequest = true
- authorize("/complicated/**", access(
- WebExpressionAuthorizationManager("hasRole('ADMIN') || hasAuthority('SCOPE_read')"))
- )
- // ...
- authorize(anyRequest, denyAll)
- }
- }
- ----
- ====
- [[switch-filter-all-dispatcher-types]]
- === Switch to filter all dispatcher types
- Spring Security 5.8 and earlier only xref:servlet/authorization/architecture.adoc[perform authorization] once per request.
- This means that dispatcher types like `FORWARD` and `INCLUDE` that run after `REQUEST` are not secured by default.
- It's recommended that Spring Security secure all dispatch types.
- As such, in 6.0, Spring Security changes this default.
- So, finally, change your authorization rules to filter all dispatcher types.
- To do this, you should change:
- ====
- .Java
- [source,java,role="primary"]
- ----
- http
- .authorizeHttpRequests((authorize) -> authorize
- .shouldFilterAllDispatcherTypes(false)
- .mvcMatchers("/app/**").hasRole("APP")
- // ...
- .anyRequest().denyAll()
- )
- // ...
- ----
- .Kotlin
- [source,kotlin,role="secondary"]
- ----
- http {
- authorizeHttpRequests {
- shouldFilterAllDispatcherTypes = false
- authorize("/app/**", hasRole("APP"))
- // ...
- authorize(anyRequest, denyAll)
- }
- }
- ----
- .Xml
- [source,xml,role="secondary"]
- ----
- <http filter-all-dispatcher-types="false" use-authorization-manager="true">
- <intercept-url pattern="/app/*" access="hasRole('APP')"/>
- <!-- ... -->
- <intercept-url pattern="/**" access="denyAll"/>
- </http>
- ----
- ====
- to:
- ====
- .Java
- [source,java,role="primary"]
- ----
- http
- .authorizeHttpRequests((authorize) -> authorize
- .shouldFilterAllDispatcherTypes(true)
- .mvcMatchers("/app/**").hasRole("APP")
- // ...
- .anyRequest().denyAll()
- )
- // ...
- ----
- .Kotlin
- [source,kotlin,role="secondary"]
- ----
- http {
- authorizeHttpRequests {
- shouldFilterAllDispatcherTypes = true
- authorize("/app/**", hasRole("APP"))
- // ...
- authorize(anyRequest, denyAll)
- }
- }
- ----
- .Xml
- [source,xml,role="secondary"]
- ----
- <http filter-all-dispatcher-types="true" use-authorization-manager="true">
- <intercept-url pattern="/app/*" access="hasRole('APP')"/>
- <!-- ... -->
- <intercept-url pattern="/**" access="denyAll"/>
- </http>
- ----
- ====
- And, the `FilterChainProxy` should be registered for all dispatcher types as well.
- 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:
- ====
- .application.properties
- [source,properties,role="primary"]
- ----
- spring.security.filter.dispatcher-types=request,async,error,forward,include
- ----
- ====
- If you are xref:servlet/configuration/java.adoc#_abstractsecuritywebapplicationinitializer[using the `AbstractSecurityWebApplicationInitializer`] you should override the `getSecurityDispatcherTypes` method and return all dispatcher types:
- ====
- .Java
- [source,java,role="primary"]
- ----
- import org.springframework.security.web.context.*;
- public class SecurityWebApplicationInitializer extends AbstractSecurityWebApplicationInitializer {
- @Override
- protected EnumSet<DispatcherType> getSecurityDispatcherTypes() {
- return EnumSet.of(DispatcherType.REQUEST, DispatcherType.ERROR, DispatcherType.ASYNC,
- DispatcherType.FORWARD, DispatcherType.INCLUDE);
- }
- }
- ----
- ====
- ==== Permit `FORWARD` when using Spring MVC
- 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.
- This is because when Spring MVC detects a mapping between view name and the actual views, it will perform a forward to the view.
- As we saw on the <<switch-filter-all-dispatcher-types,previous section>>, Spring Security 6.0 will apply authorization to `FORWARD` requests by default.
- Consider the following common configuration:
- ====
- .Java
- [source,java,role="primary"]
- ----
- @Bean
- public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
- http
- .authorizeHttpRequests((authorize) -> authorize
- .shouldFilterAllDispatcherTypes(true)
- .requestMatchers("/").authenticated()
- .anyRequest().denyAll()
- )
- .formLogin((form) -> form
- .loginPage("/login")
- .permitAll()
- ));
- return http.build();
- }
- ----
- ====
- and one of the following equivalents MVC view mapping configurations:
- ====
- .Java
- [source,java,role="primary"]
- ----
- @Controller
- public class MyController {
- @GetMapping("/login")
- public String login() {
- return "login";
- }
- }
- ----
- ====
- ====
- .Java
- [source,java,role="primary"]
- ----
- @Configuration
- public class MyWebMvcConfigurer implements WebMvcConfigurer {
- @Override
- public void addViewControllers(ViewControllerRegistry registry) {
- registry.addViewController("/login").setViewName("login");
- }
- }
- ----
- ====
- 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.
- 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`.
- To fix this, you should configure Spring Security to permit `FORWARD` requests:
- ====
- .Java
- [source,java,role="primary"]
- ----
- http
- .authorizeHttpRequests((authorize) -> authorize
- .shouldFilterAllDispatcherTypes(true)
- .dispatcherTypeMatchers(DispatcherType.FORWARD).permitAll()
- .anyRequest().denyAll()
- )
- // ...
- ----
- .Kotlin
- [source,kotlin,role="secondary"]
- ----
- http {
- authorizeHttpRequests {
- shouldFilterAllDispatcherTypes = true
- authorize(DispatcherTypeRequestMatcher(DispatcherType.FORWARD), permitAll)
- authorize(anyRequest, denyAll)
- }
- }
- ----
- .Xml
- [source,xml,role="secondary"]
- ----
- <http filter-all-dispatcher-types="true" use-authorization-manager="true">
- <intercept-url request-matcher-ref="forwardRequestMatcher" access="permitAll()" />
- <!-- ... -->
- <intercept-url pattern="/**" access="denyAll"/>
- </http>
- <bean name="forwardRequestMatcher" class="org.springframework.security.web.util.matcher.DispatcherTypeRequestMatcher">
- <constructor-arg value="FORWARD"/>
- </bean>
- ----
- ====
- === Replace any custom filter-security ``AccessDecisionManager``s
- 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.
- The preparation strategy will depend on your reason for each arrangement.
- Read on to find the best match for your situation.
- ==== I use `UnanimousBased`
- 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:
- ====
- .Java
- [source,java,role="primary"]
- ----
- @Bean
- AuthorizationManager<RequestAuthorizationContext> requestAuthorization() {
- PolicyAuthorizationManager policy = ...;
- LocalAuthorizationManager local = ...;
- return AuthorizationMangers.allOf(policy, local);
- }
- ----
- .Kotlin
- [source,kotlin,role="secondary"]
- ----
- @Bean
- fun requestAuthorization(): AuthorizationManager<RequestAuthorizationContext> {
- val policy: PolicyAuthorizationManager = ...
- val local: LocalAuthorizationManager = ...
- return AuthorizationMangers.allOf(policy, local)
- }
- ----
- .Xml
- [source,xml,role="secondary"]
- ----
- <bean id="requestAuthorization" class="org.springframework.security.authorization.AuthorizationManagers"
- factory-method="allOf">
- <constructor-arg>
- <util:list>
- <bean class="my.PolicyAuthorizationManager"/>
- <bean class="my.LocalAuthorizationManager"/>
- </util:list>
- </constructor-arg>
- </bean>
- ----
- ====
- then, wire it into the DSL like so:
- ====
- .Java
- [source,java,role="primary"]
- ----
- http
- .authorizeHttpRequests((authorize) -> authorize.anyRequest().access(requestAuthorization))
- // ...
- ----
- .Kotlin
- [source,kotlin,role="secondary"]
- ----
- http {
- authorizeHttpRequests {
- authorize(anyRequest, requestAuthorization)
- }
- // ...
- }
- ----
- .Xml
- [source,xml,role="secondary"]
- ----
- <http authorization-manager-ref="requestAuthorization"/>
- ----
- ====
- [NOTE]
- ====
- `authorizeHttpRequests` is designed so that you can apply a custom `AuthorizationManager` to any url pattern.
- See xref:servlet/authorization/authorize-http-requests.adoc#custom-authorization-manager[the reference] for more details.
- ====
- ==== I use `AffirmativeBased`
- 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:
- ====
- .Java
- [source,java,role="primary"]
- ----
- @Bean
- AuthorizationManager<RequestAuthorizationContext> requestAuthorization() {
- PolicyAuthorizationManager policy = ...;
- LocalAuthorizationManager local = ...;
- return AuthorizationMangers.anyOf(policy, local);
- }
- ----
- .Kotlin
- [source,kotlin,role="secondary"]
- ----
- @Bean
- fun requestAuthorization(): AuthorizationManager<RequestAuthorizationContext> {
- val policy: PolicyAuthorizationManager = ...
- val local: LocalAuthorizationManager = ...
- return AuthorizationMangers.anyOf(policy, local)
- }
- ----
- .Xml
- [source,xml,role="secondary"]
- ----
- <bean id="requestAuthorization" class="org.springframework.security.authorization.AuthorizationManagers"
- factory-method="anyOf">
- <constructor-arg>
- <util:list>
- <bean class="my.PolicyAuthorizationManager"/>
- <bean class="my.LocalAuthorizationManager"/>
- </util:list>
- </constructor-arg>
- </bean>
- ----
- ====
- then, wire it into the DSL like so:
- ====
- .Java
- [source,java,role="primary"]
- ----
- http
- .authorizeHttpRequests((authorize) -> authorize.anyRequest().access(requestAuthorization))
- // ...
- ----
- .Kotlin
- [source,kotlin,role="secondary"]
- ----
- http {
- authorizeHttpRequests {
- authorize(anyRequest, requestAuthorization)
- }
- // ...
- }
- ----
- .Xml
- [source,xml,role="secondary"]
- ----
- <http authorization-manager-ref="requestAuthorization"/>
- ----
- ====
- [NOTE]
- ====
- `authorizeHttpRequests` is designed so that you can apply a custom `AuthorizationManager` to any url pattern.
- See xref:servlet/authorization/authorize-http-requests.adoc#custom-authorization-manager[the reference] for more details.
- ====
- ==== I use `ConsensusBased`
- There is no framework-provided equivalent for {security-api-url}org/springframework/security/access/vote/ConsensusBased.html[`ConsensusBased`].
- 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.
- 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`].
- ==== I use a custom `AccessDecisionVoter`
- You should either change the class to implement {security-api-url}org/springframework/security/authorization/AuthorizationManager.html[`AuthorizationManager`] or create an adapter.
- Without knowing what your custom voter is doing, it is impossible to recommend a general-purpose solution.
- 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:
- ====
- .Java
- [source,java,role="primary"]
- ----
- public final class AnyRequestAuthenticatedAuthorizationManagerAdapter implements AuthorizationManager<RequestAuthorizationContext> {
- private final SecurityMetadataSource metadata;
- private final AccessDecisionVoter voter;
- public PreAuthorizeAuthorizationManagerAdapter(SecurityExpressionHandler expressionHandler) {
- Map<RequestMatcher, List<ConfigAttribute>> requestMap = Collections.singletonMap(
- AnyRequestMatcher.INSTANCE, Collections.singletonList(new SecurityConfig("authenticated")));
- this.metadata = new DefaultFilterInvocationSecurityMetadataSource(requestMap);
- WebExpressionVoter voter = new WebExpressionVoter();
- voter.setExpressionHandler(expressionHandler);
- this.voter = voter;
- }
- public AuthorizationDecision check(Supplier<Authentication> authentication, RequestAuthorizationContext context) {
- List<ConfigAttribute> attributes = this.metadata.getAttributes(context);
- int decision = this.voter.vote(authentication.get(), invocation, attributes);
- if (decision == ACCESS_GRANTED) {
- return new AuthorizationDecision(true);
- }
- if (decision == ACCESS_DENIED) {
- return new AuthorizationDecision(false);
- }
- return null; // abstain
- }
- }
- ----
- ====
- 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`].
- [[servlet-authorizationmanager-requests-opt-out]]
- === Opt-out Steps
- In case you had trouble, take a look at these scenarios for optimal opt out behavior:
- ==== I cannot secure all dispatcher types
- If you cannot secure all dispatcher types, first try and declare which dispatcher types should not require authorization like so:
- ====
- .Java
- [source,java,role="primary"]
- ----
- http
- .authorizeHttpRequests((authorize) -> authorize
- .shouldFilterAllDispatcherTypes(true)
- .dispatcherTypeMatchers(FORWARD, INCLUDE).permitAll()
- .mvcMatchers("/app/**").hasRole("APP")
- // ...
- .anyRequest().denyAll()
- )
- // ...
- ----
- .Kotlin
- [source,kotlin,role="secondary"]
- ----
- http {
- authorizeHttpRequests {
- shouldFilterAllDispatcherTypes = true
- authorize(DispatcherTypeRequestMatcher(FORWARD, INCLUDE), permitAll)
- authorize("/app/**", hasRole("APP"))
- // ...
- authorize(anyRequest, denyAll)
- }
- }
- ----
- .Xml
- [source,xml,role="secondary"]
- ----
- <http filter-all-dispatcher-types="true" use-authorization-manager="true">
- <intercept-url request-matcher-ref="dispatchers"/>
- <intercept-url pattern="/app/*" access="hasRole('APP')"/>
- <!-- ... -->
- <intercept-url pattern="/**" access="denyAll"/>
- </http>
- <bean id="dispatchers" class="org.springframework.security.web.util.matcher.DispatcherTypeRequestMatcher">
- <constructor-arg>
- <util:list value-type="javax.servlet.DispatcherType">
- <value>FORWARD</value>
- <value>INCLUDE</value>
- </util:list>
- </constructor-arg>
- </bean>
- ----
- ====
- 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`:
- ====
- .Java
- [source,java,role="primary"]
- ----
- http
- .authorizeHttpRequests((authorize) -> authorize
- .filterAllDispatcherTypes(false)
- .mvcMatchers("/app/**").hasRole("APP")
- // ...
- )
- // ...
- ----
- .Kotlin
- [source,kotlin,role="secondary"]
- ----
- http {
- authorizeHttpRequests {
- filterAllDispatcherTypes = false
- authorize("/messages/**", hasRole("APP"))
- // ...
- }
- }
- ----
- .Xml
- [source,xml,role="secondary"]
- ----
- <http filter-all-dispatcher-types="false" use-authorization-manager="true">
- <intercept-url pattern="/app/*" access="hasRole('APP')"/>
- <!-- ... -->
- </http>
- ----
- ====
- or, if you are still using `authorizeRequests` or `use-authorization-manager="false"`, set `oncePerRequest` to `true`:
- ====
- .Java
- [source,java,role="primary"]
- ----
- http
- .authorizeRequests((authorize) -> authorize
- .filterSecurityInterceptorOncePerRequest(true)
- .mvcMatchers("/app/**").hasRole("APP")
- // ...
- )
- // ...
- ----
- .Kotlin
- [source,kotlin,role="secondary"]
- ----
- http {
- authorizeRequests {
- filterSecurityInterceptorOncePerRequest = true
- authorize("/messages/**", hasRole("APP"))
- // ...
- }
- }
- ----
- .Xml
- [source,xml,role="secondary"]
- ----
- <http once-per-request="true" use-authorization-manager="false">
- <intercept-url pattern="/app/*" access="hasRole('APP')"/>
- <!-- ... -->
- </http>
- ----
- ====
- ==== I cannot declare an authorization rule for all requests
- 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:
- ====
- .Java
- [source,java,role="primary"]
- ----
- http
- .authorizeHttpReqeusts((authorize) -> authorize
- .mvcMatchers("/app/*").hasRole("APP")
- // ...
- .anyRequest().permitAll()
- )
- ----
- .Kotlin
- [source,kotlin,role="secondary"]
- ----
- http {
- authorizeHttpRequests {
- authorize("/app*", hasRole("APP"))
- // ...
- authorize(anyRequest, permitAll)
- }
- }
- ----
- .Xml
- [source,xml,role="secondary"]
- ----
- <http>
- <intercept-url pattern="/app/*" access="hasRole('APP')"/>
- <!-- ... -->
- <intercept-url pattern="/**" access="permitAll"/>
- </http>
- ----
- ====
- ==== I cannot migrate my SpEL or my `AccessDecisionManager`
- 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.
- 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.
- Second, if you still need your custom `access-decision-manager-ref` or have some other reason to opt out of `AuthorizationManager`, do:
- ====
- .Xml
- [source,xml,role="secondary"]
- ----
- <http use-authorization-manager="false">
- <intercept-url pattern="/app/*" access="hasRole('APP')"/>
- <!-- ... -->
- </http>
- ----
- ====
|