Repository navigation
Expand file tree
/
Copy pathinput.xml
More file actions
1674 lines (1617 loc) · 96.1 KB
/
Copy pathinput.xml
File metadata and controls
1674 lines (1617 loc) · 96.1 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
<?xml version="1.0" encoding="UTF-8"?>
<article version="5.0" xml:lang="en-US" xmlns="http://docbook.org/ns/docbook" xmlns:xl="http://www.w3.org/1999/xlink">
<info>
<title>Bootstrap a Web Application with Spring 4</title>
</info>
<anchor xml:id="wrapper"/>
<anchor xml:id="inner-wrapper"/>
<!--
/#side-nav
-->
<!--
/.menus
-->
<para><link linkend="top">Return to Content</link></para>
<!--
#content Starts
-->
<anchor xml:id="content"/>
<anchor xml:id="main-sidebar-container"/>
<!--
#main Starts
-->
<anchor xml:id="toc_container"/>
<para>Contents</para>
<itemizedlist>
<listitem>
<para><link linkend="Table_of_Contents">Table of Contents</link></para>
</listitem>
<listitem>
<para><link linkend="dbdoclet.1_Overview">1. Overview</link></para>
</listitem>
<listitem>
<para><link linkend="dbdoclet.2_The_Maven_pomxml">2. The Maven pom.xml</link></para>
</listitem>
<listitem>
<para><link linkend="dbdoclet.3_The_Java_based_Web_Configuration">3. The Java based Web Configuration</link></para>
</listitem>
<listitem>
<para><link linkend="dbdoclet.4_Conclusion">4. Conclusion</link></para>
</listitem>
</itemizedlist>
<para>If you're new here, <link xl:href="https://my.leadpages.net/leadbox/146382273f72a2%3A13a71ac76b46dc/5735865741475840/">you may want to get my "REST APIs with Spring" eBook</link>. Thanks for visiting!</para>
<para><link xl:href=""/></para>
<!--
Start Shortcoder content
-->
<!--
End Shortcoder content
-->
<section>
<title><anchor xml:id="Table_of_Contents"/><emphasis role="bold">Table of Contents</emphasis></title>
<itemizedlist>
<listitem>
<para><link linkend="overview"><emphasis role="bold">1. </emphasis>Overview</link></para>
</listitem>
<listitem>
<para><link linkend="maven"><emphasis role="bold">2. </emphasis>The Maven pom.xml</link></para>
</listitem>
<listitem>
<para><link linkend="cglib"><emphasis role="bold">Â Â Â 2.1. </emphasis>Justification of the <emphasis>cglib</emphasis> dependency</link></para>
</listitem>
<listitem>
<para><link linkend="cglib_gone"><emphasis role="bold">Â Â Â 2.2. </emphasis>The <emphasis>cglib</emphasis> dependency in Spring 3.2 and beyond</link></para>
</listitem>
<listitem>
<para><link linkend="java_config"><emphasis role="bold">3. </emphasis>The Java based web configuration</link></para>
</listitem>
<listitem>
<para><link linkend="web_xml"><emphasis role="bold">Â Â 3.1. </emphasis>The web.xml</link></para>
</listitem>
<listitem>
<para><link linkend="conclusion"><emphasis role="bold">4. </emphasis>Conclusion</link></para>
</listitem>
</itemizedlist>
<section xml:id="overview.1">
<title><anchor xml:id="dbdoclet.1_Overview"/><emphasis role="bold">1. Overview</emphasis></title>
<para>The tutorial illustrates how to <emphasis role="bold">Bootstrap a Web Application with Spring</emphasis> and also discusses how to make the jump <emphasis role="bold">from XML to Java</emphasis> without having to completely migrate the entire XML configuration.</para>
</section>
<section xml:id="maven.1">
<title><anchor xml:id="dbdoclet.2_The_Maven_pomxml"/><emphasis role="bold">2. The Maven pom.xml</emphasis></title>
<screen><project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="
http://maven.apache.org/POM/4.0.0
http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>org</groupId>
<artifactId>rest</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>war</packaging>
<dependencies>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>${spring.version}</version>
<exclusions>
<exclusion>
<artifactId>commons-logging</artifactId>
<groupId>commons-logging</groupId>
</exclusion>
</exclusions>
</dependency>
</dependencies>
<build>
<finalName>rest</finalName>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.1</version>
<configuration>
<source>1.6</source>
<target>1.6</target>
<encoding>UTF-8</encoding>
</configuration>
</plugin>
</plugins>
</build>
<properties>
<spring.version>4.0.5.RELEASE</spring.version>
</properties>
</project></screen>
<section xml:id="cglib.1">
<title><emphasis role="bold">2.1. The cglib dependency before Spring 3.2</emphasis></title>
<para>You may wonder why <emphasis>cglib</emphasis> is a dependency – it turns out there is a valid reason to include it – the entire configuration cannot function without it. If removed, Spring will throw:</para>
<para><emphasis>Caused by: java.lang.IllegalStateException: CGLIB is required to process @Configuration classes. Either add CGLIB to the classpath or remove the following @Configuration bean definitions</emphasis></para>
<para>The reason this happens is explained by the way Spring deals with <emphasis>@Configuration</emphasis> classes. These classes are effectively beans, and because of this they need to be aware of the Context, and respect scope and other bean semantics. This is achieved by dynamically creating a cglib proxy with this awareness for each <emphasis>@Configuration</emphasis> class, hence the cglib dependency.</para>
<para>Also, because of this, there are a few restrictions for <emphasis>Configuration</emphasis> annotated classes:</para>
<itemizedlist>
<listitem>
<para> Configuration classes <emphasis role="bold">should not be final</emphasis></para>
</listitem>
<listitem>
<para> They should have a constructor with no arguments</para>
</listitem>
</itemizedlist>
</section>
<section xml:id="cglib_gone.1">
<title><emphasis role="bold">2.2. The cglib dependency in Spring 3.2 and beyond</emphasis></title>
<para>Starting with Spring 3.2, it is <emphasis role="bold">no longer necessary to add cglib as an explicit dependency</emphasis>. This is because Spring is in now inlining <emphasis>cglib</emphasis> – which will ensure that all class based proxying functionality will work out of the box with Spring 3.2.</para>
<para>The new cglib code is placed under the Spring package: <emphasis>org.springframework.cglib</emphasis> (replacing the original <emphasis>net.sf.cglib</emphasis>). The reason for the package change is to avoid conflicts with any <emphasis>cglib</emphasis> versions already existing on the classpath.</para>
<para>Also, the new cglib 3.0 is now used, upgraded from the older 2.2 dependency (see this <link xl:href="https://jira.springsource.org/browse/SPR-9669">JIRA issue</link> for more details).</para>
<para>Finally, now that Spring 4.0 is out in the wild, changes like this one (removing the cglib dependency) are to be expected with Java 8 just around the corner – you can watch <link xl:href="https://jira.springsource.org/browse/SPR-9639">this Spring Jira</link> to keep track of the Spring support, and <link xl:href="http://www.baeldung.com/java8">the Java 8 Resources page</link> to keep tabs on the that.</para>
</section>
</section>
<section xml:id="java_config.1">
<title><anchor xml:id="dbdoclet.3_The_Java_based_Web_Configuration"/><emphasis role="bold">3. The Java based Web Configuration</emphasis></title>
<screen>@Configuration
@ImportResource( { "classpath*:/rest_config.xml" } )
@ComponentScan( basePackages = "org.rest" )
@PropertySource({ "classpath:rest.properties", "classpath:web.properties" })
public class AppConfig{
@Bean
  public static PropertySourcesPlaceholderConfigurer properties() {
  return new PropertySourcesPlaceholderConfigurer();
  }
}</screen>
<para>First, the <emphasis role="bold">@Configuration</emphasis> annotation – this is the main artifact used by the Java based Spring configuration; it is itself meta-annotated with <emphasis>@Component</emphasis>, which makes the annotated classes <emphasis role="bold">standard beans</emphasis> and as such, also candidates for component scanning. The main purpose of <emphasis>@Configuration</emphasis> classes is to be sources of bean definitions for the Spring IoC Container. For a more detailed description, see the <link xl:href="http://static.springsource.org/spring/docs/3.1.x/spring-framework-reference/html/beans.html#beans-java">official docs</link>.</para>
<para>Then, <emphasis role="bold">@ImportResource</emphasis> is used to import the existing XML based Spring configuration. This may be configuration which is still being migrated from XML to Java, or simply legacy configuration that you wish to keep. Either way, importing it into the Container is essential for a successful migration, allowing small steps without to much risk. The equivalent XML annotation that is replaced is:</para>
<para><emphasis><import resource=”classpath*:/rest_config.xml” /></emphasis></para>
<para>Moving on to <emphasis role="bold">@ComponentScan</emphasis> – this configures the component scanning directive, effectively replacing the XML:</para>
<screen><context:component-scan base-package="org.rest" /></screen>
<para>As of Spring 3.1, the <emphasis>@Configuration</emphasis> are excluded from classpath scanning by default – see <link xl:href="https://jira.springsource.org/browse/SPR-8808">this JIRA issue</link>. Before Spring 3.1 though, these classes should have been excluded explicitly:</para>
<screen>excludeFilters = { @ComponentScan.Filter( Configuration.class ) }</screen>
<para>The <emphasis>@Configuration</emphasis> classes should not be autodiscovered because they are already specified and used by the Container – allowing them to be rediscovered and introduced into the Spring context will result in the following error:</para>
<para><emphasis>Caused by: org.springframework.context.annotation.ConflictingBeanDefinitionException: Annotation-specified bean name ‘webConfig’ for bean class [org.rest.spring.AppConfig] conflicts with existing, non-compatible bean definition of same name and class [org.rest.spring.AppConfig]</emphasis></para>
<para>And finally, using the<emphasis role="bold"> @Bean</emphasis> annotation to configure the <emphasis role="bold">properties support</emphasis> –Â <emphasis>PropertySourcesPlaceholderConfigurer</emphasis> is initialized in a <emphasis>@Bean</emphasis> annotated method, indicating it will produce a Spring bean managed by the Container. This new configuration has replaced the following XML:</para>
<screen><context:property-placeholder
location="classpath:persistence.properties, classpath:web.properties"
ignore-unresolvable="true"/></screen>
<para>For a more in depth discussion on why it was necessary to manually register the <emphasis>PropertySourcesPlaceholderConfigurer</emphasis> bean, see the <link xl:href="http://www.baeldung.com/2012/02/06/properties-with-spring/">Properties with Spring Tutorial</link>.</para>
<section xml:id="web_xml.1">
<title><emphasis role="bold">3.1. The web.xml</emphasis></title>
<screen><?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="
http://java.sun.com/xml/ns/javaee"
   xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"
   xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
   xsi:schemaLocation="
http://java.sun.com/xml/ns/javaee
http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"
   id="rest" version="3.0">
<context-param>
<param-name>contextClass</param-name>
<param-value>
org.springframework.web.context.support.AnnotationConfigWebApplicationContext
</param-value>
</context-param>
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>org.rest.spring.root</param-value>
</context-param>
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<servlet>
<servlet-name>rest</servlet-name>
<servlet-class>
org.springframework.web.servlet.DispatcherServlet
</servlet-class>
<init-param>
<param-name>contextClass</param-name>
<param-value>
org.springframework.web.context.support.AnnotationConfigWebApplicationContext
</param-value>
</init-param>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>org.rest.spring.rest</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>rest</servlet-name>
<url-pattern>/api/*</url-pattern>
</servlet-mapping>
<welcome-file-list>
<welcome-file />
</welcome-file-list>
</web-app></screen>
<para> First, the root context is defined and configured to use <emphasis>AnnotationConfigWebApplicationContext</emphasis> instead of the default <emphasis>XmlWebApplicationContext</emphasis>. The newer <emphasis>AnnotationConfigWebApplicationContext</emphasis> accepts <emphasis>@Configuration</emphasis> annotated classes as input for the Container configuration and is needed in order to set up the Java based context. Unlike <emphasis>XmlWebApplicationContext</emphasis>, it assumes no default configuration class locations, so the <emphasis>“contextConfigLocation”</emphasis><emphasis>init-param</emphasis> for the Servlet must be set. This will point to the java package where the <emphasis>@Configuration</emphasis> classes are located; the fully qualified name(s) of the classes are also supported.</para>
<para>Next, the <emphasis>DispatcherServlet</emphasis> is configured to use the same kind of context, with the only difference that it’s loading configuration classes out of a different package.</para>
<para>Other than this, the <emphasis>web.xml</emphasis> doesn’t really change from a XML to a Java based configuration.</para>
</section>
</section>
<section xml:id="conclusion.1">
<title><anchor xml:id="dbdoclet.4_Conclusion"/><emphasis role="bold">4. Conclusion</emphasis></title>
<para>The presented approach allows for a smooth <emphasis role="bold">migration of the Spring configuration</emphasis> from XML to Java, mixing the old and the new. This is important for older projects, which may have a lot of XML based configuration that cannot be migrated all at once.</para>
<para>This way, in a migration, the XML beans can be ported in small increments.</para>
<para>In <link xl:href="http://www.baeldung.com/2011/10/25/building-a-restful-web-service-with-spring-3-1-and-java-based-configuration-part-2/">the next article on REST with Spring</link>, I cover setting up MVC in the project, configuration of the HTTP status codes, payload marshalling and content negotiation.</para>
<para><link xl:href="https://my.leadpages.net/leadbox/147e9e473f72a2%3A13a71ac76b46dc/5745710343389184/">The implementation of this <emphasis>Bootstrap a Spring Web App Tutorial</emphasis> can be downloaded as a working sample project.</link></para>
<para>This is an Eclipse based project, so it should be easy to import and run as it is.</para>
<!--
Start Shortcoder content
-->
<para>Â </para>
<!--
End Shortcoder content
-->
<para><link xl:href=""/></para>
<anchor xml:id="dd_ajax_float"/>
<para><link xl:href="http://twitter.com/share"/></para>
<!--
OptinSkin
-->
<anchor xml:id="ois_12"/>
<!--
End OptinSkin
-->
<!--
/.entry
-->
<para><emphasis role="italic"/><link xl:href="http://www.baeldung.com/tag/java-2/">java</link>, <link xl:href="http://www.baeldung.com/tag/spring/">Spring</link></para>
<!--
/.post
-->
<!--
/#main
-->
<anchor xml:id="optinskin-widget-3"/>
<!--
OptinSkin
-->
<anchor xml:id="ois_5"/>
<!--
End OptinSkin
-->
<!--
/#sidebar
-->
<!--
/#main-sidebar-container
-->
<!--
/#content
-->
<anchor xml:id="copyright"/>
<para>© 2014 Baeldung. All Rights Reserved. </para>
<anchor xml:id="credit"/>
<!--
/#inner-wrapper
-->
<!--
/#wrapper
-->
<!--
/.fix
-->
<!--
ngg_resource_manager_marker
-->
<!--
WP SyntaxHighlighter Ver.1.7.3 Begin
-->
<!--
WP SyntaxHighlighter Ver.1.7.3 End
-->
</section>
</section>
</article>
<?xml version="1.0" encoding="UTF-8"?>
<article version="5.0" xml:lang="en-US" xmlns="http://docbook.org/ns/docbook" xmlns:xl="http://www.w3.org/1999/xlink">
<info>
<title>Build a REST API with Spring 4 and Java Config</title>
</info>
<anchor xml:id="wrapper"/>
<anchor xml:id="inner-wrapper"/>
<!--
/#side-nav
-->
<!--
/.menus
-->
<para><link linkend="top">Return to Content</link></para>
<!--
#content Starts
-->
<anchor xml:id="content"/>
<anchor xml:id="main-sidebar-container"/>
<!--
#main Starts
-->
<anchor xml:id="toc_container"/>
<para>Contents</para>
<itemizedlist>
<listitem>
<para><link linkend="Table_of_Contents">Table of Contents</link></para>
</listitem>
<listitem>
<para><link linkend="dbdoclet.1_Overview">1. Overview</link></para>
</listitem>
<listitem>
<para><link linkend="dbdoclet.2_Understanding_REST_in_Spring">2. Understanding REST in Spring </link></para>
</listitem>
<listitem>
<para><link linkend="dbdoclet.3_The_Java_configuration">3. The Java configuration</link></para>
</listitem>
<listitem>
<para><link linkend="dbdoclet.4_Testing_the_Spring_context">4. Testing the Spring context</link></para>
</listitem>
<listitem>
<para><link linkend="dbdoclet.5_The_Controller">5. The Controller</link></para>
</listitem>
<listitem>
<para><link linkend="dbdoclet.6_Mapping_the_HTTP_response_codes">6. Mapping the HTTP response codes</link></para>
</listitem>
<listitem>
<para><link linkend="dbdoclet.7_Additional_Maven_dependencies">7. Additional Maven dependencies </link></para>
</listitem>
<listitem>
<para><link linkend="dbdoclet.8_Conclusion">8. Conclusion</link></para>
</listitem>
</itemizedlist>
<para>If you're new here, <link xl:href="https://my.leadpages.net/leadbox/146382273f72a2%3A13a71ac76b46dc/5735865741475840/">you may want to get my "REST APIs with Spring" eBook</link>. Thanks for visiting!</para>
<para><link xl:href=""/></para>
<!--
Start Shortcoder content
-->
<para>Â </para>
<!--
End Shortcoder content
-->
<section>
<title><anchor xml:id="Table_of_Contents"/><emphasis role="bold">Table of Contents</emphasis></title>
<itemizedlist>
<listitem>
<para><link linkend="overview"><emphasis role="bold">1. </emphasis>Overview</link></para>
</listitem>
<listitem>
<para><link linkend="rest"><emphasis role="bold">2. </emphasis>Understanding REST in Spring</link></para>
</listitem>
<listitem>
<para><link linkend="java-config"><emphasis role="bold">3. </emphasis>The Java configuration</link></para>
</listitem>
<listitem>
<para><link linkend="test"><emphasis role="bold">4. </emphasis>Testing the Spring context</link></para>
</listitem>
<listitem>
<para><link linkend="controller"><emphasis role="bold">5. </emphasis>The Controller</link></para>
</listitem>
<listitem>
<para><link linkend="http-codes"><emphasis role="bold">6. </emphasis>Mapping the HTTP response codes</link></para>
</listitem>
<listitem>
<para><link linkend="ch_6_1"><emphasis role="bold">Â Â Â 6.1. </emphasis>Unmapped requests</link></para>
</listitem>
<listitem>
<para><link linkend="ch_6_2"><emphasis role="bold">Â Â Â 6.2. </emphasis>Valid, mapped requests</link></para>
</listitem>
<listitem>
<para><link linkend="ch_6_3"><emphasis role="bold">Â Â Â 6.3. </emphasis>Client error</link></para>
</listitem>
<listitem>
<para><link linkend="ch_6_4"><emphasis role="bold">Â Â Â 6.4. </emphasis>Using <emphasis>@ExceptionHandler</emphasis></link></para>
</listitem>
<listitem>
<para><link linkend="maven"><emphasis role="bold">7. </emphasis>Additional Maven dependencies</link></para>
</listitem>
<listitem>
<para><link linkend="conclusion"><emphasis role="bold">8. </emphasis>Conclusion</link></para>
</listitem>
</itemizedlist>
<section xml:id="overview.1">
<title><anchor xml:id="dbdoclet.1_Overview"/><emphasis role="bold">1. Overview</emphasis></title>
<para>This article shows how to <emphasis role="bold">set up REST in Spring</emphasis> – the Controller and HTTP response codes, configuration of payload marshalling and content negotiation.</para>
</section>
<section xml:id="rest.1">
<title><anchor xml:id="dbdoclet.2_Understanding_REST_in_Spring"/><emphasis role="bold">2. Understanding REST in Spring</emphasis> </title>
<para>The Spring framework supports 2 ways of creating RESTful services:</para>
<itemizedlist>
<listitem>
<para> using MVC with <emphasis>ModelAndView</emphasis></para>
</listitem>
<listitem>
<para> using HTTP message converters</para>
</listitem>
</itemizedlist>
<para>The <emphasis role="bold">ModelAndView</emphasis> approach is older and much better documented, but also more verbose and configuration heavy. It tries to shoehorn the REST paradigm into the old model, which is not without problems. The Spring team understood this and provided first-class REST support starting with <emphasis role="bold">Spring 3.0</emphasis>.</para>
<para>The new approach, based on <emphasis role="bold">HttpMessageConverter</emphasis>and<emphasis role="bold"> annotations</emphasis>, is much more lightweight and easy to implement. Configuration is minimal and it provides sensible defaults for what you would expect from a RESTful service. It is however newer and a a bit on the light side concerning documentation; what’s , the reference doesn’t go out of it’s way to make the distinction and the tradeoffs between the two approaches as clear as they should be. Nevertheless, this is the way RESTful services should be build after Spring 3.0.</para>
</section>
<section xml:id="java-config.1">
<title><anchor xml:id="dbdoclet.3_The_Java_configuration"/><emphasis role="bold">3. The Java configuration</emphasis></title>
<para><link xl:href="http://www.baeldung.com/wp-content/uploads/2013/11/SPRING-JAVA-CONFIGURATION.jpg"/></para>
<screen>@Configuration
@EnableWebMvc
public class WebConfig{
//
}</screen>
<para>The new <emphasis role="bold">@EnableWebMvc</emphasis> annotation does a number of useful things – specifically, in the case of REST, it detect the existence of Jackson and JAXB 2 on the classpath and automatically creates and registers default <emphasis role="bold">JSON and XML converters</emphasis>. The functionality of the annotation is equivalent to the XML version:</para>
<para><emphasis><mvc:annotation-driven /></emphasis></para>
<para>This is a shortcut, and though it may be useful in many situations, it’s not perfect. When more complex configuration is needed, remove the annotation and extend <emphasis>WebMvcConfigurationSupport</emphasis> directly.</para>
</section>
<section xml:id="test.1">
<title><anchor xml:id="dbdoclet.4_Testing_the_Spring_context"/><emphasis role="bold">4. Testing the Spring context</emphasis></title>
<para>Starting with <emphasis role="bold">Spring 3.1</emphasis>, <link xl:href="http://spring.io/blog/2011/06/21/spring-3-1-m2-testing-with-configuration-classes-and-profiles/">we get</link> first-class testing support for <emphasis>@Configuration</emphasis> classes:</para>
<screen>@RunWith( SpringJUnit4ClassRunner.class )
@ContextConfiguration( classes = { ApplicationConfig.class, PersistenceConfig.class },
loader = AnnotationConfigContextLoader.class )
public class SpringTest{
@Test
public void whenSpringContextIsInstantiated_thenNoExceptions(){
// When
}
}</screen>
<para>The Java configuration classes are simply specified with the <emphasis role="bold">@ContextConfiguration</emphasis> annotation and the new <emphasis>AnnotationConfigContextLoader</emphasis> loads the bean definitions from the <emphasis>@Configuration</emphasis> classes.</para>
<para>Notice that the <emphasis>WebConfig</emphasis> configuration class was not included in the test because it needs to run in a Servlet context, which is not provided.</para>
</section>
<section xml:id="controller.1">
<title><anchor xml:id="dbdoclet.5_The_Controller"/><emphasis role="bold">5. The Controller</emphasis></title>
<para>The <emphasis role="bold">@Controller</emphasis> is the central artifact in the entire Web Tier of the RESTful API. For the purpose of this post, the controller is modeling a simple REST resource – <emphasis>Foo</emphasis>:</para>
<screen>@Controller
@RequestMapping( value = "/foos" )
class FooController{
@Autowired
IFooService service;
@RequestMapping( method = RequestMethod.GET )
@ResponseBody
public List< Foo > findAll(){
return service.findAll();
}
@RequestMapping( value = "/{id}", method = RequestMethod.GET )
@ResponseBody
public Foo findOne( @PathVariable( "id" ) Long id ){
return RestPreconditions.checkFound( service.findOne( id ) );
}
@RequestMapping( method = RequestMethod.POST )
@ResponseStatus( HttpStatus.CREATED )
@ResponseBody
public Long create( @RequestBody Foo resource ){
Preconditions.checkNotNull( resource );
return service.create( resource );
}
@RequestMapping( value = "/{id}", method = RequestMethod.PUT )
@ResponseStatus( HttpStatus.OK )
public void update( @PathVariable( "id" ) Long id, @RequestBody Foo resource ){
Preconditions.checkNotNull( resource );
RestPreconditions.checkNotNull( service.getById( resource.getId() ) );
service.update( resource );
}
@RequestMapping( value = "/{id}", method = RequestMethod.DELETE )
@ResponseStatus( HttpStatus.OK )
public void delete( @PathVariable( "id" ) Long id ){
service.deleteById( id );
}
}</screen>
<para>You may have noticed I’m using a very simple, guava style <emphasis>RestPreconditions</emphasis> utility:</para>
<screen>public class RestPreconditions {
public static <T> T checkFound(final T resource) {
if (resource == null) {
throw new MyResourceNotFoundException();
}
return resource;
}
}</screen>
<para>The Controller implementation is <emphasis role="bold">non-public</emphasis> – this is because it doesn’t need to be. Usually the controller is the last in the chain of dependencies – it receives HTTP requests from the Spring front controller (the<emphasis> DispathcerServlet</emphasis>) and simply delegate them forward to a service layer. If there is no use case where the controller has to be injected or manipulated through a direct reference, then I prefer not to declare it as public.</para>
<para>The <emphasis role="bold">request mappings</emphasis> are straightforward – as with any controller, the actual <emphasis>value</emphasis> of the mapping as well as the HTTP <emphasis>method</emphasis> are used to determine the target method for the request. <emphasis role="bold">@</emphasis><emphasis><emphasis role="bold">RequestBody</emphasis></emphasis> will bind the parameters of the method to the body of the HTTP request, whereas <emphasis role="bold">@ResponseBody</emphasis> does the same for the response and return type. They also ensure that the resource will be marshalled and unmarshalled using the correct HTTP converter. <emphasis role="bold">Content negotiation</emphasis> will take place to choose which one of the active converters will be used, based mostly on the <emphasis>Accept</emphasis> header, although other HTTP headers may be used to determine the representation as well.</para>
</section>
<section xml:id="http-codes.1">
<title><anchor xml:id="dbdoclet.6_Mapping_the_HTTP_response_codes"/><emphasis role="bold">6. Mapping the HTTP response codes</emphasis></title>
<para>The status codes of the HTTP response are one of the most important parts of the REST service, and the subject can quickly become very complex. Getting these right can be what makes or breaks the service.</para>
<section xml:id="ch_6_1.1">
<title><emphasis role="bold">6.1. Unmapped requests</emphasis></title>
<para>If Spring MVC receives a request which doesn’t have a mapping, it considers the request not to be allowed and returns a <emphasis role="bold">405 METHOD NOT ALLOWED</emphasis> back to the client. It is also good practice to include the <emphasis role="bold">Allow HTTP header</emphasis> when returning a <emphasis>405</emphasis> to the client, in order to specify which operations <emphasis role="bold">are</emphasis> allowed. This is the standard behavior of Spring MVC and does not require any additional configuration.</para>
</section>
<section xml:id="ch_6_2.1">
<title><emphasis role="bold">6.2. Valid, mapped requests</emphasis></title>
<para>For any request that does have a mapping, Spring MVC considers the request valid and responds with <emphasis role="bold">200 OK</emphasis> if no other status code is specified otherwise. It is because of this that controller declares different <emphasis><emphasis role="bold">@ResponseStatus</emphasis></emphasis> for the <emphasis>create</emphasis>, <emphasis>update</emphasis> and <emphasis>delete</emphasis> actions but not for <emphasis>get</emphasis>, which should indeed return the default 200 OK.</para>
</section>
<section xml:id="ch_6_3.1">
<title><emphasis role="bold">6.3. Client error</emphasis></title>
<para>In case of a <emphasis role="bold">client error</emphasis>, custom exceptions are defined and mapped to the appropriate error codes. Simply throwing these exceptions from any of the layers of the web tier will ensure Spring maps the corresponding status code on the HTTP response.</para>
<screen>@ResponseStatus( value = HttpStatus.BAD_REQUEST )
public class BadRequestException extends RuntimeException{
//
}
@ResponseStatus( value = HttpStatus.NOT_FOUND )
public class ResourceNotFoundException extends RuntimeException{
//
}</screen>
<para>These exceptions are part of the REST API and, as such, should only be used in the appropriate layers corresponding to REST; if for instance a DAO/DAL layer exist, it should not use the exceptions directly. Note also that these are not <emphasis role="bold">checked exceptions</emphasis> but <emphasis role="bold">runtime exceptions</emphasis> – in line with Spring practices and idioms.</para>
</section>
<section xml:id="ch_6_4.1">
<title><emphasis role="bold">6.4. Using @ExceptionHandler</emphasis></title>
<para>Another option to map custom exceptions on specific status codes is to use the <emphasis><emphasis role="bold">@ExceptionHandler</emphasis></emphasis> annotation in the controller. The problem with that approach is that the annotation only applies to the controller in which it is defined, not to the entire Spring Container, which means that it needs to be declared in each controller individually. This quickly becomes cumbersome, especially in more complex applications which many controllers. There are a few <emphasis role="bold">JIRA issues</emphasis> opened with Spring at this time to handle this and other related limitations: <link xl:href="https://jira.springsource.org/browse/SPR-8124">SPR-8124</link>, <link xl:href="https://jira.springsource.org/browse/SPR-7278">SPR-7278</link>, <link xl:href="https://jira.springsource.org/browse/SPR-8406">SPR-8406</link>.</para>
</section>
</section>
<section xml:id="maven.1">
<title><anchor xml:id="dbdoclet.7_Additional_Maven_dependencies"/><emphasis role="bold">7. Additional Maven dependencies</emphasis><emphasis role="bold"></emphasis></title>
<para>In addition to the <emphasis>spring-webmvc</emphasis> dependency <link xl:href="http://www.baeldung.com/spring-with-maven#mvc">required for the standard web application</link>, we’ll need to set up content marshalling and unmarshalling for the REST API:</para>
<screen><dependencies>
<dependency>
  <groupId>com.fasterxml.jackson.core</groupId>
  <artifactId>jackson-databind</artifactId>
  <version>${jackson.version}</version>
</dependency>
<dependency>
<groupId>javax.xml.bind</groupId>
<artifactId>jaxb-api</artifactId>
<version>${jaxb-api.version}</version>
<scope>runtime</scope>
</dependency>
</dependencies>
<properties>
<jackson.version>2.4.0</jackson.version>
<jaxb-api.version>2.2.11</jaxb-api.version>
</properties></screen>
<para>These are the libraries used to convert the representation of the REST resource to either <emphasis role="bold">JSON</emphasis> or <emphasis role="bold">XML</emphasis>.</para>
</section>
<section xml:id="conclusion.1">
<title><anchor xml:id="dbdoclet.8_Conclusion"/><emphasis role="bold">8. Conclusion</emphasis></title>
<para>This tutorial illustrated how to implement and configure a REST Service using Spring 4 and Java based configuration, discussing HTTP response codes, basic Content Negotiation and marshaling.</para>
<para>In the next articles of the series I will focus on <link xl:href="http://www.baeldung.com/2011/11/06/restful-web-service-discoverability-part-4/">Discoverability of the API</link>, advanced <emphasis role="bold">content negotiation</emphasis> and working with <emphasis role="bold">additional representations</emphasis> of a Resource.</para>
<para><link xl:href="https://my.leadpages.net/leadbox/143ecbd73f72a2%3A13a71ac76b46dc/5762893836451840/">The implementation of this <emphasis>Spring REST API Tutorial</emphasis> can be downloaded as a working sample project.</link></para>
<para>This is an Eclipse based project, so it should be easy to import and run as it is.</para>
<!--
Start Shortcoder content
-->
<!--
End Shortcoder content
-->
<para><link xl:href=""/></para>
<anchor xml:id="dd_ajax_float"/>
<para><link xl:href="http://twitter.com/share"/></para>
<!--
OptinSkin
-->
<anchor xml:id="ois_12"/>
<!--
End OptinSkin
-->
<!--
/.entry
-->
<para><emphasis role="italic"/><link xl:href="http://www.baeldung.com/tag/java-2/">java</link>, <link xl:href="http://www.baeldung.com/tag/rest/">REST</link>, <link xl:href="http://www.baeldung.com/tag/spring/">Spring</link>, <link xl:href="http://www.baeldung.com/tag/testing/">testing</link></para>
<!--
/.post
-->
<!--
/#main
-->
<anchor xml:id="optinskin-widget-3"/>
<!--
OptinSkin
-->
<anchor xml:id="ois_5"/>
<!--
End OptinSkin
-->
<!--
/#sidebar
-->
<!--
/#main-sidebar-container
-->
<!--
/#content
-->
<anchor xml:id="copyright"/>
<para>© 2014 Baeldung. All Rights Reserved. </para>
<anchor xml:id="credit"/>
<!--
/#inner-wrapper
-->
<!--
/#wrapper
-->
<!--
/.fix
-->
<!--
ngg_resource_manager_marker
-->
<!--
WP SyntaxHighlighter Ver.1.7.3 Begin
-->
<!--
WP SyntaxHighlighter Ver.1.7.3 End
-->
<!--
Creater Script for Social Locker
Created by the Social Locker plugin (c) OnePress Ltd
http://sociallocker.org
-->
<!--
/
-->
</section>
</section>
</article>
<?xml version="1.0" encoding="UTF-8"?>
<article version="5.0" xml:lang="en-US" xmlns="http://docbook.org/ns/docbook" xmlns:xl="http://www.w3.org/1999/xlink">
<info>
<title>Spring Security for a REST API</title>
</info>
<anchor xml:id="wrapper"/>
<anchor xml:id="inner-wrapper"/>
<!--
/#side-nav
-->
<!--
/.menus
-->
<para><link linkend="top">Return to Content</link></para>
<!--
#content Starts
-->
<anchor xml:id="content"/>
<anchor xml:id="main-sidebar-container"/>
<!--
#main Starts
-->
<anchor xml:id="toc_container"/>
<para>Contents</para>
<itemizedlist>
<listitem>
<para><link linkend="Table_of_Contents">Table of Contents</link></para>
</listitem>
<listitem>
<para><link linkend="dbdoclet.1_Overview">1. Overview</link></para>
</listitem>
<listitem>
<para><link linkend="dbdoclet.2_Spring_Security_in_the_webxml">2. Spring Security in the web.xml</link></para>
</listitem>
<listitem>
<para><link linkend="dbdoclet.3_The_Security_Configuration">3. The Security Configuration</link></para>
</listitem>
<listitem>
<para><link linkend="dbdoclet.4_Maven_and_other_trouble">4. Maven and other trouble</link></para>
</listitem>
<listitem>
<para><link linkend="dbdoclet.5_Conclusion">5. Conclusion</link></para>
</listitem>
</itemizedlist>
<para><link xl:href=""/></para>
<!--
Start Shortcoder content
-->
<!--
End Shortcoder content
-->
<section>
<title><anchor xml:id="Table_of_Contents"/><emphasis role="bold">Table of Contents</emphasis></title>
<itemizedlist>
<listitem>
<para><link linkend="overview"><emphasis role="bold">1. </emphasis>Overview</link></para>
</listitem>
<listitem>
<para><link linkend="springsec"><emphasis role="bold">2. </emphasis>Introducing Spring Security in the <literal>web.xml</literal></link></para>
</listitem>
<listitem>
<para><link linkend="config"><emphasis role="bold">3. </emphasis>The Security Configuration</link></para>
</listitem>
<listitem>
<para><link linkend="ch_3_1"><emphasis role="bold">Â Â Â Â 3.1. </emphasis>The basics</link></para>
</listitem>
<listitem>
<para><link linkend="ch_3_2"><emphasis role="bold">Â Â Â Â 3.2. </emphasis>The Entry Point</link></para>
</listitem>
<listitem>
<para><link linkend="ch_3_3"><emphasis role="bold">Â Â Â Â 3.3. </emphasis>The Login</link></para>
</listitem>
<listitem>
<para><link linkend="ch_3_4"><emphasis role="bold">Â Â Â 3.4. </emphasis>Authentication should return <emphasis role="bold">200</emphasis> instead of <emphasis role="bold">301</emphasis></link></para>
</listitem>
<listitem>
<para><link linkend="ch_3_5"><emphasis role="bold">Â Â Â 3.5. </emphasis>Failed Authentication should return <emphasis role="bold">401</emphasis> instead of <emphasis role="bold">302</emphasis></link></para>
</listitem>
<listitem>
<para><link linkend="ch_3_6"><emphasis role="bold">Â Â Â Â 3.6. </emphasis>The Authentication Manager and Provider</link></para>
</listitem>
<listitem>
<para><link linkend="ch_3_7"><emphasis role="bold">   3.7. </emphasis>Finally – Authentication against the running REST Service</link></para>
</listitem>
<listitem>
<para><link linkend="maven"><emphasis role="bold">4. </emphasis>Maven and other trouble</link></para>
</listitem>
<listitem>
<para><link linkend="conclusion"><emphasis role="bold">5. </emphasis>Conclusion</link></para>
</listitem>
</itemizedlist>
<section xml:id="overview.1">
<title><anchor xml:id="dbdoclet.1_Overview"/><emphasis role="bold">1. Overview</emphasis></title>
<para>This tutorial shows how to <emphasis role="bold">Secure a REST Service using Spring and Spring Security 3.1</emphasis> with Java based configuration. The article will focus on how to set up the Security Configuration specifically for the REST API using a Login and Cookie approach.</para>
</section>
<section xml:id="springsec.1">
<title><anchor xml:id="dbdoclet.2_Spring_Security_in_the_webxml"/><emphasis role="bold">2. Spring Security in the web.xml</emphasis></title>
<para>The architecture of Spring Security is based entirely on Servlet Filters and, as such, comes before Spring MVC in regards to the processing of HTTP requests. Keeping this in mind, to begin with, a <emphasis role="bold">filter</emphasis> needs to be declared in the <emphasis>web.xml</emphasis> of the application:</para>
<screen><filter>
<filter-name>springSecurityFilterChain</filter-name>
<filter-class>org.springframework.web.filter.DelegatingFilterProxy</filter-class>
</filter>
<filter-mapping>
<filter-name>springSecurityFilterChain</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping></screen>
<para>The filter must necessarily be named <emphasis>‘springSecurityFilterChain’</emphasis>Â to match the default bean created by Spring Security in the container.</para>
<para>Note that the defined filter is not the actual class implementing the security logic but a <emphasis>DelegatingFilterProxy</emphasis> with the purpose of delegating the Filter’s methods to an internal bean. This is done so that the target bean can still benefit from the Spring context lifecycle and flexibility.</para>
<para>The URL pattern used to configure the Filter is <emphasis role="bold">/*</emphasis> even though the entire web service is mapped to <emphasis role="bold">/api/*</emphasis> so that the security configuration has the option to secure other possible mappings as well, if required.</para>
</section>
<section xml:id="config.1">
<title><anchor xml:id="dbdoclet.3_The_Security_Configuration"/><emphasis role="bold">3. The Security Configuration</emphasis></title>
<screen><?xml version="1.0" encoding="UTF-8"?>
<beans:beans
xmlns="http://www.springframework.org/schema/security"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:beans="http://www.springframework.org/schema/beans"
xmlns:sec="http://www.springframework.org/schema/security"
xsi:schemaLocation="
http://www.springframework.org/schema/security
http://www.springframework.org/schema/security/spring-security-3.2.xsd
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-4.0.xsd">
<http entry-point-ref="restAuthenticationEntryPoint">
<intercept-url pattern="/api/admin/**" access="ROLE_ADMIN"/>
<form-login
authentication-success-handler-ref="mySuccessHandler"
authentication-failure-handler-ref="myFailureHandler"
/>
<logout />
</http>
<beans:bean id="mySuccessHandler"
class="org.rest.security.MySavedRequestAwareAuthenticationSuccessHandler"/>
<beans:bean id="myFailureHandler"
class="org.springframework.security.web.authentication.SimpleUrlAuthenticationFailureHandler"/>
<authentication-manager alias="authenticationManager">
<authentication-provider>
<user-service>
<user name="temporary" password="temporary" authorities="ROLE_ADMIN"/>
<user name="user" password="user" authorities="ROLE_USER"/>
</user-service>
</authentication-provider>
</authentication-manager>
</beans:beans></screen>
<para> Most of the configuration is done using the <emphasis role="bold">security namespace</emphasis> – for this to be enabled, the schema locations must be defined and pointed to the correct 3.1 or 3.2 XSD versions. The namespace is designed so that it expresses the common uses of Spring Security while still providing hooks raw beans to accommodate more advanced scenarios. <link xl:href="http://products.baeldung.com/rest-api-with-spring"><emphasis role="bold">>> Signup for my upcoming Video Course on Building a REST API with Spring 4</emphasis></link></para>
<section xml:id="ch_3_1.1">
<title><emphasis role="bold">3.1. The <http> element</emphasis></title>
<para>The <emphasis><http></emphasis> element is the main container element for HTTP security configuration. In the current implementation, it only secured a single mapping: <emphasis>/api/admin/**</emphasis>. Note that the mapping is <emphasis role="bold">relative to the root context</emphasis> of the web application, not to the <emphasis>rest</emphasis> Servlet; this is because the entire security configuration lives in the root Spring context and not in the child context of the Servlet.</para>
</section>
<section xml:id="ch_3_2.1">
<title><emphasis role="bold">3.2. The Entry Point</emphasis></title>
<para>In a standard web application, the authentication process may be automatically triggered when the client tries to access a secured resource without being authenticated – this is usually done by redirecting to a login page so that the user can enter credentials. However, for a <emphasis role="bold">REST Web Service </emphasis>this behavior doesn’t make much sense – Authentication should only be done by a request to the correct URI and all other requests should simply fail with a <emphasis role="bold">401 UNAUTHORIZED</emphasis> status code if the user is not authenticated.</para>
<para>Spring Security handles this automatic triggering of the authentication process with the concept of an <emphasis role="bold">Entry Point</emphasis> – this is a required part of the configuration, and can be injected via the <emphasis>entry-point-ref</emphasis> attribute of the <emphasis><http></emphasis> element. Keeping in mind that this functionality doesn’t make sense in the context of the REST Service, the new custom entry point is defined to simply return 401 whenever it is triggered:</para>
<screen>@Component( "restAuthenticationEntryPoint" )
public class RestAuthenticationEntryPoint implements AuthenticationEntryPoint{
@Override
public void commence( HttpServletRequest request, HttpServletResponse response,
AuthenticationException authException ) throws IOException{
response.sendError( HttpServletResponse.SC_UNAUTHORIZED, "Unauthorized" );
}
}</screen>
<para>A quick sidenote here is that the 401 is sent without the <emphasis>WWW-Authenticate</emphasis> header, as required by the HTTP Spec – we can of course set the value manually if we need to.</para>
</section>
<section xml:id="ch_3_3.1">
<title><emphasis role="bold">3.3. The Login Form for REST</emphasis></title>
<para>There are multiple ways to do Authentication for a REST API – one of the default Spring Security provides is <emphasis role="bold">Form Login</emphasis> – which uses an authentication processing filter – <emphasis>org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter</emphasis>.</para>
<para>The <emphasis><form-login></emphasis> element will create this filter and will also allow us to set our custom authentication success handler on it. This can also be done manually by using the <emphasis><custom-filter></emphasis> element to register a filter at the position <emphasis>FORM_LOGIN_FILTER</emphasis> – but the namespace support is flexible enough.</para>
<para>Note that for a standard web application, the <emphasis role="bold">auto-config </emphasis>attribute of the <emphasis><http> element </emphasis>is shorthand syntax for some useful security configuration. While this may be appropriate for some very simple configurations, it doesn’t fit and should not be used for a REST API.</para>
</section>
<section xml:id="ch_3_4.1">
<title><emphasis role="bold">3.4. Authentication should return 200 instead of 301</emphasis></title>
<para>By default, form login will answer a successful authentication request with a <emphasis role="bold">301 MOVED PERMANENTLY</emphasis> status code; this makes sense in the context of an actual login form which needs to redirect after login. For a RESTful web service however, the desired response for a successful authentication should be <emphasis role="bold">200 OK</emphasis>.</para>
<para>This is done by injecting a <emphasis role="bold">custom authentication success handler</emphasis> in the form login filter, to replace the default one. The new handler implements the exact same login as the default <emphasis>org.springframework.security.web.authentication.SavedRequestAwareAuthenticationSuccessHandler</emphasis> with one notable difference – the redirect logic is removed:</para>
<screen>public class MySavedRequestAwareAuthenticationSuccessHandler
extends SimpleUrlAuthenticationSuccessHandler {
private RequestCache requestCache = new HttpSessionRequestCache();
@Override
public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response,
Authentication authentication) throws ServletException, IOException {
SavedRequest savedRequest = requestCache.getRequest(request, response);
if (savedRequest == null) {
clearAuthenticationAttributes(request);
return;
}
String targetUrlParam = getTargetUrlParameter();
if (isAlwaysUseDefaultTargetUrl() ||
(targetUrlParam != null &&
StringUtils.hasText(request.getParameter(targetUrlParam)))) {
requestCache.removeRequest(request, response);
clearAuthenticationAttributes(request);
return;
}
clearAuthenticationAttributes(request);
}
public void setRequestCache(RequestCache requestCache) {
this.requestCache = requestCache;
}
}</screen>
</section>
<section xml:id="ch_3_5.1">
<title><emphasis role="bold">3.5. Failed Authentication should return 401 instead of 302</emphasis></title>
<para>Similarly – we configured the authentication failure handler – same way we did with the success handler.</para>
<para>Luckily – in this case, we don’t need to actually define a new class for this handler – the standard implementation – <emphasis>SimpleUrlAuthenticationFailureHandler</emphasis> – does just fine.</para>
<para>The only difference is that – now that we’re defining this explicitly in our XML config – it’s <emphasis role="bold">not going to get a default defaultFailureUrl from Spring</emphasis> – and so it won’t redirect.</para>
</section>
<section xml:id="ch_3_6.1">
<title><emphasis role="bold">3.6. The Authentication Manager and Provider</emphasis></title>
<para>The authentication process uses an <emphasis role="bold">in-memory provider</emphasis> to perform authentication – this is meant to simplify the configuration as a production implementation of these artifacts is outside the scope of this post.</para>
</section>
<section xml:id="ch_3_7.1">
<title><emphasis role="bold">3.7 Finally – Authentication against the running REST Service</emphasis></title>
<para>Now let’s see how we can authenticate against the REST API – the URL for login is <emphasis>/j_spring_security_check</emphasis> – and a simple <emphasis>curl</emphasis> command performing login would be:</para>
<screen>curl -i -X POST -d j_username=user -d j_password=userPass
http://localhost:8080/spring-security-rest/j_spring_security_check</screen>
<para>This request will return the Cookie which will then be used by any subsequent request against the REST Service.</para>
<para>We can use <emphasis>curl</emphasis> to authentication and <emphasis role="bold">store the cookie it receives in a file</emphasis>:</para>
<screen>curl -i -X POST -d j_username=user -d j_password=userPass -c /opt/cookies.txt
http://localhost:8080/spring-security-rest/j_spring_security_check</screen>
<para>Then <emphasis role="bold">we can use the cookie from the file</emphasis> to do further authenticated requests:</para>
<screen>curl -i --header "Accept:application/json" -X GET -b /opt/cookies.txt
http://localhost:8080/spring-security-rest/api/foos</screen>
<para>This authenticated request will correctly <emphasis role="bold">result in a 200 OK</emphasis>:</para>
<screen>HTTP/1.1 200 OK
Server: Apache-Coyote/1.1
Content-Type: application/json;charset=UTF-8
Transfer-Encoding: chunked
Date: Wed, 24 Jul 2013 20:31:13 GMT
[{"id":0,"name":"JbidXc"}]</screen>
</section>
</section>
<section xml:id="maven.1">
<title><anchor xml:id="dbdoclet.4_Maven_and_other_trouble"/><emphasis role="bold">4. Maven and other trouble</emphasis></title>
<para>The Spring <link xl:href="http://www.baeldung.com/spring-with-maven#mvc">core dependencies</link> necessary for a web application and for the REST Service have been discussed in detail. For security, we’ll need to add: <emphasis>spring-security-web</emphasis> and <emphasis>spring-security-config</emphasis> – all of these have also been covered in the <link xl:href="http://www.baeldung.com/spring-security-with-maven">Maven for Spring Security</link> tutorial.</para>
<para>It’s worth paying close attention to the way Maven will resolve the older Spring dependencies – the resolution strategy will start <link xl:href="http://www.baeldung.com/spring-security-with-maven#maven_problem">causing problems</link> once the security artifacts are added to the pom. To address this problem, some of the core dependencies will need to be overridden in order to keep them at the right version.</para>
</section>
<section xml:id="conclusion.1">
<title><anchor xml:id="dbdoclet.5_Conclusion"/><emphasis role="bold">5. Conclusion</emphasis></title>
<para>This post covered the basic security configuration and implementation for a RESTful Service using <emphasis role="bold">Spring Security 3.1</emphasis>, discussing the <emphasis>web.xml</emphasis>, the security configuration, the HTTP status codes for the authentication process and the Maven resolution of the security artifacts.</para>
<para><link xl:href="https://my.leadpages.net/leadbox/14476c373f72a2%3A13a71ac76b46dc/5664530495438848/">The implementation of this Spring Security REST Tutorial can be downloaded as a working sample project.</link>This is an Eclipse based project, so it should be easy to import and run as it is.</para>
<!--
Start Shortcoder content
-->
<!--
End Shortcoder content
-->
<para><link xl:href=""/></para>
<anchor xml:id="dd_ajax_float"/>
<para><link xl:href="http://twitter.com/share"/></para>
<!--
OptinSkin
-->
<anchor xml:id="ois_12"/>
<!--
End OptinSkin
-->
<!--
/.entry
-->
<para><emphasis role="italic"/><link xl:href="http://www.baeldung.com/tag/rest/">REST</link>, <link xl:href="http://www.baeldung.com/tag/security/">security</link>, <link xl:href="http://www.baeldung.com/tag/spring/">Spring</link></para>
<!--
/.post
-->
<!--
/#main
-->
<anchor xml:id="optinskin-widget-3"/>
<!--
OptinSkin
-->
<anchor xml:id="ois_5"/>
<!--
End OptinSkin
-->
<!--
/#sidebar
-->
<!--
/#main-sidebar-container
-->
<!--
/#content
-->
<anchor xml:id="copyright"/>
<para>© 2014 Baeldung. All Rights Reserved. </para>
<anchor xml:id="credit"/>
<!--
/#inner-wrapper
-->
<!--
/#wrapper
-->
<!--
/.fix
-->
<!--
ngg_resource_manager_marker
-->
<!--
WP SyntaxHighlighter Ver.1.7.3 Begin
-->
<!--
WP SyntaxHighlighter Ver.1.7.3 End
-->
<!--
Creater Script for Social Locker
Created by the Social Locker plugin (c) OnePress Ltd
http://sociallocker.org
-->
<!--
/
-->
</section>
</section>
</article>
<?xml version="1.0" encoding="UTF-8"?>
<article version="5.0" xml:lang="en-US" xmlns="http://docbook.org/ns/docbook" xmlns:xl="http://www.w3.org/1999/xlink">
<info>
<title>Spring Security Basic Authentication</title>
</info>
<anchor xml:id="wrapper"/>
<anchor xml:id="inner-wrapper"/>
<!--
/#side-nav
-->
<!--
/.menus
-->
<para><link linkend="top">Return to Content</link></para>
<!--
#content Starts
-->
<anchor xml:id="content"/>
<anchor xml:id="main-sidebar-container"/>
<!--
#main Starts