<!DOCTYPE html> <html lang="en"><head><script src="Spring%20Security%20Reference_files/docsearchbarspring.js" async="" type="text/javascript"></script> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <meta name="generator" content="Asciidoctor 0.1.4"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Spring Security Reference</title> <style>article,aside,details,figcaption,figure,footer,header,hgroup,main,nav,section,summary{display:block;}audio,canvas,video{display:inline-block;}audio:not([controls]){display:none;height:0;}[hidden]{display:none;}html{background:#fff;color:#000;font-family:sans-serif;-ms-text-size-adjust:100%;-webkit-text-size-adjust:100%;}body{margin:0;}a:focus{outline:thin dotted;}a:active,a:hover{outline:0;}h1{font-size:2em;margin:0.67em 0;}abbr[title]{border-bottom:1px dotted;}b,strong{font-weight:bold;}dfn{font-style:italic;}hr{-moz-box-sizing:content-box;box-sizing:content-box;height:0;}mark{background:#ff0;color:#000;}code,kbd,pre,samp{font-family:monospace,serif;font-size:1em;}pre{white-space:pre-wrap;}q{quotes:"\201C" "\201D" "\2018" "\2019";}small{font-size:80%;}sub,sup{font-size:75%;line-height:0;position:relative;vertical-align:baseline;}sup{top:-0.5em;}sub{bottom:-0.25em;}img{border:0;}svg:not(:root){overflow:hidden;}figure{margin:0;}fieldset{border:1px solid #c0c0c0;margin:0 2px;padding:0.35em 0.625em 0.75em;}legend{border:0;padding:0;}button,input,select,textarea{font-family:inherit;font-size:100%;margin:0;}button,input{line-height:normal;}button,select{text-transform:none;}button,html input[type="button"],input[type="reset"],input[type="submit"]{-webkit-appearance:button;cursor:pointer;}button[disabled],html input[disabled]{cursor:default;}input[type="checkbox"],input[type="radio"]{box-sizing:border-box;padding:0;}input[type="search"]{-webkit-appearance:textfield;-moz-box-sizing:content-box;-webkit-box-sizing:content-box;box-sizing:content-box;}input[type="search"]::-webkit-search-cancel-button,input[type="search"]::-webkit-search-decoration{-webkit-appearance:none;}button::-moz-focus-inner,input::-moz-focus-inner{border:0;padding:0;}textarea{overflow:auto;vertical-align:top;}table{border-collapse:collapse;border-spacing:0;}*,*:before,*:after{-moz-box-sizing:border-box;-webkit-box-sizing:border-box;box-sizing:border-box;}html,body{font-size:100%;}body{background:white;color:#222222;padding:0;margin:0;font-family:"Helvetica Neue","Helvetica",Helvetica,Arial,sans-serif;font-weight:normal;font-style:normal;line-height:1;position:relative;cursor:auto;}a:hover{cursor:pointer;}a:focus{outline:none;}img,object,embed{max-width:100%;height:auto;}object,embed{height:100%;}img{-ms-interpolation-mode:bicubic;}#map_canvas img,#map_canvas embed,#map_canvas object,.map_canvas img,.map_canvas embed,.map_canvas object{max-width:none!important;}.left{float:left!important;}.right{float:right!important;}.text-left{text-align:left!important;}.text-right{text-align:right!important;}.text-center{text-align:center!important;}.text-justify{text-align:justify!important;}.hide{display:none;}.antialiased,body{-webkit-font-smoothing:antialiased;}img{display:inline-block;vertical-align:middle;}textarea{height:auto;min-height:50px;}select{width:100%;}p.lead,.paragraph.lead>p,#preamble>.sectionbody>.paragraph:first-of-type p{font-size:1.21875em;line-height:1.6;}.subheader,#content #toctitle,.admonitionblock td.content>.title,.exampleblock>.title,.imageblock>.title,.videoblock>.title,.listingblock>.title,.literalblock>.title,.openblock>.title,.paragraph>.title,.quoteblock>.title,.sidebarblock>.title,.tableblock>.title,.verseblock>.title,.dlist>.title,.olist>.title,.ulist>.title,.qlist>.title,.hdlist>.title,.tableblock>caption{line-height:1.4;color:#7a2518;font-weight:300;margin-top:0.2em;margin-bottom:0.5em;}div,dl,dt,dd,ul,ol,li,h1,h2,h3,#toctitle,.sidebarblock>.content>.title,h4,h5,h6,pre,form,p,blockquote,th,td{margin:0;padding:0;direction:ltr;}a{color:#005498;text-decoration:underline;line-height:inherit;}a:hover,a:focus{color:#00467f;}a img{border:none;}p{font-family:inherit;font-weight:normal;font-size:1em;line-height:1.6;margin-bottom:1.25em;text-rendering:optimizeLegibility;}p aside{font-size:0.875em;line-height:1.35;font-style:italic;}h1,h2,h3,#toctitle,.sidebarblock>.content>.title,h4,h5,h6{font-family:Georgia,"URW Bookman L",Helvetica,Arial,sans-serif;font-weight:normal;font-style:normal;color:#ba3925;text-rendering:optimizeLegibility;margin-top:1em;margin-bottom:0.5em;line-height:1.2125em;}h1 small,h2 small,h3 small,#toctitle small,.sidebarblock>.content>.title small,h4 small,h5 small,h6 small{font-size:60%;color:#e99b8f;line-height:0;}h1{font-size:2.125em;}h2{font-size:1.6875em;}h3,#toctitle,.sidebarblock>.content>.title{font-size:1.375em;}h4{font-size:1.125em;}h5{font-size:1.125em;}h6{font-size:1em;}hr{border:solid #dddddd;border-width:1px 0 0;clear:both;margin:1.25em 0 1.1875em;height:0;}em,i{font-style:italic;line-height:inherit;}strong,b{font-weight:bold;line-height:inherit;}small{font-size:60%;line-height:inherit;}code{font-family:Consolas,"Liberation Mono",Courier,monospace;font-weight:normal;color:#6d180b;}ul,ol,dl{font-size:1em;line-height:1.6;margin-bottom:1.25em;list-style-position:outside;font-family:inherit;}ul,ol{margin-left:1.5em;}ul li ul,ul li ol{margin-left:1.25em;margin-bottom:0;font-size:1em;}ul.square li ul,ul.circle li ul,ul.disc li ul{list-style:inherit;}ul.square{list-style-type:square;}ul.circle{list-style-type:circle;}ul.disc{list-style-type:disc;}ul.no-bullet{list-style:none;}ol li ul,ol li ol{margin-left:1.25em;margin-bottom:0;}dl dt{margin-bottom:0.3125em;font-weight:bold;}dl dd{margin-bottom:1.25em;}abbr,acronym{text-transform:uppercase;font-size:90%;color:#222222;border-bottom:1px dotted #dddddd;cursor:help;}abbr{text-transform:none;}blockquote{margin:0 0 1.25em;padding:0.5625em 1.25em 0 1.1875em;border-left:1px solid #dddddd;}blockquote cite{display:block;font-size:inherit;color:#555555;}blockquote cite:before{content:"\2014 \0020";}blockquote cite a,blockquote cite a:visited{color:#555555;}blockquote,blockquote p{line-height:1.6;color:#6f6f6f;}.vcard{display:inline-block;margin:0 0 1.25em 0;border:1px solid #dddddd;padding:0.625em 0.75em;}.vcard li{margin:0;display:block;}.vcard .fn{font-weight:bold;font-size:0.9375em;}.vevent .summary{font-weight:bold;}.vevent abbr{cursor:auto;text-decoration:none;font-weight:bold;border:none;padding:0 0.0625em;}@media only screen and (min-width: 768px) {h1,h2,h3,#toctitle,.sidebarblock>.content>.title,h4,h5,h6{line-height:1.4;}h1{font-size:2.75em;}h2{font-size:2.3125em;}h3,#toctitle,.sidebarblock>.content>.title{font-size:1.6875em;}h4{font-size:1.4375em;}}.print-only{display:none!important;}@media print {*{background:transparent!important;color:#000!important;box-shadow:none!important;text-shadow:none!important;}a,a:visited{text-decoration:underline;}a[href]:after{content:" (" attr(href) ")";}abbr[title]:after{content:" (" attr(title) ")";}.ir a:after,a[href^="javascript:"]:after,a[href^="#"]:after{content:"";}pre,blockquote{border:1px solid #999;page-break-inside:avoid;}thead{display:table-header-group;}tr,img{page-break-inside:avoid;}img{max-width:100%!important;}@page{margin:0.5cm;}p,h2,h3,#toctitle,.sidebarblock>.content>.title{orphans:3;widows:3;}h2,h3,#toctitle,.sidebarblock>.content>.title{page-break-after:avoid;}.hide-on-print{display:none!important;}.print-only{display:block!important;}.hide-for-print{display:none!important;}.show-for-print{display:inherit!important;}}table{background:white;margin-bottom:1.25em;border:solid 1px #dddddd;}table thead,table tfoot{background:whitesmoke;font-weight:bold;}table thead tr th,table thead tr td,table tfoot tr th,table tfoot tr td{padding:0.5em 0.625em 0.625em;font-size:inherit;color:#222222;text-align:left;}table tr th,table tr td{padding:0.5625em 0.625em;font-size:inherit;color:#222222;}table tr.even,table tr.alt,table tr:nth-of-type(even){background:#f9f9f9;}table thead tr th,table tfoot tr th,table tbody tr td,table tr td,table tfoot tr td{display:table-cell;line-height:1.6;}.clearfix:before,.clearfix:after,.float-group:before,.float-group:after{content:" ";display:table;}.clearfix:after,.float-group:after{clear:both;}*:not(pre)>code{font-size:0.9375em;padding:1px 3px 0;white-space:nowrap;background-color:#f2f2f2;border:1px solid #cccccc;-webkit-border-radius:4px;border-radius:4px;text-shadow:none;}pre,pre>code{line-height:1.4;color:inherit;font-family:Consolas,"Liberation Mono",Courier,monospace;font-weight:normal;}kbd.keyseq{color:#555555;}kbd:not(.keyseq){display:inline-block;color:#222222;font-size:0.75em;line-height:1.4;background-color:#F7F7F7;border:1px solid #ccc;-webkit-border-radius:3px;border-radius:3px;-webkit-box-shadow:0 1px 0 rgba(0,0,0,0.2),0 0 0 2px white inset;box-shadow:0 1px 0 rgba(0,0,0,0.2),0 0 0 2px white inset;margin:-0.15em 0.15em 0 0.15em;padding:0.2em 0.6em 0.2em 0.5em;vertical-align:middle;white-space:nowrap;}kbd kbd:first-child{margin-left:0;}kbd kbd:last-child{margin-right:0;}.menuseq,.menu{color:#090909;}p a>code:hover{color:#561309;}#header,#content,#footnotes,#footer{width:100%;margin-left:auto;margin-right:auto;margin-top:0;margin-bottom:0;max-width:62.5em;*zoom:1;position:relative;padding-left:0.9375em;padding-right:0.9375em;}#header:before,#header:after,#content:before,#content:after,#footnotes:before,#footnotes:after,#footer:before,#footer:after{content:" ";display:table;}#header:after,#content:after,#footnotes:after,#footer:after{clear:both;}#header{margin-bottom:2.5em;}#header>h1{color:black;font-weight:normal;border-bottom:1px solid #dddddd;margin-bottom:-28px;padding-bottom:32px;}#header span{color:#6f6f6f;}#header #revnumber{text-transform:capitalize;}#header br{display:none;}#header br+span{padding-left:3px;}#header br+span:before{content:"\2013 \0020";}#header br+span.author{padding-left:0;}#header br+span.author:before{content:", ";}#toc{border-bottom:3px double #ebebeb;padding-bottom:1.25em;}#toc>ul{margin-left:0.25em;}#toc ul.sectlevel0>li>a{font-style:italic;}#toc ul.sectlevel0 ul.sectlevel1{margin-left:0;margin-top:0.5em;margin-bottom:0.5em;}#toc ul{list-style-type:none;}#toctitle{color:#7a2518;}@media only screen and (min-width: 1280px) {body.toc2{padding-left:20em;}#toc.toc2{position:fixed;width:20em;left:0;top:0;border-right:1px solid #ebebeb;border-bottom:0;z-index:1000;padding:1em;height:100%;overflow:auto;}#toc.toc2 #toctitle{margin-top:0;}#toc.toc2>ul{font-size:.95em;}#toc.toc2 ul ul{margin-left:0;padding-left:1.25em;}#toc.toc2 ul.sectlevel0 ul.sectlevel1{padding-left:0;margin-top:0.5em;margin-bottom:0.5em;}body.toc2.toc-right{padding-left:0;padding-right:20em;}body.toc2.toc-right #toc.toc2{border-right:0;border-left:1px solid #ebebeb;left:auto;right:0;}}#content #toc{border-style:solid;border-width:1px;border-color:#d9d9d9;margin-bottom:1.25em;padding:1.25em;background:#f2f2f2;border-width:0;-webkit-border-radius:4px;border-radius:4px;}#content #toc>:first-child{margin-top:0;}#content #toc>:last-child{margin-bottom:0;}#content #toc a{text-decoration:none;}#content #toctitle{font-weight:bold;font-family:"Helvetica Neue","Helvetica",Helvetica,Arial,sans-serif;font-size:1em;padding-left:0.125em;}#footer{max-width:100%;background-color:#222222;padding:1.25em;}#footer-text{color:#dddddd;line-height:1.44;}.sect1{padding-bottom:1.25em;}.sect1+.sect1{border-top:3px double #ebebeb;}#content h1>a.anchor,h2>a.anchor,h3>a.anchor,#toctitle>a.anchor,.sidebarblock>.content>.title>a.anchor,h4>a.anchor,h5>a.anchor,h6>a.anchor{position:absolute;width:1em;margin-left:-1em;display:block;text-decoration:none;visibility:hidden;text-align:center;font-weight:normal;}#content h1>a.anchor:before,h2>a.anchor:before,h3>a.anchor:before,#toctitle>a.anchor:before,.sidebarblock>.content>.title>a.anchor:before,h4>a.anchor:before,h5>a.anchor:before,h6>a.anchor:before{content:'\00A7';font-size:.85em;vertical-align:text-top;display:block;margin-top:0.05em;}#content h1:hover>a.anchor,#content h1>a.anchor:hover,h2:hover>a.anchor,h2>a.anchor:hover,h3:hover>a.anchor,#toctitle:hover>a.anchor,.sidebarblock>.content>.title:hover>a.anchor,h3>a.anchor:hover,#toctitle>a.anchor:hover,.sidebarblock>.content>.title>a.anchor:hover,h4:hover>a.anchor,h4>a.anchor:hover,h5:hover>a.anchor,h5>a.anchor:hover,h6:hover>a.anchor,h6>a.anchor:hover{visibility:visible;}#content h1>a.link,h2>a.link,h3>a.link,#toctitle>a.link,.sidebarblock>.content>.title>a.link,h4>a.link,h5>a.link,h6>a.link{color:#ba3925;text-decoration:none;}#content h1>a.link:hover,h2>a.link:hover,h3>a.link:hover,#toctitle>a.link:hover,.sidebarblock>.content>.title>a.link:hover,h4>a.link:hover,h5>a.link:hover,h6>a.link:hover{color:#a53221;}.imageblock,.literalblock,.listingblock,.verseblock,.videoblock{margin-bottom:1.25em;}.admonitionblock td.content>.title,.exampleblock>.title,.imageblock>.title,.videoblock>.title,.listingblock>.title,.literalblock>.title,.openblock>.title,.paragraph>.title,.quoteblock>.title,.sidebarblock>.title,.tableblock>.title,.verseblock>.title,.dlist>.title,.olist>.title,.ulist>.title,.qlist>.title,.hdlist>.title{text-align:left;font-weight:bold;}.tableblock>caption{text-align:left;font-weight:bold;white-space:nowrap;overflow:visible;max-width:0;}table.tableblock #preamble>.sectionbody>.paragraph:first-of-type p{font-size:inherit;}.admonitionblock>table{border:0;background:none;width:100%;}.admonitionblock>table td.icon{text-align:center;width:80px;}.admonitionblock>table td.icon img{max-width:none;}.admonitionblock>table td.icon .title{font-weight:bold;text-transform:uppercase;}.admonitionblock>table td.content{padding-left:1.125em;padding-right:1.25em;border-left:1px solid #dddddd;color:#6f6f6f;}.admonitionblock>table td.content>:last-child>:last-child{margin-bottom:0;}.exampleblock>.content{border-style:solid;border-width:1px;border-color:#e6e6e6;margin-bottom:1.25em;padding:1.25em;background:white;-webkit-border-radius:4px;border-radius:4px;}.exampleblock>.content>:first-child{margin-top:0;}.exampleblock>.content>:last-child{margin-bottom:0;}.exampleblock>.content h1,.exampleblock>.content h2,.exampleblock>.content h3,.exampleblock>.content #toctitle,.sidebarblock.exampleblock>.content>.title,.exampleblock>.content h4,.exampleblock>.content h5,.exampleblock>.content h6,.exampleblock>.content p{color:#333333;}.exampleblock>.content h1,.exampleblock>.content h2,.exampleblock>.content h3,.exampleblock>.content #toctitle,.sidebarblock.exampleblock>.content>.title,.exampleblock>.content h4,.exampleblock>.content h5,.exampleblock>.content h6{line-height:1;margin-bottom:0.625em;}.exampleblock>.content h1.subheader,.exampleblock>.content h2.subheader,.exampleblock>.content h3.subheader,.exampleblock>.content .subheader#toctitle,.sidebarblock.exampleblock>.content>.subheader.title,.exampleblock>.content h4.subheader,.exampleblock>.content h5.subheader,.exampleblock>.content h6.subheader{line-height:1.4;}.exampleblock.result>.content{-webkit-box-shadow:0 1px 8px #d9d9d9;box-shadow:0 1px 8px #d9d9d9;}.sidebarblock{border-style:solid;border-width:1px;border-color:#d9d9d9;margin-bottom:1.25em;padding:1.25em;background:#f2f2f2;-webkit-border-radius:4px;border-radius:4px;}.sidebarblock>:first-child{margin-top:0;}.sidebarblock>:last-child{margin-bottom:0;}.sidebarblock h1,.sidebarblock h2,.sidebarblock h3,.sidebarblock #toctitle,.sidebarblock>.content>.title,.sidebarblock h4,.sidebarblock h5,.sidebarblock h6,.sidebarblock p{color:#333333;}.sidebarblock h1,.sidebarblock h2,.sidebarblock h3,.sidebarblock #toctitle,.sidebarblock>.content>.title,.sidebarblock h4,.sidebarblock h5,.sidebarblock h6{line-height:1;margin-bottom:0.625em;}.sidebarblock h1.subheader,.sidebarblock h2.subheader,.sidebarblock h3.subheader,.sidebarblock .subheader#toctitle,.sidebarblock>.content>.subheader.title,.sidebarblock h4.subheader,.sidebarblock h5.subheader,.sidebarblock h6.subheader{line-height:1.4;}.sidebarblock>.content>.title{color:#7a2518;margin-top:0;line-height:1.6;}.exampleblock>.content>:last-child>:last-child,.exampleblock>.content .olist>ol>li:last-child>:last-child,.exampleblock>.content .ulist>ul>li:last-child>:last-child,.exampleblock>.content .qlist>ol>li:last-child>:last-child,.sidebarblock>.content>:last-child>:last-child,.sidebarblock>.content .olist>ol>li:last-child>:last-child,.sidebarblock>.content .ulist>ul>li:last-child>:last-child,.sidebarblock>.content .qlist>ol>li:last-child>:last-child{margin-bottom:0;}.literalblock>.content pre,.listingblock>.content pre{background:none;border-width:1px 0;border-style:dotted;border-color:#bfbfbf;-webkit-border-radius:4px;border-radius:4px;padding:0.75em 0.75em 0.5em 0.75em;word-wrap:break-word;}.literalblock>.content pre.nowrap,.listingblock>.content pre.nowrap{overflow-x:auto;white-space:pre;word-wrap:normal;}.literalblock>.content pre>code,.listingblock>.content pre>code{display:block;}@media only screen {.literalblock>.content pre,.listingblock>.content pre{font-size:0.8em;}}@media only screen and (min-width: 768px) {.literalblock>.content pre,.listingblock>.content pre{font-size:0.9em;}}@media only screen and (min-width: 1280px) {.literalblock>.content pre,.listingblock>.content pre{font-size:1em;}}.listingblock>.content{position:relative;}.listingblock:hover code[class*=" language-"]:before{text-transform:uppercase;font-size:0.9em;color:#999;position:absolute;top:0.375em;right:0.375em;}.listingblock:hover code.asciidoc:before{content:"asciidoc";}.listingblock:hover code.clojure:before{content:"clojure";}.listingblock:hover code.css:before{content:"css";}.listingblock:hover code.groovy:before{content:"groovy";}.listingblock:hover code.html:before{content:"html";}.listingblock:hover code.java:before{content:"java";}.listingblock:hover code.javascript:before{content:"javascript";}.listingblock:hover code.python:before{content:"python";}.listingblock:hover code.ruby:before{content:"ruby";}.listingblock:hover code.scss:before{content:"scss";}.listingblock:hover code.xml:before{content:"xml";}.listingblock:hover code.yaml:before{content:"yaml";}.listingblock.terminal pre .command:before{content:attr(data-prompt);padding-right:0.5em;color:#999;}.listingblock.terminal pre .command:not([data-prompt]):before{content:'$';}table.pyhltable{border:0;margin-bottom:0;}table.pyhltable td{vertical-align:top;padding-top:0;padding-bottom:0;}table.pyhltable td.code{padding-left:.75em;padding-right:0;}.highlight.pygments .lineno,table.pyhltable td:not(.code){color:#999;padding-left:0;padding-right:.5em;border-right:1px solid #dddddd;}.highlight.pygments .lineno{display:inline-block;margin-right:.25em;}table.pyhltable .linenodiv{background-color:transparent!important;padding-right:0!important;}.quoteblock{margin:0 0 1.25em;padding:0.5625em 1.25em 0 1.1875em;border-left:1px solid #dddddd;}.quoteblock blockquote{margin:0 0 1.25em 0;padding:0 0 0.5625em 0;border:0;}.quoteblock blockquote>.paragraph:last-child p{margin-bottom:0;}.quoteblock .attribution{margin-top:-.25em;padding-bottom:0.5625em;font-size:inherit;color:#555555;}.quoteblock .attribution br{display:none;}.quoteblock .attribution cite{display:block;margin-bottom:0.625em;}table thead th,table tfoot th{font-weight:bold;}table.tableblock.grid-all{border-collapse:separate;border-spacing:1px;-webkit-border-radius:4px;border-radius:4px;border-top:1px solid #dddddd;border-bottom:1px solid #dddddd;}table.tableblock.frame-topbot,table.tableblock.frame-none{border-left:0;border-right:0;}table.tableblock.frame-sides,table.tableblock.frame-none{border-top:0;border-bottom:0;}table.tableblock td .paragraph:last-child p,table.tableblock td>p:last-child{margin-bottom:0;}th.tableblock.halign-left,td.tableblock.halign-left{text-align:left;}th.tableblock.halign-right,td.tableblock.halign-right{text-align:right;}th.tableblock.halign-center,td.tableblock.halign-center{text-align:center;}th.tableblock.valign-top,td.tableblock.valign-top{vertical-align:top;}th.tableblock.valign-bottom,td.tableblock.valign-bottom{vertical-align:bottom;}th.tableblock.valign-middle,td.tableblock.valign-middle{vertical-align:middle;}p.tableblock.header{color:#222222;font-weight:bold;}td>div.verse{white-space:pre;}ol{margin-left:1.75em;}ul li ol{margin-left:1.5em;}dl dd{margin-left:1.125em;}dl dd:last-child,dl dd:last-child>:last-child{margin-bottom:0;}ol>li p,ul>li p,ul dd,ol dd,.olist .olist,.ulist .ulist,.ulist .olist,.olist .ulist{margin-bottom:0.625em;}ul.unstyled,ol.unnumbered,ul.checklist,ul.none{list-style-type:none;}ul.unstyled,ol.unnumbered,ul.checklist{margin-left:0.625em;}ul.checklist li>p:first-child>i[class^="icon-check"]:first-child,ul.checklist li>p:first-child>input[type="checkbox"]:first-child{margin-right:0.25em;}ul.checklist li>p:first-child>input[type="checkbox"]:first-child{position:relative;top:1px;}ul.inline{margin:0 auto 0.625em auto;margin-left:-1.375em;margin-right:0;padding:0;list-style:none;overflow:hidden;}ul.inline>li{list-style:none;float:left;margin-left:1.375em;display:block;}ul.inline>li>*{display:block;}.unstyled dl dt{font-weight:normal;font-style:normal;}ol.arabic{list-style-type:decimal;}ol.decimal{list-style-type:decimal-leading-zero;}ol.loweralpha{list-style-type:lower-alpha;}ol.upperalpha{list-style-type:upper-alpha;}ol.lowerroman{list-style-type:lower-roman;}ol.upperroman{list-style-type:upper-roman;}ol.lowergreek{list-style-type:lower-greek;}.hdlist>table,.colist>table{border:0;background:none;}.hdlist>table>tbody>tr,.colist>table>tbody>tr{background:none;}td.hdlist1{padding-right:.8em;font-weight:bold;}td.hdlist1,td.hdlist2{vertical-align:top;}.literalblock+.colist,.listingblock+.colist{margin-top:-0.5em;}.colist>table tr>td:first-of-type{padding:0 .8em;line-height:1;}.colist>table tr>td:last-of-type{padding:0.25em 0;}.qanda>ol>li>p>em:only-child{color:#00467f;}.thumb,.th{line-height:0;display:inline-block;border:solid 4px white;-webkit-box-shadow:0 0 0 1px #dddddd;box-shadow:0 0 0 1px #dddddd;}.imageblock.left,.imageblock[style*="float: left"]{margin:0.25em 0.625em 1.25em 0;}.imageblock.right,.imageblock[style*="float: right"]{margin:0.25em 0 1.25em 0.625em;}.imageblock>.title{margin-bottom:0;}.imageblock.thumb,.imageblock.th{border-width:6px;}.imageblock.thumb>.title,.imageblock.th>.title{padding:0 0.125em;}.image.left,.image.right{margin-top:0.25em;margin-bottom:0.25em;display:inline-block;line-height:0;}.image.left{margin-right:0.625em;}.image.right{margin-left:0.625em;}a.image{text-decoration:none;}span.footnote,span.footnoteref{vertical-align:super;font-size:0.875em;}span.footnote a,span.footnoteref a{text-decoration:none;}#footnotes{padding-top:0.75em;padding-bottom:0.75em;margin-bottom:0.625em;}#footnotes hr{width:20%;min-width:6.25em;margin:-.25em 0 .75em 0;border-width:1px 0 0 0;}#footnotes .footnote{padding:0 0.375em;line-height:1.3;font-size:0.875em;margin-left:1.2em;text-indent:-1.2em;margin-bottom:.2em;}#footnotes .footnote a:first-of-type{font-weight:bold;text-decoration:none;}#footnotes .footnote:last-of-type{margin-bottom:0;}#content #footnotes{margin-top:-0.625em;margin-bottom:0;padding:0.75em 0;}.gist .file-data>table{border:none;background:#fff;width:100%;margin-bottom:0;}.gist .file-data>table td.line-data{width:99%;}div.unbreakable{page-break-inside:avoid;}.big{font-size:larger;}.small{font-size:smaller;}.underline{text-decoration:underline;}.overline{text-decoration:overline;}.line-through{text-decoration:line-through;}.aqua{color:#00bfbf;}.aqua-background{background-color:#00fafa;}.black{color:black;}.black-background{background-color:black;}.blue{color:#0000bf;}.blue-background{background-color:#0000fa;}.fuchsia{color:#bf00bf;}.fuchsia-background{background-color:#fa00fa;}.gray{color:#606060;}.gray-background{background-color:#7d7d7d;}.green{color:#006000;}.green-background{background-color:#007d00;}.lime{color:#00bf00;}.lime-background{background-color:#00fa00;}.maroon{color:#600000;}.maroon-background{background-color:#7d0000;}.navy{color:#000060;}.navy-background{background-color:#00007d;}.olive{color:#606000;}.olive-background{background-color:#7d7d00;}.purple{color:#600060;}.purple-background{background-color:#7d007d;}.red{color:#bf0000;}.red-background{background-color:#fa0000;}.silver{color:#909090;}.silver-background{background-color:#bcbcbc;}.teal{color:#006060;}.teal-background{background-color:#007d7d;}.white{color:#bfbfbf;}.white-background{background-color:#fafafa;}.yellow{color:#bfbf00;}.yellow-background{background-color:#fafa00;}span.icon>[class^="icon-"],span.icon>[class*=" icon-"]{cursor:default;}.admonitionblock td.icon [class^="icon-"]:before{font-size:2.5em;text-shadow:1px 1px 2px rgba(0,0,0,0.5);cursor:default;}.admonitionblock td.icon .icon-note:before{content:"\f05a";color:#005498;color:#003f72;}.admonitionblock td.icon .icon-tip:before{content:"\f0eb";text-shadow:1px 1px 2px rgba(155,155,0,0.8);color:#111;}.admonitionblock td.icon .icon-warning:before{content:"\f071";color:#bf6900;}.admonitionblock td.icon .icon-caution:before{content:"\f06d";color:#bf3400;}.admonitionblock td.icon .icon-important:before{content:"\f06a";color:#bf0000;}.conum{display:inline-block;color:white!important;background-color:#222222;-webkit-border-radius:100px;border-radius:100px;text-align:center;width:20px;height:20px;font-size:12px;font-weight:bold;line-height:20px;font-family:Arial,sans-serif;font-style:normal;position:relative;top:-2px;letter-spacing:-1px;}.conum *{color:white!important;}.conum+b{display:none;}.conum:after{content:attr(data-value);}.conum:not([data-value]):empty{display:none;}.literalblock>.content>pre,.listingblock>.content>pre{-webkit-border-radius:0;border-radius:0;}</style> <link rel="stylesheet" href="Spring%20Security%20Reference_files/font-awesome.css"> <link rel="stylesheet" href="Spring%20Security%20Reference_files/prettify.css"> <script id="undefined" src="Spring%20Security%20Reference_files/inpage_linkid.js" async="" type="text/javascript"></script><script src="Spring%20Security%20Reference_files/ga.js" async="" type="text/javascript"></script><script src="Spring%20Security%20Reference_files/prettify.js"></script> <script>document.addEventListener('DOMContentLoaded', prettyPrint)</script> <script type="text/javascript" src="Spring%20Security%20Reference_files/jquery-1.js"></script><link rel="stylesheet" href="Spring%20Security%20Reference_files/searchtool.css" type="text/css"><link rel="stylesheet" href="Spring%20Security%20Reference_files/searchtool_spring.css" type="text/css"><style>/* docsearchbarspring Training Classes */ .S2UniGeoipBanner { margin-top: 0px !important; letter-spacing: 0px !important; line-height: 1.2 !important; text-align: left !important; text-indent: 0 !important; text-transform: none !important; word-spacing: 0px !important; cursor: pointer !important; left: 210px !important; position: absolute !important; top: 6px !important; } .S2UniGeoipBanner .S2GPcourse_name { font-size: 11px !important; font-weight: bold !important; font-family: Arial !important; text-transform: uppercase !important; color: #88f !important; } .S2UniGeoipBanner .S2GPcity, .S2UniGeoipBanner .S2GPstart_date { font-family: Arial !important; font-size: 11px !important; color: #bbb !important; } .S2UniGeoipBanner .learn-more-button { display:none !important; }</style></head> <body class="book toc2 toc-left"> <div id="header"> <h1>Spring Security Reference</h1> <span id="author" class="author">Ben Alex</span><br><span id="author2" class="author">Luke Taylor</span><br><span id="author3" class="author">Rob Winch</span><br> <span id="revnumber">version 3.2.6.RELEASE</span> <div id="toc" class="toc2"> <div id="toctitle">Table of Contents</div> <ul class="sectlevel0"> <li><a href="#preface">Preface</a></li> <li><a href="#getting-started">Getting Started</a></li> <li> <ul class="sectlevel1"> <li><a href="#introduction">1. Introduction</a></li> <li> <ul class="sectlevel2"> <li><a href="#what-is-acegi-security">1.1. What is Spring Security?</a></li> <li><a href="#history">1.2. History</a></li> <li><a href="#release-numbering">1.3. Release Numbering</a></li> <li><a href="#get-spring-security">1.4. Getting Spring Security</a></li> </ul> </li> <li><a href="#new">2. What’s new in Spring Security 3.2</a></li> <li><a href="#jc">3. Java Configuration</a></li> <li> <ul class="sectlevel2"> <li><a href="#hello-web-security-java-configuration">3.1. Hello Web Security Java Configuration</a></li> <li><a href="#jc-httpsecurity">3.2. HttpSecurity</a></li> <li><a href="#jc-form">3.3. Java Configuration and Form Login</a></li> <li><a href="#authorize-requests">3.4. Authorize Requests</a></li> <li><a href="#jc-authentication">3.5. Authentication</a></li> <li><a href="#multiple-httpsecurity">3.6. Multiple HttpSecurity</a></li> <li><a href="#jc-method">3.7. Method Security</a></li> <li><a href="#post-processing-configured-objects">3.8. Post Processing Configured Objects</a></li> </ul> </li> <li><a href="#ns-config">4. Security Namespace Configuration</a></li> <li> <ul class="sectlevel2"> <li><a href="#introduction-2">4.1. Introduction</a></li> <li><a href="#ns-getting-started">4.2. Getting Started with Security Namespace Configuration</a></li> <li><a href="#ns-web-advanced">4.3. Advanced Web Features</a></li> <li><a href="#ns-method-security">4.4. Method Security</a></li> <li><a href="#ns-access-manager">4.5. The Default AccessDecisionManager</a></li> <li><a href="#ns-auth-manager">4.6. The Authentication Manager and the Namespace</a></li> </ul> </li> <li><a href="#sample-apps">5. Sample Applications</a></li> <li> <ul class="sectlevel2"> <li><a href="#tutorial-sample">5.1. Tutorial Sample</a></li> <li><a href="#contacts-sample">5.2. Contacts</a></li> <li><a href="#ldap-sample">5.3. LDAP Sample</a></li> <li><a href="#openid-sample">5.4. OpenID Sample</a></li> <li><a href="#cas-sample">5.5. CAS Sample</a></li> <li><a href="#jaas-sample">5.6. JAAS Sample</a></li> <li><a href="#preauth-sample">5.7. Pre-Authentication Sample</a></li> </ul> </li> <li><a href="#community">6. Spring Security Community</a></li> <li> <ul class="sectlevel2"> <li><a href="#jira">6.1. Issue Tracking</a></li> <li><a href="#becoming-involved">6.2. Becoming Involved</a></li> <li><a href="#further-info">6.3. Further Information</a></li> </ul> </li> </ul> </li> <li><a href="#overall-architecture">Architecture and Implementation</a></li> <li> <ul class="sectlevel1"> <li><a href="#technical-overview">1. Technical Overview</a></li> <li> <ul class="sectlevel2"> <li><a href="#runtime-environment">1.1. Runtime Environment</a></li> <li><a href="#core-components">1.2. Core Components</a></li> <li><a href="#tech-intro-authentication">1.3. Authentication</a></li> <li><a href="#tech-intro-web-authentication">1.4. Authentication in a Web Application</a></li> <li><a href="#tech-intro-access-control">1.5. Access-Control (Authorization) in Spring Security</a></li> <li><a href="#localization">1.6. Localization</a></li> </ul> </li> <li><a href="#core-services">2. Core Services</a></li> <li> <ul class="sectlevel2"> <li><a href="#core-services-authentication-manager">2.1. The AuthenticationManager, ProviderManager and AuthenticationProvider</a></li> <li><a href="#userdetailsservice-implementations">2.2. UserDetailsService Implementations</a></li> <li><a href="#core-services-password-encoding">2.3. Password Encoding</a></li> </ul> </li> </ul> </li> <li><a href="#web-app-security">Web Application Security</a></li> <li> <ul class="sectlevel1"> <li><a href="#security-filter-chain">1. The Security Filter Chain</a></li> <li> <ul class="sectlevel2"> <li><a href="#delegating-filter-proxy">1.1. DelegatingFilterProxy</a></li> <li><a href="#filter-chain-proxy">1.2. FilterChainProxy</a></li> <li><a href="#filter-ordering">1.3. Filter Ordering</a></li> <li><a href="#request-matching">1.4. Request Matching and HttpFirewall</a></li> <li><a href="#use-with-other-filter-based-frameworks">1.5. Use with other Filter-Based Frameworks</a></li> <li><a href="#filter-chains-with-ns">1.6. Advanced Namespace Configuration</a></li> </ul> </li> <li><a href="#core-web-filters">2. Core Security Filters</a></li> <li> <ul class="sectlevel2"> <li><a href="#filter-security-interceptor">2.1. FilterSecurityInterceptor</a></li> <li><a href="#exception-translation-filter">2.2. ExceptionTranslationFilter</a></li> <li><a href="#security-context-persistence-filter">2.3. SecurityContextPersistenceFilter</a></li> <li><a href="#form-login-filter">2.4. UsernamePasswordAuthenticationFilter</a></li> </ul> </li> <li><a href="#servletapi">3. Servlet API integration</a></li> <li> <ul class="sectlevel2"> <li><a href="#servletapi-25">3.1. Servlet 2.5+ Integration</a></li> <li><a href="#servletapi-3">3.2. Servlet 3+ Integration</a></li> <li><a href="#servletapi-31">3.3. Servlet 3.1+ Integration</a></li> </ul> </li> <li><a href="#basic">4. Basic and Digest Authentication</a></li> <li> <ul class="sectlevel2"> <li><a href="#basic-processing-filter">4.1. BasicAuthenticationFilter</a></li> <li><a href="#digest-processing-filter">4.2. DigestAuthenticationFilter</a></li> </ul> </li> <li><a href="#remember-me">5. Remember-Me Authentication</a></li> <li> <ul class="sectlevel2"> <li><a href="#remember-me-overview">5.1. Overview</a></li> <li><a href="#remember-me-hash-token">5.2. Simple Hash-Based Token Approach</a></li> <li><a href="#remember-me-persistent-token">5.3. Persistent Token Approach</a></li> <li><a href="#remember-me-impls">5.4. Remember-Me Interfaces and Implementations</a></li> </ul> </li> <li><a href="#csrf">6. Cross Site Request Forgery (CSRF)</a></li> <li> <ul class="sectlevel2"> <li><a href="#csrf-attacks">6.1. CSRF Attacks</a></li> <li><a href="#synchronizer-token-pattern">6.2. Synchronizer Token Pattern</a></li> <li><a href="#when-to-use-csrf-protection">6.3. When to use CSRF protection</a></li> <li><a href="#csrf-using">6.4. Using Spring Security CSRF Protection</a></li> <li><a href="#csrf-caveats">6.5. CSRF Caveats</a></li> <li><a href="#overriding-defaults">6.6. Overriding Defaults</a></li> </ul> </li> <li><a href="#headers">7. Security HTTP Response Headers</a></li> <li> <ul class="sectlevel2"> <li><a href="#default-security-headers">7.1. Default Security Headers</a></li> <li><a href="#headers-custom">7.2. Custom Headers</a></li> </ul> </li> <li><a href="#session-mgmt">8. Session Management</a></li> <li> <ul class="sectlevel2"> <li><a href="#sessionmanagementfilter">8.1. SessionManagementFilter</a></li> <li><a href="#sessionauthenticationstrategy">8.2. SessionAuthenticationStrategy</a></li> <li><a href="#concurrent-sessions">8.3. Concurrency Control</a></li> </ul> </li> <li><a href="#anonymous">9. Anonymous Authentication</a></li> <li> <ul class="sectlevel2"> <li><a href="#anonymous-overview">9.1. Overview</a></li> <li><a href="#anonymous-config">9.2. Configuration</a></li> <li><a href="#anonymous-auth-trust-resolver">9.3. AuthenticationTrustResolver</a></li> </ul> </li> </ul> </li> <li><a href="#authorization">Authorization</a></li> <li> <ul class="sectlevel1"> <li><a href="#authz-arch">1. Authorization Architecture</a></li> <li> <ul class="sectlevel2"> <li><a href="#authz-authorities">1.1. Authorities</a></li> <li><a href="#authz-pre-invocation">1.2. Pre-Invocation Handling</a></li> <li><a href="#authz-after-invocation-handling">1.3. After Invocation Handling</a></li> <li><a href="#authz-hierarchical-roles">1.4. Hierarchical Roles</a></li> </ul> </li> <li><a href="#secure-object-impls">2. Secure Object Implementations</a></li> <li> <ul class="sectlevel2"> <li><a href="#aop-alliance">2.1. AOP Alliance (MethodInvocation) Security Interceptor</a></li> <li><a href="#aspectj">2.2. AspectJ (JoinPoint) Security Interceptor</a></li> </ul> </li> <li><a href="#el-access">3. Expression-Based Access Control</a></li> <li> <ul class="sectlevel2"> <li><a href="#overview">3.1. Overview</a></li> <li><a href="#el-access-web">3.2. Web Security Expressions</a></li> <li><a href="#method-security-expressions">3.3. Method Security Expressions</a></li> </ul> </li> </ul> </li> <li><a href="#advanced-topics">Additional Topics</a></li> <li> <ul class="sectlevel1"> <li><a href="#domain-acls">1. Domain Object Security (ACLs)</a></li> <li> <ul class="sectlevel2"> <li><a href="#domain-acls-overview">1.1. Overview</a></li> <li><a href="#domain-acls-key-concepts">1.2. Key Concepts</a></li> <li><a href="#domain-acls-getting-started">1.3. Getting Started</a></li> </ul> </li> <li><a href="#preauth">2. Pre-Authentication Scenarios</a></li> <li> <ul class="sectlevel2"> <li><a href="#pre-authentication-framework-classes">2.1. Pre-Authentication Framework Classes</a></li> <li><a href="#concrete-implementations">2.2. Concrete Implementations</a></li> </ul> </li> <li><a href="#ldap">3. LDAP Authentication</a></li> <li> <ul class="sectlevel2"> <li><a href="#ldap-overview">3.1. Overview</a></li> <li><a href="#using-ldap-with-spring-security">3.2. Using LDAP with Spring Security</a></li> <li><a href="#ldap-server">3.3. Configuring an LDAP Server</a></li> <li><a href="#implementation-classes">3.4. Implementation Classes</a></li> <li><a href="#ldap-active-directory">3.5. Active Directory Authentication</a></li> </ul> </li> <li><a href="#taglibs">4. JSP Tag Libraries</a></li> <li> <ul class="sectlevel2"> <li><a href="#declaring-the-taglib">4.1. Declaring the Taglib</a></li> <li><a href="#the-authorize-tag">4.2. The authorize Tag</a></li> <li><a href="#the-authentication-tag">4.3. The authentication Tag</a></li> <li><a href="#the-accesscontrollist-tag">4.4. The accesscontrollist Tag</a></li> <li><a href="#the-csrfinput-tag">4.5. The csrfInput Tag</a></li> <li><a href="#the-csrfmetatags-tag">4.6. The csrfMetaTags Tag</a></li> </ul> </li> <li><a href="#jaas">5. Java Authentication and Authorization Service (JAAS) Provider</a></li> <li> <ul class="sectlevel2"> <li><a href="#overview-2">5.1. Overview</a></li> <li><a href="#jaas-abstractjaasauthenticationprovider">5.2. AbstractJaasAuthenticationProvider</a></li> <li><a href="#jaas-defaultjaasauthenticationprovider">5.3. DefaultJaasAuthenticationProvider</a></li> <li><a href="#jaas-jaasauthenticationprovider">5.4. JaasAuthenticationProvider</a></li> <li><a href="#jaas-apiprovision">5.5. Running as a Subject</a></li> </ul> </li> <li><a href="#cas">6. CAS Authentication</a></li> <li> <ul class="sectlevel2"> <li><a href="#cas-overview">6.1. Overview</a></li> <li><a href="#cas-how-it-works">6.2. How CAS Works</a></li> <li><a href="#cas-client">6.3. Configuration of CAS Client</a></li> </ul> </li> <li><a href="#x509">7. X.509 Authentication</a></li> <li> <ul class="sectlevel2"> <li><a href="#x509-overview">7.1. Overview</a></li> <li><a href="#adding-x-509-authentication-to-your-web-application">7.2. Adding X.509 Authentication to Your Web Application</a></li> <li><a href="#x509-ssl-config">7.3. Setting up SSL in Tomcat</a></li> </ul> </li> <li><a href="#runas">8. Run-As Authentication Replacement</a></li> <li> <ul class="sectlevel2"> <li><a href="#runas-overview">8.1. Overview</a></li> <li><a href="#runas-config">8.2. Configuration</a></li> </ul> </li> <li><a href="#crypto">9. Spring Security Crypto Module</a></li> <li> <ul class="sectlevel2"> <li><a href="#spring-security-crypto-introduction">9.1. Introduction</a></li> <li><a href="#spring-security-crypto-encryption">9.2. Encryptors</a></li> <li><a href="#spring-security-crypto-keygenerators">9.3. Key Generators</a></li> <li><a href="#spring-security-crypto-passwordencoders">9.4. Password Encoding</a></li> </ul> </li> <li><a href="#concurrency">10. Concurrency Support</a></li> <li> <ul class="sectlevel2"> <li><a href="#delegatingsecuritycontextrunnable">10.1. DelegatingSecurityContextRunnable</a></li> <li><a href="#delegatingsecuritycontextexecutor">10.2. DelegatingSecurityContextExecutor</a></li> <li><a href="#spring-security-concurrency-classes">10.3. Spring Security Concurrency Classes</a></li> </ul> </li> <li><a href="#mvc">11. Spring MVC Integration</a></li> <li> <ul class="sectlevel2"> <li><a href="#mvc-enablewebmvcsecurity">11.1. @EnableWebMvcSecurity</a></li> <li><a href="#mvc-authentication-principal">11.2. @AuthenticationPrincipal</a></li> <li><a href="#mvc-async">11.3. Spring MVC Async Integration</a></li> <li><a href="#mvc-csrf">11.4. Spring MVC and CSRF Integration</a></li> </ul> </li> </ul> </li> <li><a href="#appendix">Appendix</a></li> <li> <ul class="sectlevel1"> <li><a href="#appendix-schema">1. Security Database Schema</a></li> <li> <ul class="sectlevel2"> <li><a href="#user-schema">1.1. User Schema</a></li> <li><a href="#persistent-login-remember-me-schema">1.2. Persistent Login (Remember-Me) Schema</a></li> <li><a href="#dbschema-acl">1.3. ACL Schema</a></li> </ul> </li> <li><a href="#appendix-namespace">2. The Security Namespace</a></li> <li> <ul class="sectlevel2"> <li><a href="#nsa-web">2.1. Web Application Security</a></li> <li><a href="#nsa-authentication">2.2. Authentication Services</a></li> <li><a href="#nsa-method-security">2.3. Method Security</a></li> <li><a href="#nsa-ldap">2.4. LDAP Namespace Options</a></li> </ul> </li> <li><a href="#appendix-dependencies">3. Spring Security Dependencies</a></li> <li> <ul class="sectlevel2"> <li><a href="#spring-security-core-2">3.1. spring-security-core</a></li> <li><a href="#spring-security-remoting-2">3.2. spring-security-remoting</a></li> <li><a href="#spring-security-web-2">3.3. spring-security-web</a></li> <li><a href="#spring-security-ldap-2">3.4. spring-security-ldap</a></li> <li><a href="#spring-security-config-2">3.5. spring-security-config</a></li> <li><a href="#spring-security-acl-2">3.6. spring-security-acl</a></li> <li><a href="#spring-security-cas-2">3.7. spring-security-cas</a></li> <li><a href="#spring-security-openid-2">3.8. spring-security-openid</a></li> <li><a href="#spring-security-taglibs">3.9. spring-security-taglibs</a></li> </ul> </li> </ul> </li> </ul> </div> </div> <div id="content"> <div id="preamble"> <div class="sectionbody"> <div class="paragraph"> <p>Spring Security is a powerful and highly customizable authentication and access-control framework. It is the de-facto standard for securing Spring-based applications.</p> </div> </div> </div> <h1 id="preface" class="sect0"><a class="anchor" href="#preface"></a>Preface</h1> <div class="paragraph"> <p>Spring Security provides a comprehensive security solution for Java EE-based enterprise software applications. As you will discover as you venture through this reference guide, we have tried to provide you a useful and highly configurable security system.</p> </div> <div class="paragraph"> <p>Security is an ever-moving target, and it’s important to pursue a comprehensive, system-wide approach. In security circles we encourage you to adopt "layers of security", so that each layer tries to be as secure as possible in its own right, with successive layers providing additional security. The "tighter" the security of each layer, the more robust and safe your application will be. At the bottom level you’ll need to deal with issues such as transport security and system identification, in order to mitigate man-in-the-middle attacks. Next you’ll generally utilise firewalls, perhaps with VPNs or IP security to ensure only authorised systems can attempt to connect. In corporate environments you may deploy a DMZ to separate public-facing servers from backend database and application servers. Your operating system will also play a critical part, addressing issues such as running processes as non-privileged users and maximising file system security. An operating system will usually also be configured with its own firewall. Hopefully somewhere along the way you’ll be trying to prevent denial of service and brute force attacks against the system. An intrusion detection system will also be especially useful for monitoring and responding to attacks, with such systems able to take protective action such as blocking offending TCP/IP addresses in real-time. Moving to the higher layers, your Java Virtual Machine will hopefully be configured to minimize the permissions granted to different Java types, and then your application will add its own problem domain-specific security configuration. Spring Security makes this latter area - application security - much easier.</p> </div> <div class="paragraph"> <p>Of course, you will need to properly address all security layers mentioned above, together with managerial factors that encompass every layer. A non-exhaustive list of such managerial factors would include security bulletin monitoring, patching, personnel vetting, audits, change control, engineering management systems, data backup, disaster recovery, performance benchmarking, load monitoring, centralised logging, incident response procedures etc.</p> </div> <div class="paragraph"> <p>With Spring Security being focused on helping you with the enterprise application security layer, you will find that there are as many different requirements as there are business problem domains. A banking application has different needs from an ecommerce application. An ecommerce application has different needs from a corporate sales force automation tool. These custom requirements make application security interesting, challenging and rewarding.</p> </div> <div class="paragraph"> <p>Please read <a href="#getting-started">Getting Started</a>, in its entirety to begin with. This will introduce you to the framework and the namespace-based configuration system with which you can get up and running quite quickly. To get more of an understanding of how Spring Security works, and some of the classes you might need to use, you should then read <a href="#overall-architecture">Architecture and Implementation</a>. The remaining parts of this guide are structured in a more traditional reference style, designed to be read on an as-required basis. We’d also recommend that you read up as much as possible on application security issues in general. Spring Security is not a panacea which will solve all security issues. It is important that the application is designed with security in mind from the start. Attempting to retrofit it is not a good idea. In particular, if you are building a web application, you should be aware of the many potential vulnerabilities such as cross-site scripting, request-forgery and session-hijacking which you should be taking into account from the start. The OWASP web site (<a href="http://www.owasp.org/">http://www.owasp.org/</a>) maintains a top ten list of web application vulnerabilities as well as a lot of useful reference information.</p> </div> <div class="paragraph"> <p>We hope that you find this reference guide useful, and we welcome your feedback and <a href="#jira">suggestions</a>.</p> </div> <div class="paragraph"> <p>Finally, welcome to the Spring Security <a href="#community">community</a>.</p> </div> <h1 id="getting-started" class="sect0"><a class="anchor" href="#getting-started"></a>Getting Started</h1> <div class="paragraph"> <p>The later parts of this guide provide an in-depth discussion of the framework architecture and implementation classes, which you need to understand if you want to do any serious customization. In this part, we’ll introduce Spring Security 3.0, give a brief overview of the project’s history and take a slightly gentler look at how to get started using the framework. In particular, we’ll look at namespace configuration which provides a much simpler way of securing your application compared to the traditional Spring bean approach where you have to wire up all the implementation classes individually.</p> </div> <div class="paragraph"> <p>We’ll also take a look at the sample applications that are available. It’s worth trying to run these and experimenting with them a bit even before you read the later sections - you can dip back into them as your understanding of the framework increases. Please also check out the <a href="http://static.springsource.org/spring-security/site/index.html">project website</a> as it has useful information on building the project, plus links to articles, videos and tutorials.</p> </div> <div class="sect1"> <h2 id="introduction"><a class="anchor" href="#introduction"></a>1. Introduction</h2> <div class="sectionbody"> <div class="sect2"> <h3 id="what-is-acegi-security"><a class="anchor" href="#what-is-acegi-security"></a>1.1. What is Spring Security?</h3> <div class="paragraph"> <p>Spring Security provides comprehensive security services for Java EE-based enterprise software applications. There is a particular emphasis on supporting projects built using The Spring Framework, which is the leading Java EE solution for enterprise software development. If you’re not using Spring for developing enterprise applications, we warmly encourage you to take a closer look at it. Some familiarity with Spring - and in particular dependency injection principles - will help you get up to speed with Spring Security more easily.</p> </div> <div class="paragraph"> <p>People use Spring Security for many reasons, but most are drawn to the project after finding the security features of Java EE’s Servlet Specification or EJB Specification lack the depth required for typical enterprise application scenarios. Whilst mentioning these standards, it’s important to recognise that they are not portable at a WAR or EAR level. Therefore, if you switch server environments, it is typically a lot of work to reconfigure your application’s security in the new target environment. Using Spring Security overcomes these problems, and also brings you dozens of other useful, customisable security features.</p> </div> <div class="paragraph"> <p>As you probably know two major areas of application security are "authentication" and "authorization" (or "access-control"). These are the two main areas that Spring Security targets. "Authentication" is the process of establishing a principal is who they claim to be (a "principal" generally means a user, device or some other system which can perform an action in your application)."Authorization" refers to the process of deciding whether a principal is allowed to perform an action within your application. To arrive at the point where an authorization decision is needed, the identity of the principal has already been established by the authentication process. These concepts are common, and not at all specific to Spring Security.</p> </div> <div class="paragraph"> <p>At an authentication level, Spring Security supports a wide range of authentication models. Most of these authentication models are either provided by third parties, or are developed by relevant standards bodies such as the Internet Engineering Task Force. In addition, Spring Security provides its own set of authentication features. Specifically, Spring Security currently supports authentication integration with all of these technologies:</p> </div> <div class="ulist"> <ul> <li> <p>HTTP BASIC authentication headers (an IETF RFC-based standard)</p> </li> <li> <p>HTTP Digest authentication headers (an IETF RFC-based standard)</p> </li> <li> <p>HTTP X.509 client certificate exchange (an IETF RFC-based standard)</p> </li> <li> <p>LDAP (a very common approach to cross-platform authentication needs, especially in large environments)</p> </li> <li> <p>Form-based authentication (for simple user interface needs)</p> </li> <li> <p>OpenID authentication</p> </li> <li> <p>Authentication based on pre-established request headers (such as Computer Associates Siteminder)</p> </li> <li> <p>JA-SIG Central Authentication Service (otherwise known as CAS, which is a popular open source single sign-on system)</p> </li> <li> <p>Transparent authentication context propagation for Remote Method Invocation (RMI) and HttpInvoker (a Spring remoting protocol)</p> </li> <li> <p>Automatic "remember-me" authentication (so you can tick a box to avoid re-authentication for a predetermined period of time)</p> </li> <li> <p>Anonymous authentication (allowing every unauthenticated call to automatically assume a particular security identity)</p> </li> <li> <p>Run-as authentication (which is useful if one call should proceed with a different security identity)</p> </li> <li> <p>Java Authentication and Authorization Service (JAAS)</p> </li> <li> <p>JEE container autentication (so you can still use Container Managed Authentication if desired)</p> </li> <li> <p>Kerberos</p> </li> <li> <p>Java Open Source Single Sign On (JOSSO) *</p> </li> <li> <p>OpenNMS Network Management Platform *</p> </li> <li> <p>AppFuse *</p> </li> <li> <p>AndroMDA *</p> </li> <li> <p>Mule ESB *</p> </li> <li> <p>Direct Web Request (DWR) *</p> </li> <li> <p>Grails *</p> </li> <li> <p>Tapestry *</p> </li> <li> <p>JTrac *</p> </li> <li> <p>Jasypt *</p> </li> <li> <p>Roller *</p> </li> <li> <p>Elastic Path *</p> </li> <li> <p>Atlassian Crowd *</p> </li> <li> <p>Your own authentication systems (see below)</p> </li> </ul> </div> <div class="paragraph"> <p>(* Denotes provided by a third party</p> </div> <div class="paragraph"> <p>Many independent software vendors (ISVs) adopt Spring Security because of this significant choice of flexible authentication models. Doing so allows them to quickly integrate their solutions with whatever their end clients need, without undertaking a lot of engineering or requiring the client to change their environment. If none of the above authentication mechanisms suit your needs, Spring Security is an open platform and it is quite simple to write your own authentication mechanism. Many corporate users of Spring Security need to integrate with "legacy" systems that don’t follow any particular security standards, and Spring Security is happy to "play nicely" with such systems.</p> </div> <div class="paragraph"> <p>Irrespective of the authentication mechanism, Spring Security provides a deep set of authorization capabilities. There are three main areas of interest - authorizing web requests, authorizing whether methods can be invoked, and authorizing access to individual domain object instances. To help you understand the differences, consider the authorization capabilities found in the Servlet Specification web pattern security, EJB Container Managed Security and file system security respectively. Spring Security provides deep capabilities in all of these important areas, which we’ll explore later in this reference guide.</p> </div> </div> <div class="sect2"> <h3 id="history"><a class="anchor" href="#history"></a>1.2. History</h3> <div class="paragraph"> <p>Spring Security began in late 2003 as "The Acegi Security System for Spring". A question was posed on the Spring Developers' mailing list asking whether there had been any consideration given to a Spring-based security implementation. At the time the Spring community was relatively small (especially compared with the size today!), and indeed Spring itself had only existed as a SourceForge project from early 2003. The response to the question was that it was a worthwhile area, although a lack of time currently prevented its exploration.</p> </div> <div class="paragraph"> <p>With that in mind, a simple security implementation was built and not released. A few weeks later another member of the Spring community inquired about security, and at the time this code was offered to them. Several other requests followed, and by January 2004 around twenty people were using the code. These pioneering users were joined by others who suggested a SourceForge project was in order, which was duly established in March 2004.</p> </div> <div class="paragraph"> <p>In those early days, the project didn’t have any of its own authentication modules. Container Managed Security was relied upon for the authentication process, with Acegi Security instead focusing on authorization. This was suitable at first, but as more and more users requested additional container support, the fundamental limitation of container-specific authentication realm interfaces became clear. There was also a related issue of adding new JARs to the container’s classpath, which was a common source of end user confusion and misconfiguration.</p> </div> <div class="paragraph"> <p>Acegi Security-specific authentication services were subsequently introduced. Around a year later, Acegi Security became an official Spring Framework subproject. The 1.0.0 final release was published in May 2006 - after more than two and a half years of active use in numerous production software projects and many hundreds of improvements and community contributions.</p> </div> <div class="paragraph"> <p>Acegi Security became an official Spring Portfolio project towards the end of 2007 and was rebranded as "Spring Security".</p> </div> <div class="paragraph"> <p>Today Spring Security enjoys a strong and active open source community. There are thousands of messages about Spring Security on the support forums. There is an active core of developers who work on the code itself and an active community which also regularly share patches and support their peers.</p> </div> </div> <div class="sect2"> <h3 id="release-numbering"><a class="anchor" href="#release-numbering"></a>1.3. Release Numbering</h3> <div class="paragraph"> <p>It is useful to understand how Spring Security release numbers work, as it will help you identify the effort (or lack thereof) involved in migrating to future releases of the project. Each release uses a standard triplet of integers: MAJOR.MINOR.PATCH. The intent is that MAJOR versions are incompatible, large-scale upgrades of the API. MINOR versions should largely retain source and binary compatibility with older minor versions, thought there may be some design changes and incompatible updates. PATCH level should be perfectly compatible, forwards and backwards, with the possible exception of changes which are to fix bugs and defects.</p> </div> <div class="paragraph"> <p>The extent to which you are affected by changes will depend on how tightly integrated your code is. If you are doing a lot of customization you are more likely to be affected than if you are using a simple namespace configuration.</p> </div> <div class="paragraph"> <p>You should always test your application thoroughly before rolling out a new version.</p> </div> </div> <div class="sect2"> <h3 id="get-spring-security"><a class="anchor" href="#get-spring-security"></a>1.4. Getting Spring Security</h3> <div class="paragraph"> <p>You can get hold of Spring Security in several ways. You can download a packaged distribution from the main <a href="http://spring.io/spring-security">Spring Security</a> page, download individual jars from the Maven Central repository (or a SpringSource Maven repository for snapshot and milestone releases) or, alternatively, you can build the project from source yourself.</p> </div> <div class="sect3"> <h4 id="maven"><a class="anchor" href="#maven"></a>1.4.1. Usage with Maven</h4> <div class="paragraph"> <p>A minimal Spring Security Maven set of dependencies typically looks like the following:</p> </div> <div class="listingblock"> <div class="title">pom.xml</div> <div class="content"> <pre style="" class="prettyprint xml language-xml prettyprinted"><code><span class="tag"><dependencies></span><span class="pln"> </span><span class="com"><!-- ... other dependency elements ... --></span><span class="pln"> </span><span class="tag"><dependency></span><span class="pln"> </span><span class="tag"><groupId></span><span class="pln">org.springframework.security</span><span class="tag"></groupId></span><span class="pln"> </span><span class="tag"><artifactId></span><span class="pln">spring-security-web</span><span class="tag"></artifactId></span><span class="pln"> </span><span class="tag"><version></span><span class="pln">3.2.6.RELEASE</span><span class="tag"></version></span><span class="pln"> </span><span class="tag"></dependency></span><span class="pln"> </span><span class="tag"><dependency></span><span class="pln"> </span><span class="tag"><groupId></span><span class="pln">org.springframework.security</span><span class="tag"></groupId></span><span class="pln"> </span><span class="tag"><artifactId></span><span class="pln">spring-security-config</span><span class="tag"></artifactId></span><span class="pln"> </span><span class="tag"><version></span><span class="pln">3.2.6.RELEASE</span><span class="tag"></version></span><span class="pln"> </span><span class="tag"></dependency></span><span class="pln"> </span><span class="tag"></dependencies></span></code></pre> </div> </div> <div class="paragraph"> <p>If you are using additional features like LDAP, OpenID, etc. you will need to also include the appropriate <a href="#modules">Project Modules</a>.</p> </div> <div class="sect4"> <h5 id="maven-repositories"><a class="anchor" href="#maven-repositories"></a>Maven Repositories</h5> <div class="paragraph"> <p>All GA releases (i.e. versions ending in .RELEASE) are deployed to Maven Central, so no additional Maven repositories need to be declared in your pom.</p> </div> <div class="paragraph"> <p>If you are using a SNAPSHOT version, you will need to ensure you have the Spring Snapshot repository defined as shown below:</p> </div> <div class="listingblock"> <div class="title">pom.xml</div> <div class="content"> <pre style="" class="prettyprint xml language-xml prettyprinted"><code><span class="tag"><repositories></span><span class="pln"> </span><span class="com"><!-- ... possibly other repository elements ... --></span><span class="pln"> </span><span class="tag"><repository></span><span class="pln"> </span><span class="tag"><id></span><span class="pln">spring-snapshot</span><span class="tag"></id></span><span class="pln"> </span><span class="tag"><name></span><span class="pln">Spring Snapshot Repository</span><span class="tag"></name></span><span class="pln"> </span><span class="tag"><url></span><span class="pln">http://repo.springsource.org/snapshot</span><span class="tag"></url></span><span class="pln"> </span><span class="tag"></repository></span><span class="pln"> </span><span class="tag"></repositories></span></code></pre> </div> </div> <div class="paragraph"> <p>If you are using a milestone or release candidate version, you will need to ensure you have the Spring Milestone repository defined as shown below:</p> </div> <div class="listingblock"> <div class="title">pom.xml</div> <div class="content"> <pre style="" class="prettyprint xml language-xml prettyprinted"><code><span class="tag"><repositories></span><span class="pln"> </span><span class="com"><!-- ... possibly other repository elements ... --></span><span class="pln"> </span><span class="tag"><repository></span><span class="pln"> </span><span class="tag"><id></span><span class="pln">spring-milestone</span><span class="tag"></id></span><span class="pln"> </span><span class="tag"><name></span><span class="pln">Spring Milestone Repository</span><span class="tag"></name></span><span class="pln"> </span><span class="tag"><url></span><span class="pln">http://repo.springsource.org/milestone</span><span class="tag"></url></span><span class="pln"> </span><span class="tag"></repository></span><span class="pln"> </span><span class="tag"></repositories></span></code></pre> </div> </div> </div> <div class="sect4"> <h5 id="maven-bom"><a class="anchor" href="#maven-bom"></a>Using Spring 4 and Maven</h5> <div class="paragraph"> <p>Spring Security builds against Spring Framework 3.2.8.RELEASE, but is also tested against Spring Framework 4.0.2.RELEASE. This means you can use Spring Security 3.2.6.RELEASE with Spring Framework 4.0.2.RELEASE. The problem that many users will have is that Spring Security’s transitive dependencies resolve Spring Framework 3.2.8.RELEASE causing all sorts of strange classpath problems.</p> </div> <div class="paragraph"> <p>One (tedious) way to circumvent this issue would be to include all the Spring Framework modules in a <a href="http://maven.apache.org/guides/introduction/introduction-to-dependency-mechanism.html#Dependency_Management"><dependencyManagement></a> section of your pom. An alternative approach is to include the <code>spring-framework-bom</code> within your <code><dependencyManagement></code> section of your <code>pom.xml</code> as shown below:</p> </div> <div class="listingblock"> <div class="title">pom.xml</div> <div class="content"> <pre style="" class="prettyprint xml language-xml prettyprinted"><code><span class="tag"><dependencyManagement></span><span class="pln"> </span><span class="tag"><dependencies></span><span class="pln"> </span><span class="tag"><dependency></span><span class="pln"> </span><span class="tag"><groupId></span><span class="pln">org.springframework</span><span class="tag"></groupId></span><span class="pln"> </span><span class="tag"><artifactId></span><span class="pln">spring-framework-bom</span><span class="tag"></artifactId></span><span class="pln"> </span><span class="tag"><version></span><span class="pln">4.0.2.RELEASE</span><span class="tag"></version></span><span class="pln"> </span><span class="tag"><type></span><span class="pln">pom</span><span class="tag"></type></span><span class="pln"> </span><span class="tag"><scope></span><span class="pln">import</span><span class="tag"></scope></span><span class="pln"> </span><span class="tag"></dependency></span><span class="pln"> </span><span class="tag"></dependencies></span><span class="pln"> </span><span class="tag"></dependencyManagement></span></code></pre> </div> </div> <div class="paragraph"> <p>This will ensure that all the transitive dependencies of Spring Security use the Spring 4.0.2.RELEASE modules.</p> </div> <div class="admonitionblock note"> <table> <tbody><tr> <td class="icon"> <i class="icon-note" title="Note"></i> </td> <td class="content"> This approach uses Maven’s "bill of materials" (BOM) concept and is only available in Maven 2.0.9+. For additional details about how dependencies are resolved refer to <a href="http://maven.apache.org/guides/introduction/introduction-to-dependency-mechanism.html">Maven’s Introduction to the Dependency Mechanism documentation</a>. </td> </tr> </tbody></table> </div> </div> </div> <div class="sect3"> <h4 id="gradle"><a class="anchor" href="#gradle"></a>1.4.2. Gradle</h4> <div class="paragraph"> <p>A minimal Spring Security Gradle set of dependencies typically looks like the following:</p> </div> <div class="listingblock"> <div class="title">build.gradle</div> <div class="content"> <pre style="" class="prettyprint groovy language-groovy prettyprinted"><code><span class="pln">dependencies </span><span class="pun">{</span><span class="pln"> compile </span><span class="str">'org.springframework.security:spring-security-web:3.2.6.RELEASE'</span><span class="pln"> compile </span><span class="str">'org.springframework.security:spring-security-config:3.2.6.RELEASE'</span><span class="pln"> </span><span class="pun">}</span></code></pre> </div> </div> <div class="paragraph"> <p>If you are using additional features like LDAP, OpenID, etc. you will need to also include the appropriate <a href="#modules">Project Modules</a>.</p> </div> <div class="sect4"> <h5 id="gradle-repositories"><a class="anchor" href="#gradle-repositories"></a>Gradle Repositories</h5> <div class="paragraph"> <p>All GA releases (i.e. versions ending in .RELEASE) are deployed to Maven Central, so using the mavenCentral() repository is sufficient for GA releases.</p> </div> <div class="listingblock"> <div class="title">build.gradle</div> <div class="content"> <pre style="" class="prettyprint groovy language-groovy prettyprinted"><code><span class="pln">repositories </span><span class="pun">{</span><span class="pln"> mavenCentral</span><span class="pun">()</span><span class="pln"> </span><span class="pun">}</span></code></pre> </div> </div> <div class="paragraph"> <p>If you are using a SNAPSHOT version, you will need to ensure you have the Spring Snapshot repository defined as shown below:</p> </div> <div class="listingblock"> <div class="title">build.gradle</div> <div class="content"> <pre style="" class="prettyprint groovy language-groovy prettyprinted"><code><span class="pln">repositories </span><span class="pun">{</span><span class="pln"> maven </span><span class="pun">{</span><span class="pln"> url </span><span class="str">'https://repo.spring.io/snapshot'</span><span class="pln"> </span><span class="pun">}</span><span class="pln"> </span><span class="pun">}</span></code></pre> </div> </div> <div class="paragraph"> <p>If you are using a milestone or release candidate version, you will need to ensure you have the Spring Milestone repository defined as shown below:</p> </div> <div class="listingblock"> <div class="title">build.gradle</div> <div class="content"> <pre style="" class="prettyprint groovy language-groovy prettyprinted"><code><span class="pln">repositories </span><span class="pun">{</span><span class="pln"> maven </span><span class="pun">{</span><span class="pln"> url </span><span class="str">'https://repo.spring.io/milestone'</span><span class="pln"> </span><span class="pun">}</span><span class="pln"> </span><span class="pun">}</span></code></pre> </div> </div> </div> <div class="sect4"> <h5 id="gradle-resolutionStrategy"><a class="anchor" href="#gradle-resolutionStrategy"></a>Using Spring 4 and Gradle</h5> <div class="paragraph"> <p>By default Gradle will use the newest version when resolving transitive versions. This means that often times no additional work is necessary when running Spring Security 3.2.6.RELEASE with Spring Framework 4.0.2.RELEASE. However, at times there can be issues that come up so it is best to mitigate this using <a href="http://www.gradle.org/docs/current/dsl/org.gradle.api.artifacts.ResolutionStrategy.html">Gradle’s ResolutionStrategy</a> as shown below:</p> </div> <div class="listingblock"> <div class="title">build.gradle</div> <div class="content"> <pre style="" class="prettyprint groovy language-groovy prettyprinted"><code><span class="pln">configurations</span><span class="pun">.</span><span class="pln">all </span><span class="pun">{</span><span class="pln"> resolutionStrategy</span><span class="pun">.</span><span class="pln">eachDependency </span><span class="pun">{</span><span class="pln"> </span><span class="typ">DependencyResolveDetails</span><span class="pln"> details </span><span class="pun">-></span><span class="pln"> </span><span class="kwd">if</span><span class="pln"> </span><span class="pun">(</span><span class="pln">details</span><span class="pun">.</span><span class="pln">requested</span><span class="pun">.</span><span class="kwd">group</span><span class="pln"> </span><span class="pun">==</span><span class="pln"> </span><span class="str">'org.springframework'</span><span class="pun">)</span><span class="pln"> </span><span class="pun">{</span><span class="pln"> details</span><span class="pun">.</span><span class="pln">useVersion </span><span class="str">'4.0.2.RELEASE'</span><span class="pln"> </span><span class="pun">}</span><span class="pln"> </span><span class="pun">}</span><span class="pln"> </span><span class="pun">}</span></code></pre> </div> </div> <div class="paragraph"> <p>This will ensure that all the transitive dependencies of Spring Security use the Spring 4.0.2.RELEASE modules.</p> </div> <div class="admonitionblock note"> <table> <tbody><tr> <td class="icon"> <i class="icon-note" title="Note"></i> </td> <td class="content"> This example uses Gradle 1.9, but may need modifications to work in future versions of Gradle since this is an incubating feature within Gradle. </td> </tr> </tbody></table> </div> </div> </div> <div class="sect3"> <h4 id="modules"><a class="anchor" href="#modules"></a>1.4.3. Project Modules</h4> <div class="paragraph"> <p>In Spring Security 3.0, the codebase has been sub-divided into separate jars which more clearly separate different functionaltiy areas and third-party dependencies. If you are using Maven to build your project, then these are the modules you will add to your <code>pom.xml</code>. Even if you’re not using Maven, we’d recommend that you consult the <code>pom.xml</code> files to get an idea of third-party dependencies and versions. Alternatively, a good idea is to examine the libraries that are included in the sample applications.</p> </div> <div class="sect4"> <h5 id="spring-security-core"><a class="anchor" href="#spring-security-core"></a>Core - spring-security-core.jar</h5> <div class="paragraph"> <p>Contains core authentication and access-contol classes and interfaces, remoting support and basic provisioning APIs. Required by any application which uses Spring Security. Supports standalone applications, remote clients, method (service layer) security and JDBC user provisioning. Contains the top-level packages:</p> </div> <div class="ulist"> <ul> <li> <p><code>org.springframework.security.core</code></p> </li> <li> <p><code>org.springframework.security.access</code></p> </li> <li> <p><code>org.springframework.security.authentication</code></p> </li> <li> <p><code>org.springframework.security.provisioning</code></p> </li> </ul> </div> </div> <div class="sect4"> <h5 id="spring-security-remoting"><a class="anchor" href="#spring-security-remoting"></a>Remoting - spring-security-remoting.jar</h5> <div class="paragraph"> <p>Provides intergration with Spring Remoting. You don’t need this unless you are writing a remote client which uses Spring Remoting. The main package is <code>org.springframework.security.remoting</code>.</p> </div> </div> <div class="sect4"> <h5 id="spring-security-web"><a class="anchor" href="#spring-security-web"></a>Web - spring-security-web.jar</h5> <div class="paragraph"> <p>Contains filters and related web-security infrastructure code. Anything with a servlet API dependency. You’ll need it if you require Spring Security web authentication services and URL-based access-control. The main package is <code>org.springframework.security.web</code>.</p> </div> </div> <div class="sect4"> <h5 id="spring-security-config"><a class="anchor" href="#spring-security-config"></a>Config - spring-security-config.jar</h5> <div class="paragraph"> <p>Contains the security namespace parsing code. You need it if you are using the Spring Security XML namespace for configuration. The main package is <code>org.springframework.security.config</code>. None of the classes are intended for direct use in an application.</p> </div> </div> <div class="sect4"> <h5 id="spring-security-ldap"><a class="anchor" href="#spring-security-ldap"></a>LDAP - spring-security-ldap.jar</h5> <div class="paragraph"> <p>LDAP authentication and provisioning code. Required if you need to use LDAP authentication or manage LDAP user entries. The top-level package is <code>org.springframework.security.ldap</code>.</p> </div> </div> <div class="sect4"> <h5 id="spring-security-acl"><a class="anchor" href="#spring-security-acl"></a>ACL - spring-security-acl.jar</h5> <div class="paragraph"> <p>Specialized domain object ACL implementation. Used to apply security to specific domain object instances within your application. The top-level package is <code>org.springframework.security.acls</code>.</p> </div> </div> <div class="sect4"> <h5 id="spring-security-cas"><a class="anchor" href="#spring-security-cas"></a>CAS - spring-security-cas.jar</h5> <div class="paragraph"> <p>Spring Security’s CAS client integration. If you want to use Spring Security web authentication with a CAS single sign-on server. The top-level package is <code>org.springframework.security.cas</code>.</p> </div> </div> <div class="sect4"> <h5 id="spring-security-openid"><a class="anchor" href="#spring-security-openid"></a>OpenID - spring-security-openid.jar</h5> <div class="paragraph"> <p>OpenID web authentication support. Used to authenticate users against an external OpenID server. <code>org.springframework.security.openid</code>. Requires OpenID4Java.</p> </div> </div> </div> <div class="sect3"> <h4 id="get-source"><a class="anchor" href="#get-source"></a>1.4.4. Checking out the Source</h4> <div class="paragraph"> <p>Since Spring Security is an Open Source project, we’d strongly encourage you to check out the source code using git. This will give you full access to all the sample applications and you can build the most up to date version of the project easily. Having the source for a project is also a huge help in debugging. Exception stack traces are no longer obscure black-box issues but you can get straight to the line that’s causing the problem and work out what’s happening. The source is the ultimate documentation for a project and often the simplest place to find out how something actually works.</p> </div> <div class="paragraph"> <p>To obtain the source for the project, use the following git command:</p> </div> <div class="listingblock"> <div class="content"> <pre style="" class="prettyprint txt language-txt prettyprinted"><code><span class="pln">git clone https</span><span class="pun">:</span><span class="com">//github.com/spring-projects/spring-security.git</span></code></pre> </div> </div> <div class="paragraph"> <p>This will give you access to the entire project history (including all releases and branches) on your local machine.</p> </div> </div> </div> </div> </div> <div class="sect1"> <h2 id="new"><a class="anchor" href="#new"></a>2. What’s new in Spring Security 3.2</h2> <div class="sectionbody"> <div class="paragraph"> <p>There are <a href="https://jira.springsource.org/issues/?jql=project%20%3D%20SEC%20AND%20fixVersion%20in%20%28%223.2.0.RC2%22%2C%20%223.2.0%22%2C%20%223.2.0.RC1%22%2C%20%223.2.0.M2%22%2C%20%223.2.0.M1%22%29%20ORDER%20BY%20priority%20DESC%2C%20issuetype%20ASC%2C%20key%20DESC">150+ tickets resolved</a> with the Spring Security 3.2 release. Below are the highlights of the new features found in Spring Security 3.2.</p> </div> <div class="ulist"> <ul> <li> <p><a href="#jc">Java Configuration Support</a></p> </li> <li> <p><a href="#csrf">Cross Site Request Forgery (CSRF) Protection</a></p> </li> <li> <p><a href="#headers-frame-options">Click Jacking Protection</a></p> </li> <li> <p><a href="#headers">Security HTTP Response Headers</a></p> </li> <li> <p>Optional <a href="#mvc">Spring MVC</a> Integration</p> <div class="ulist"> <ul> <li> <p>Automatic Resolving <code>Authentication.getPrincipal()</code> with <a href="#mvc-authentication-principal">@AuthenticationPrincipal</a></p> </li> <li> <p>Automatic <a href="#mvc-async">Spring MVC Async integration</a></p> </li> <li> <p><a href="#mvc-csrf">Spring MVC and CSRF Integration</a></p> </li> </ul> </div> </li> <li> <p><a href="#concurrency">Concurrency Support</a></p> </li> <li> <p><a href="#servletapi-3">Servlet 3+ Integration</a> and <a href="#servletapi-31">Servlet 3.1+ Integration</a></p> </li> <li> <p>Extended ability to <a href="#el-pre-post-annotations-arguments">resolve method parameter names</a> to assist with Method based security</p> <div class="ulist"> <ul> <li> <p>Support for standard JDK 8 reflection</p> </li> <li> <p>Support for annotation based resolution</p> </li> <li> <p>Enables resolving parameter names on interfaces</p> </li> <li> <p>Automatic integration with Spring Data’s <code>@Param</code> tag</p> </li> </ul> </div> </li> <li> <p>Additional <code>RequestMatcher</code> implementations</p> <div class="ulist"> <ul> <li> <p><a href="http://docs.spring.io/spring-security/site/docs/3.2.x-SNAPSHOT/apidocs/org/springframework/security/web/util/matcher/MediaTypeRequestMatcher.html">MediaTypeRequestMatcher</a> - allows matching requests using content negotiation.</p> </li> <li> <p><code>OrRequestMatcher</code> - allows passing in multiple RequestMatcher instances into the contructor. If a single one returns true, then the result is true.</p> </li> <li> <p><code>AndRequestMatcher</code> - allows passing in multiple RequestMatcher instances into the contructor. If a all of them return true, then the result is true.</p> </li> <li> <p><code>NegatedRequestMatcher</code> - allows padding in a RequestMatcher instance. If the result of the delegate is false, the result is true.</p> </li> </ul> </div> </li> <li> <p><code>DebugFilter</code> now outputs request headers</p> </li> <li> <p>Documentation</p> <div class="ulist"> <ul> <li> <p>Started creating task focussed <a href="http://docs.spring.io/spring-security/site/docs/3.2.x-SNAPSHOT/guides/">guides</a></p> </li> <li> <p>10+ <a href="https://github.com/spring-projects/spring-security/tree/master/samples">Spring Security Samples</a> added</p> </li> <li> <p>Converted all documentation to <a href="http://asciidoctor.org/">Asciidoctor</a></p> </li> </ul> </div> </li> <li> <p>Sonar integration for the build</p> </li> </ul> </div> </div> </div> <div class="sect1"> <h2 id="jc"><a class="anchor" href="#jc"></a>3. Java Configuration</h2> <div class="sectionbody"> <div class="paragraph"> <p>General support for <a href="http://docs.spring.io/spring/docs/3.1.x/spring-framework-reference/html/beans.html#beans-java">Java Configuration</a> was added to Spring framework in Spring 3.1. Since Spring Security 3.2 there has been Spring Security Java Configuration support which enables users to easily configure Spring Security without the use of any XML.</p> </div> <div class="paragraph"> <p>If you are familiar with the <a href="#ns-config">Security Namespace Configuration</a> then you should find quite a few similarities between it and the Security Java Configuration support.</p> </div> <div class="admonitionblock note"> <table> <tbody><tr> <td class="icon"> <i class="icon-note" title="Note"></i> </td> <td class="content"> Spring Security provides <a href="https://github.com/spring-projects/spring-security/tree/master/samples">lots of sample applications</a> that end in <code>-jc</code> which demonstrate the use of Spring Security Java Configuration. </td> </tr> </tbody></table> </div> <div class="sect2"> <h3 id="hello-web-security-java-configuration"><a class="anchor" href="#hello-web-security-java-configuration"></a>3.1. Hello Web Security Java Configuration</h3> <div class="paragraph"> <p>The first step is to create our Spring Security Java Configuration. The configuration creates a Servlet Filter known as the <code>springSecurityFilterChain</code> which is responsible for all the security (protecting the application URLs, validating submitted username and passwords, redirecting to the log in form, etc) within your application. You can find the most basic example of a Spring Security Java configuration below:</p> </div> <div id="jc-hello-wsca" class="listingblock"> <div class="content"> <pre style="" class="prettyprint java language-java prettyprinted"><code><span class="kwd">import</span><span class="pln"> org</span><span class="pun">.</span><span class="pln">springframework</span><span class="pun">.</span><span class="pln">beans</span><span class="pun">.</span><span class="pln">factory</span><span class="pun">.</span><span class="pln">annotation</span><span class="pun">.</span><span class="typ">Autowired</span><span class="pun">;</span><span class="pln"> </span><span class="kwd">import</span><span class="pln"> org</span><span class="pun">.</span><span class="pln">springframework</span><span class="pun">.</span><span class="pln">context</span><span class="pun">.</span><span class="pln">annotation</span><span class="pun">.*;</span><span class="pln"> </span><span class="kwd">import</span><span class="pln"> org</span><span class="pun">.</span><span class="pln">springframework</span><span class="pun">.</span><span class="pln">security</span><span class="pun">.</span><span class="pln">config</span><span class="pun">.</span><span class="pln">annotation</span><span class="pun">.</span><span class="pln">authentication</span><span class="pun">.</span><span class="pln">builders</span><span class="pun">.*;</span><span class="pln"> </span><span class="kwd">import</span><span class="pln"> org</span><span class="pun">.</span><span class="pln">springframework</span><span class="pun">.</span><span class="pln">security</span><span class="pun">.</span><span class="pln">config</span><span class="pun">.</span><span class="pln">annotation</span><span class="pun">.</span><span class="pln">web</span><span class="pun">.</span><span class="pln">configuration</span><span class="pun">.*;</span><span class="pln"> </span><span class="lit">@Configuration</span><span class="pln"> </span><span class="lit">@EnableWebSecurity</span><span class="pln"> </span><span class="kwd">public</span><span class="pln"> </span><span class="kwd">class</span><span class="pln"> </span><span class="typ">SecurityConfig</span><span class="pln"> </span><span class="kwd">extends</span><span class="pln"> </span><span class="typ">WebSecurityConfigurerAdapter</span><span class="pln"> </span><span class="pun">{</span><span class="pln"> </span><span class="lit">@Autowired</span><span class="pln"> </span><span class="kwd">public</span><span class="pln"> </span><span class="kwd">void</span><span class="pln"> configureGlobal</span><span class="pun">(</span><span class="typ">AuthenticationManagerBuilder</span><span class="pln"> auth</span><span class="pun">)</span><span class="pln"> </span><span class="kwd">throws</span><span class="pln"> </span><span class="typ">Exception</span><span class="pln"> </span><span class="pun">{</span><span class="pln"> auth </span><span class="pun">.</span><span class="pln">inMemoryAuthentication</span><span class="pun">()</span><span class="pln"> </span><span class="pun">.</span><span class="pln">withUser</span><span class="pun">(</span><span class="str">"user"</span><span class="pun">).</span><span class="pln">password</span><span class="pun">(</span><span class="str">"password"</span><span class="pun">).</span><span class="pln">roles</span><span class="pun">(</span><span class="str">"USER"</span><span class="pun">);</span><span class="pln"> </span><span class="pun">}</span><span class="pln"> </span><span class="pun">}</span></code></pre> </div> </div> <div class="admonitionblock note"> <table> <tbody><tr> <td class="icon"> <i class="icon-note" title="Note"></i> </td> <td class="content"> The name of the configureGlobal method is not important. However, it is important to only configure AuthenticationManagerBuilder in a class annotated with either <code>@EnableWebSecurity</code>, <code>@EnableWebMvcSecurity</code>, <code>@EnableGlobalMethodSecurity</code>, or <code>@EnableGlobalAuthentication</code>. Doing otherwise has unpredictable results. </td> </tr> </tbody></table> </div> <div class="paragraph"> <p>There really isn’t much to this configuration, but it does a lot. You can find a summary of the features below:</p> </div> <div class="ulist"> <ul> <li> <p>Require authentication to every URL in your application</p> </li> <li> <p>Generate a login form for you</p> </li> <li> <p>Allow the user with the <strong>Username</strong> <em>user</em> and the <strong>Password</strong> <em>password</em> to authenticate with form based authentication</p> </li> <li> <p>Allow the user to logout</p> </li> <li> <p><a href="http://en.wikipedia.org/wiki/Cross-site_request_forgery">CSRF attack</a> prevention</p> </li> <li> <p><a href="http://en.wikipedia.org/wiki/Session_fixation">Session Fixation</a> protection</p> </li> <li> <p>Security Header integration</p> <div class="ulist"> <ul> <li> <p><a href="http://en.wikipedia.org/wiki/HTTP_Strict_Transport_Security">HTTP Strict Transport Security</a> for secure requests</p> </li> <li> <p><a href="http://msdn.microsoft.com/en-us/library/ie/gg622941%28v=vs.85%29.aspx">X-Content-Type-Options</a> integration</p> </li> <li> <p>Cache Control (can be overridden later by your application to allow caching of your static resources)</p> </li> <li> <p><a href="http://msdn.microsoft.com/en-us/library/dd565647%28v=vs.85%29.aspx">X-XSS-Protection</a> integration</p> </li> <li> <p>X-Frame-Options integration to help prevent <a href="http://en.wikipedia.org/wiki/Clickjacking">Clickjacking</a></p> </li> </ul> </div> </li> <li> <p>Integrate with the following Servlet API methods</p> <div class="ulist"> <ul> <li> <p><a href="http://docs.oracle.com/javaee/6/api/javax/servlet/http/HttpServletRequest.html#getRemoteUser%28%29">HttpServletRequest#getRemoteUser()</a></p> </li> <li> <p><a href="http://docs.oracle.com/javaee/6/api/javax/servlet/http/HttpServletRequest.html#getUserPrincipal%28%29">HttpServletRequest.html#getUserPrincipal()</a></p> </li> <li> <p><a href="http://docs.oracle.com/javaee/6/api/javax/servlet/http/HttpServletRequest.html#isUserInRole%28java.lang.String%29">HttpServletRequest.html#isUserInRole(java.lang.String)</a></p> </li> <li> <p><a href="http://docs.oracle.com/javaee/6/api/javax/servlet/http/HttpServletRequest.html#login%28java.lang.String,%20java.lang.String%29">HttpServletRequest.html#login(java.lang.String, java.lang.String)</a></p> </li> <li> <p><a href="http://docs.oracle.com/javaee/6/api/javax/servlet/http/HttpServletRequest.html#logout%28%29">HttpServletRequest.html#logout()</a></p> </li> </ul> </div> </li> </ul> </div> <div class="sect3"> <h4 id="abstractsecuritywebapplicationinitializer"><a class="anchor" href="#abstractsecuritywebapplicationinitializer"></a>3.1.1. AbstractSecurityWebApplicationInitializer</h4> <div class="paragraph"> <p>The next step is to register the <code>springSecurityFilterChain</code> with the war. This can be done in Java Configuration with <a href="http://docs.spring.io/spring/docs/3.2.x/spring-framework-reference/html/mvc.html#mvc-container-config">Spring’s WebApplicationInitializer support</a> in a Servlet 3.0+ environment. Not suprisingly, Spring Security provides a base class <code>AbstractSecurityWebApplicationInitializer</code> that will ensure the <code>springSecurityFilterChain</code> gets registered for you. The way in which we use <code>AbstractSecurityWebApplicationInitializer</code> differs depending on if we are already using Spring or if Spring Security is the only Spring component in our application.</p> </div> <div class="ulist"> <ul> <li> <p><a href="#abstractsecuritywebapplicationinitializer-without-existing-spring">AbstractSecurityWebApplicationInitializer without Existing Spring</a> - Use these instructions if you are not using Spring already</p> </li> <li> <p><a href="#abstractsecuritywebapplicationinitializer-with-spring-mvc">AbstractSecurityWebApplicationInitializer with Spring MVC</a> - Use these instructions if you are already using Spring</p> </li> </ul> </div> </div> <div class="sect3"> <h4 id="abstractsecuritywebapplicationinitializer-without-existing-spring"><a class="anchor" href="#abstractsecuritywebapplicationinitializer-without-existing-spring"></a>3.1.2. AbstractSecurityWebApplicationInitializer without Existing Spring</h4> <div class="paragraph"> <p>If you are not using Spring or Spring MVC, you will need to pass in the <code>SecurityConfig</code> into the superclass to ensure the configuration is picked up. You can find an example below:</p> </div> <div class="listingblock"> <div class="content"> <pre style="" class="prettyprint java language-java prettyprinted"><code><span class="kwd">import</span><span class="pln"> org</span><span class="pun">.</span><span class="pln">springframework</span><span class="pun">.</span><span class="pln">security</span><span class="pun">.</span><span class="pln">web</span><span class="pun">.</span><span class="pln">context</span><span class="pun">.*;</span><span class="pln"> </span><span class="kwd">public</span><span class="pln"> </span><span class="kwd">class</span><span class="pln"> </span><span class="typ">SecurityWebApplicationInitializer</span><span class="pln"> </span><span class="kwd">extends</span><span class="pln"> </span><span class="typ">AbstractSecurityWebApplicationInitializer</span><span class="pln"> </span><span class="pun">{</span><span class="pln"> </span><span class="kwd">public</span><span class="pln"> </span><span class="typ">SecurityWebApplicationInitializer</span><span class="pun">()</span><span class="pln"> </span><span class="pun">{</span><span class="pln"> </span><span class="kwd">super</span><span class="pun">(</span><span class="typ">SecurityConfig</span><span class="pun">.</span><span class="kwd">class</span><span class="pun">);</span><span class="pln"> </span><span class="pun">}</span><span class="pln"> </span><span class="pun">}</span></code></pre> </div> </div> <div class="paragraph"> <p>The <code>SecurityWebApplicationInitializer</code> will do the following things:</p> </div> <div class="ulist"> <ul> <li> <p>Automatically register the springSecurityFilterChain Filter for every URL in your application</p> </li> <li> <p>Add a ContextLoaderListener that loads the <a href="#jc-hello-wsca">SecurityConfig</a>.</p> </li> </ul> </div> </div> <div class="sect3"> <h4 id="abstractsecuritywebapplicationinitializer-with-spring-mvc"><a class="anchor" href="#abstractsecuritywebapplicationinitializer-with-spring-mvc"></a>3.1.3. AbstractSecurityWebApplicationInitializer with Spring MVC</h4> <div class="paragraph"> <p>If we were using Spring elsewhere in our application we probably already had a <code>WebApplicationInitializer</code> that is loading our Spring Configuration. If we use the previous configuration we would get an error. Instead, we should register Spring Security with the existing <code>ApplicationContext</code>. For example, if we were using Spring MVC our <code>SecurityWebApplicationInitializer</code> would look something like the following:</p> </div> <div class="listingblock"> <div class="content"> <pre style="" class="prettyprint java language-java prettyprinted"><code><span class="kwd">import</span><span class="pln"> org</span><span class="pun">.</span><span class="pln">springframework</span><span class="pun">.</span><span class="pln">security</span><span class="pun">.</span><span class="pln">web</span><span class="pun">.</span><span class="pln">context</span><span class="pun">.*;</span><span class="pln"> </span><span class="kwd">public</span><span class="pln"> </span><span class="kwd">class</span><span class="pln"> </span><span class="typ">SecurityWebApplicationInitializer</span><span class="pln"> </span><span class="kwd">extends</span><span class="pln"> </span><span class="typ">AbstractSecurityWebApplicationInitializer</span><span class="pln"> </span><span class="pun">{</span><span class="pln"> </span><span class="pun">}</span></code></pre> </div> </div> <div class="paragraph"> <p>This would simply only register the springSecurityFilterChain Filter for every URL in your application. After that we would ensure that <code>SecurityConfig</code> was loaded in our existing ApplicationInitializer. For example, if we were using Spring MVC it would be added in the <code>getRootConfigClasses()</code></p> </div> <div id="message-web-application-inititializer-java" class="listingblock"> <div class="content"> <pre style="" class="prettyprint java language-java prettyprinted"><code><span class="kwd">public</span><span class="pln"> </span><span class="kwd">class</span><span class="pln"> </span><span class="typ">MvcWebApplicationInitializer</span><span class="pln"> </span><span class="kwd">extends</span><span class="pln"> </span><span class="typ">AbstractAnnotationConfigDispatcherServletInitializer</span><span class="pln"> </span><span class="pun">{</span><span class="pln"> </span><span class="lit">@Override</span><span class="pln"> </span><span class="kwd">protected</span><span class="pln"> </span><span class="typ">Class</span><span class="pun"><?>[]</span><span class="pln"> getRootConfigClasses</span><span class="pun">()</span><span class="pln"> </span><span class="pun">{</span><span class="pln"> </span><span class="kwd">return</span><span class="pln"> </span><span class="kwd">new</span><span class="pln"> </span><span class="typ">Class</span><span class="pun">[]</span><span class="pln"> </span><span class="pun">{</span><span class="pln"> </span><span class="typ">SecurityConfig</span><span class="pun">.</span><span class="kwd">class</span><span class="pln"> </span><span class="pun">};</span><span class="pln"> </span><span class="pun">}</span><span class="pln"> </span><span class="com">// ... other overrides ...</span><span class="pln"> </span><span class="pun">}</span></code></pre> </div> </div> </div> </div> <div class="sect2"> <h3 id="jc-httpsecurity"><a class="anchor" href="#jc-httpsecurity"></a>3.2. HttpSecurity</h3> <div class="paragraph"> <p>Thus far our <a href="#jc-hello-wsca">SecurityConfig</a> only contains information about how to authenticate our users. How does Spring Security know that we want to require all users to be authenticated? How does Spring Security know we want to support form based authentication? The reason for this is that the <code>WebSecurityConfigurerAdapter</code> provides a default configuration in the <code>configure(HttpSecurity http)</code> method that looks like:</p> </div> <div class="listingblock"> <div class="content"> <pre style="" class="prettyprint java language-java prettyprinted"><code><span class="kwd">protected</span><span class="pln"> </span><span class="kwd">void</span><span class="pln"> configure</span><span class="pun">(</span><span class="typ">HttpSecurity</span><span class="pln"> http</span><span class="pun">)</span><span class="pln"> </span><span class="kwd">throws</span><span class="pln"> </span><span class="typ">Exception</span><span class="pln"> </span><span class="pun">{</span><span class="pln"> http </span><span class="pun">.</span><span class="pln">authorizeRequests</span><span class="pun">()</span><span class="pln"> </span><span class="pun">.</span><span class="pln">anyRequest</span><span class="pun">().</span><span class="pln">authenticated</span><span class="pun">()</span><span class="pln"> </span><span class="pun">.</span><span class="pln">and</span><span class="pun">()</span><span class="pln"> </span><span class="pun">.</span><span class="pln">formLogin</span><span class="pun">()</span><span class="pln"> </span><span class="pun">.</span><span class="pln">and</span><span class="pun">()</span><span class="pln"> </span><span class="pun">.</span><span class="pln">httpBasic</span><span class="pun">();</span><span class="pln"> </span><span class="pun">}</span></code></pre> </div> </div> <div class="paragraph"> <p>The default configuration above:</p> </div> <div class="ulist"> <ul> <li> <p>Ensures that any request to our application requires the user to be authenticated</p> </li> <li> <p>Allows users to authenticate with form based login</p> </li> <li> <p>Allows users to authenticate with HTTP Basic authentication</p> </li> </ul> </div> <div class="paragraph"> <p>You will notice that this configuration is quite similar the XML Namespace configuration:</p> </div> <div class="listingblock"> <div class="content"> <pre style="" class="prettyprint xml language-xml prettyprinted"><code><span class="tag"><http</span><span class="pln"> </span><span class="atn">use-expressions</span><span class="pun">=</span><span class="atv">"true"</span><span class="tag">></span><span class="pln"> </span><span class="tag"><intercept-url</span><span class="pln"> </span><span class="atn">pattern</span><span class="pun">=</span><span class="atv">"/**"</span><span class="pln"> </span><span class="atn">access</span><span class="pun">=</span><span class="atv">"authenticated"</span><span class="tag">/></span><span class="pln"> </span><span class="tag"><form-login</span><span class="pln"> </span><span class="tag">/></span><span class="pln"> </span><span class="tag"><http-basic</span><span class="pln"> </span><span class="tag">/></span><span class="pln"> </span><span class="tag"></http></span></code></pre> </div> </div> <div class="paragraph"> <p>The Java Configuration equivalent of closing an XML tag is expressed using the <code>and()</code> method which allows us to continue configuring the parent. If you read the code it also makes sense. I want to configure authorized requests <em>and</em> configure form login <em>and</em> configure HTTP Basic authentication.</p> </div> <div class="paragraph"> <p>However, Java configuration has different defaults URLs and parameters. Keep this in mind when creating custom login pages. The result is that our URLs are more RESTful. Additionally, it is not quite so obvious we are using Spring Security which helps to prevent <a href="https://www.owasp.org/index.php/Information_Leak_%28information_disclosure%29">information leaks</a>. For example:</p> </div> <div class="ulist"> <ul> <li> <p>GET /login renders the login page instead of /spring_security_login</p> </li> <li> <p>POST /login authenticates the user instead of /j_spring_security_check</p> </li> <li> <p>The username parameter defaults to username instead of j_username</p> </li> <li> <p>The password parameter defaults to password instead of j_password</p> </li> </ul> </div> </div> <div class="sect2"> <h3 id="jc-form"><a class="anchor" href="#jc-form"></a>3.3. Java Configuration and Form Login</h3> <div class="paragraph"> <p>You might be wondering where the login form came from when you were prompted to log in, since we made no mention of any HTML files or JSPs. Since Spring Security’s default configuration does not explicitly set a URL for the login page, Spring Security generates one automatically, based on the features that are enabled and using standard values for the URL which processes the submitted login, the default target URL the user will be sent to after logging in and so on.</p> </div> <div class="paragraph"> <p>While the automatically generated log in page is convenient to get up and running quickly, most applications will want to provide their own log in page. To do so we can update our configuration as seen below:</p> </div> <div class="listingblock"> <div class="content"> <pre style="" class="prettyprint java language-java prettyprinted"><code><span class="kwd">protected</span><span class="pln"> </span><span class="kwd">void</span><span class="pln"> configure</span><span class="pun">(</span><span class="typ">HttpSecurity</span><span class="pln"> http</span><span class="pun">)</span><span class="pln"> </span><span class="kwd">throws</span><span class="pln"> </span><span class="typ">Exception</span><span class="pln"> </span><span class="pun">{</span><span class="pln"> http </span><span class="pun">.</span><span class="pln">authorizeRequests</span><span class="pun">()</span><span class="pln"> </span><span class="pun">.</span><span class="pln">anyRequest</span><span class="pun">().</span><span class="pln">authenticated</span><span class="pun">()</span><span class="pln"> </span><span class="pun">.</span><span class="pln">and</span><span class="pun">()</span><span class="pln"> </span><span class="pun">.</span><span class="pln">formLogin</span><span class="pun">()</span><span class="pln"> </span><span class="pun">.</span><span class="pln">loginPage</span><span class="pun">(</span><span class="str">"/login"</span><span class="pun">)</span><span class="pln"> </span><i class="conum" data-value="1"></i><b><span class="pun">(</span><span class="lit">1</span><span class="pun">)</span></b><span class="pln"> </span><span class="pun">.</span><span class="pln">permitAll</span><span class="pun">();</span><span class="pln"> </span><i class="conum" data-value="2"></i><b><span class="pun">(</span><span class="lit">2</span><span class="pun">)</span></b><span class="pln"> </span><span class="pun">}</span></code></pre> </div> </div> <div class="colist arabic"> <table> <tbody><tr> <td><i class="conum" data-value="1"></i><b>1</b></td> <td>The updated configuration specifies the location of the log in page.</td> </tr> <tr> <td><i class="conum" data-value="2"></i><b>2</b></td> <td>We must grant all users (i.e. unauthenticated users) access to our log in page. The <code>formLogin().permitAll()</code> method allows granting access to all users for all URLs associated with form based log in.</td> </tr> </tbody></table> </div> <div class="paragraph"> <p>An example log in page implemented with JSPs for our current configuration can be seen below:</p> </div> <div class="admonitionblock note"> <table> <tbody><tr> <td class="icon"> <i class="icon-note" title="Note"></i> </td> <td class="content"> The login page below represents our current configuration. We could easily update our configuration if some of the defaults do not meet our needs. </td> </tr> </tbody></table> </div> <div class="listingblock"> <div class="content"> <pre style="" class="prettyprint html language-html prettyprinted"><code><span class="tag"><c:url</span><span class="pln"> </span><span class="atn">value</span><span class="pun">=</span><span class="atv">"/login"</span><span class="pln"> </span><span class="atn">var</span><span class="pun">=</span><span class="atv">"loginUrl"</span><span class="tag">/></span><span class="pln"> </span><span class="tag"><form</span><span class="pln"> </span><span class="atn">action</span><span class="pun">=</span><span class="atv">"${loginUrl}"</span><span class="pln"> </span><span class="atn">method</span><span class="pun">=</span><span class="atv">"post"</span><span class="tag">></span><span class="pln"> </span><i class="conum" data-value="1"></i><b><span class="pln">(1)</span></b><span class="pln"> </span><span class="tag"><c:if</span><span class="pln"> </span><span class="atn">test</span><span class="pun">=</span><span class="atv">"${param.error != null}"</span><span class="tag">></span><span class="pln"> </span><i class="conum" data-value="2"></i><b><span class="pln">(2)</span></b><span class="pln"> </span><span class="tag"><p></span><span class="pln"> Invalid username and password. </span><span class="tag"></p></span><span class="pln"> </span><span class="tag"></c:if></span><span class="pln"> </span><span class="tag"><c:if</span><span class="pln"> </span><span class="atn">test</span><span class="pun">=</span><span class="atv">"${param.logout != null}"</span><span class="tag">></span><span class="pln"> </span><i class="conum" data-value="3"></i><b><span class="pln">(3)</span></b><span class="pln"> </span><span class="tag"><p></span><span class="pln"> You have been logged out. </span><span class="tag"></p></span><span class="pln"> </span><span class="tag"></c:if></span><span class="pln"> </span><span class="tag"><p></span><span class="pln"> </span><span class="tag"><label</span><span class="pln"> </span><span class="atn">for</span><span class="pun">=</span><span class="atv">"username"</span><span class="tag">></span><span class="pln">Username</span><span class="tag"></label></span><span class="pln"> </span><span class="tag"><input</span><span class="pln"> </span><span class="atn">type</span><span class="pun">=</span><span class="atv">"text"</span><span class="pln"> </span><span class="atn">id</span><span class="pun">=</span><span class="atv">"username"</span><span class="pln"> </span><span class="atn">name</span><span class="pun">=</span><span class="atv">"username"</span><span class="tag">/></span><span class="pln"> </span><i class="conum" data-value="4"></i><b><span class="pln">(4)</span></b><span class="pln"> </span><span class="tag"></p></span><span class="pln"> </span><span class="tag"><p></span><span class="pln"> </span><span class="tag"><label</span><span class="pln"> </span><span class="atn">for</span><span class="pun">=</span><span class="atv">"password"</span><span class="tag">></span><span class="pln">Password</span><span class="tag"></label></span><span class="pln"> </span><span class="tag"><input</span><span class="pln"> </span><span class="atn">type</span><span class="pun">=</span><span class="atv">"password"</span><span class="pln"> </span><span class="atn">id</span><span class="pun">=</span><span class="atv">"password"</span><span class="pln"> </span><span class="atn">name</span><span class="pun">=</span><span class="atv">"password"</span><span class="tag">/></span><span class="pln"> </span><i class="conum" data-value="5"></i><b><span class="pln">(5)</span></b><span class="pln"> </span><span class="tag"></p></span><span class="pln"> </span><span class="tag"><input</span><span class="pln"> </span><span class="atn">type</span><span class="pun">=</span><span class="atv">"hidden"</span><span class="pln"> </span><i class="conum" data-value="6"></i><b><span class="pln">(6)</span></b><span class="pln"> </span><span class="atn">name</span><span class="pun">=</span><span class="atv">"${_csrf.parameterName}"</span><span class="pln"> </span><span class="atn">value</span><span class="pun">=</span><span class="atv">"${_csrf.token}"</span><span class="tag">/></span><span class="pln"> </span><span class="tag"><button</span><span class="pln"> </span><span class="atn">type</span><span class="pun">=</span><span class="atv">"submit"</span><span class="pln"> </span><span class="atn">class</span><span class="pun">=</span><span class="atv">"btn"</span><span class="tag">></span><span class="pln">Log in</span><span class="tag"></button></span><span class="pln"> </span><span class="tag"></form></span></code></pre> </div> </div> <div class="colist arabic"> <table> <tbody><tr> <td><i class="conum" data-value="1"></i><b>1</b></td> <td>A POST to the <code>/login</code> URL will attempt to authenticate the user</td> </tr> <tr> <td><i class="conum" data-value="2"></i><b>2</b></td> <td>If the query parameter <code>error</code> exists, authentication was attempted and failed</td> </tr> <tr> <td><i class="conum" data-value="3"></i><b>3</b></td> <td>If the query parameter <code>logout</code> exists, the user was successfully logged out</td> </tr> <tr> <td><i class="conum" data-value="4"></i><b>4</b></td> <td>The username must be present as the HTTP parameter named <em>username</em></td> </tr> <tr> <td><i class="conum" data-value="5"></i><b>5</b></td> <td>The password must be present as the HTTP parameter named <em>password</em></td> </tr> <tr> <td><i class="conum" data-value="6"></i><b>6</b></td> <td>We must <a href="#csrf-include-csrf-token">Include the CSRF Token</a> To learn more read the <a href="#csrf">Cross Site Request Forgery (CSRF)</a> section of the reference</td> </tr> </tbody></table> </div> </div> <div class="sect2"> <h3 id="authorize-requests"><a class="anchor" href="#authorize-requests"></a>3.4. Authorize Requests</h3> <div class="paragraph"> <p>Our examples have only required users to be authenticated and have done so for every URL in our application. We can specify custom requirements for our URLs by adding multiple children to our <code>http.authorizeRequests()</code> method. For example:</p> </div> <div class="listingblock"> <div class="content"> <pre style="" class="prettyprint java language-java prettyprinted"><code><span class="kwd">protected</span><span class="pln"> </span><span class="kwd">void</span><span class="pln"> configure</span><span class="pun">(</span><span class="typ">HttpSecurity</span><span class="pln"> http</span><span class="pun">)</span><span class="pln"> </span><span class="kwd">throws</span><span class="pln"> </span><span class="typ">Exception</span><span class="pln"> </span><span class="pun">{</span><span class="pln"> http </span><span class="pun">.</span><span class="pln">authorizeRequests</span><span class="pun">()</span><span class="pln"> </span><i class="conum" data-value="1"></i><b><span class="pun">(</span><span class="lit">1</span><span class="pun">)</span></b><span class="pln"> </span><span class="pun">.</span><span class="pln">antMatchers</span><span class="pun">(</span><span class="str">"/resources/**"</span><span class="pun">,</span><span class="pln"> </span><span class="str">"/signup"</span><span class="pun">,</span><span class="pln"> </span><span class="str">"/about"</span><span class="pun">).</span><span class="pln">permitAll</span><span class="pun">()</span><span class="pln"> </span><i class="conum" data-value="2"></i><b><span class="pun">(</span><span class="lit">2</span><span class="pun">)</span></b><span class="pln"> </span><span class="pun">.</span><span class="pln">antMatchers</span><span class="pun">(</span><span class="str">"/admin/**"</span><span class="pun">).</span><span class="pln">hasRole</span><span class="pun">(</span><span class="str">"ADMIN"</span><span class="pun">)</span><span class="pln"> </span><i class="conum" data-value="3"></i><b><span class="pun">(</span><span class="lit">3</span><span class="pun">)</span></b><span class="pln"> </span><span class="pun">.</span><span class="pln">antMatchers</span><span class="pun">(</span><span class="str">"/db/**"</span><span class="pun">).</span><span class="pln">access</span><span class="pun">(</span><span class="str">"hasRole('ROLE_ADMIN') and hasRole('ROLE_DBA')"</span><span class="pun">)</span><span class="pln"> </span><i class="conum" data-value="4"></i><b><span class="pun">(</span><span class="lit">4</span><span class="pun">)</span></b><span class="pln"> </span><span class="pun">.</span><span class="pln">anyRequest</span><span class="pun">().</span><span class="pln">authenticated</span><span class="pun">()</span><span class="pln"> </span><i class="conum" data-value="5"></i><b><span class="pun">(</span><span class="lit">5</span><span class="pun">)</span></b><span class="pln"> </span><span class="pun">.</span><span class="pln">and</span><span class="pun">()</span><span class="pln"> </span><span class="com">// ...</span><span class="pln"> </span><span class="pun">.</span><span class="pln">formLogin</span><span class="pun">();</span><span class="pln"> </span><span class="pun">}</span></code></pre> </div> </div> <div class="colist arabic"> <table> <tbody><tr> <td><i class="conum" data-value="1"></i><b>1</b></td> <td>There are multiple children to the <code>http.authorizeRequests()</code> method each matcher is considered in the order they were declared.</td> </tr> <tr> <td><i class="conum" data-value="2"></i><b>2</b></td> <td>We specified multiple URL patterns that any user can access. Specifically, any user can access a request if the URL starts with "/resources/", equals "/signup", or equals "/about".</td> </tr> <tr> <td><i class="conum" data-value="3"></i><b>3</b></td> <td>Any URL that starts with "/admin/" will be resticted to users who have the role "ROLE_ADMIN". You will notice that since we are invoking the <code>hasRole</code> method we do not need to specify the "ROLE_" prefix.</td> </tr> <tr> <td><i class="conum" data-value="4"></i><b>4</b></td> <td>Any URL that starts with "/db/" requires the user to have both "ROLE_ADMIN" and "ROLE_DBA"</td> </tr> <tr> <td><i class="conum" data-value="5"></i><b>5</b></td> <td>Any URL that has not already been matched on only requires that the user be authenticated</td> </tr> </tbody></table> </div> </div> <div class="sect2"> <h3 id="jc-authentication"><a class="anchor" href="#jc-authentication"></a>3.5. Authentication</h3> <div class="paragraph"> <p>Thus far we have only taken a look at the most basic authentication configuration. Let’s take a look at a few slightly more advanced options for configuring authentication.</p> </div> <div class="sect3"> <h4 id="jc-authentication-inmememory"><a class="anchor" href="#jc-authentication-inmememory"></a>3.5.1. In Memory Authentication</h4> <div class="paragraph"> <p>We have already seen an example of configuring in memory authentication for a single user. Below is an example to configure multiple users:</p> </div> <div class="listingblock"> <div class="content"> <pre style="" class="prettyprint java language-java prettyprinted"><code><span class="lit">@Autowired</span><span class="pln"> </span><span class="kwd">public</span><span class="pln"> </span><span class="kwd">void</span><span class="pln"> configureGlobal</span><span class="pun">(</span><span class="typ">AuthenticationManagerBuilder</span><span class="pln"> auth</span><span class="pun">)</span><span class="pln"> </span><span class="kwd">throws</span><span class="pln"> </span><span class="typ">Exception</span><span class="pln"> </span><span class="pun">{</span><span class="pln"> auth </span><span class="pun">.</span><span class="pln">inMemoryAuthentication</span><span class="pun">()</span><span class="pln"> </span><span class="pun">.</span><span class="pln">withUser</span><span class="pun">(</span><span class="str">"user"</span><span class="pun">).</span><span class="pln">password</span><span class="pun">(</span><span class="str">"password"</span><span class="pun">).</span><span class="pln">roles</span><span class="pun">(</span><span class="str">"USER"</span><span class="pun">).</span><span class="pln">and</span><span class="pun">()</span><span class="pln"> </span><span class="pun">.</span><span class="pln">withUser</span><span class="pun">(</span><span class="str">"admin"</span><span class="pun">).</span><span class="pln">password</span><span class="pun">(</span><span class="str">"password"</span><span class="pun">).</span><span class="pln">roles</span><span class="pun">(</span><span class="str">"USER"</span><span class="pun">,</span><span class="pln"> </span><span class="str">"ADMIN"</span><span class="pun">);</span><span class="pln"> </span><span class="pun">}</span></code></pre> </div> </div> </div> <div class="sect3"> <h4 id="jc-authentication-jdbc"><a class="anchor" href="#jc-authentication-jdbc"></a>3.5.2. JDBC Authentication</h4> <div class="paragraph"> <p>You can find the updates to suppport JDBC based authentication. The example below assumes that you have already defined a <code>DataSource</code> within your application. The <a href="https://github.com/spring-projects/spring-security/tree/master/samples/jdbc-jc">jdbc-jc sample</a> provides a complete example of using JDBC based authentication.</p> </div> <div class="listingblock"> <div class="content"> <pre style="" class="prettyprint java language-java prettyprinted"><code><span class="lit">@Autowired</span><span class="pln"> </span><span class="kwd">private</span><span class="pln"> </span><span class="typ">DataSource</span><span class="pln"> dataSource</span><span class="pun">;</span><span class="pln"> </span><span class="lit">@Autowired</span><span class="pln"> </span><span class="kwd">public</span><span class="pln"> </span><span class="kwd">void</span><span class="pln"> configureGlobal</span><span class="pun">(</span><span class="typ">AuthenticationManagerBuilder</span><span class="pln"> auth</span><span class="pun">)</span><span class="pln"> </span><span class="kwd">throws</span><span class="pln"> </span><span class="typ">Exception</span><span class="pln"> </span><span class="pun">{</span><span class="pln"> auth </span><span class="pun">.</span><span class="pln">jdbcAuthentication</span><span class="pun">()</span><span class="pln"> </span><span class="pun">.</span><span class="pln">dataSource</span><span class="pun">(</span><span class="pln">dataSource</span><span class="pun">)</span><span class="pln"> </span><span class="pun">.</span><span class="pln">withDefaultSchema</span><span class="pun">()</span><span class="pln"> </span><span class="pun">.</span><span class="pln">withUser</span><span class="pun">(</span><span class="str">"user"</span><span class="pun">).</span><span class="pln">password</span><span class="pun">(</span><span class="str">"password"</span><span class="pun">).</span><span class="pln">roles</span><span class="pun">(</span><span class="str">"USER"</span><span class="pun">).</span><span class="pln">and</span><span class="pun">()</span><span class="pln"> </span><span class="pun">.</span><span class="pln">withUser</span><span class="pun">(</span><span class="str">"admin"</span><span class="pun">).</span><span class="pln">password</span><span class="pun">(</span><span class="str">"password"</span><span class="pun">).</span><span class="pln">roles</span><span class="pun">(</span><span class="str">"USER"</span><span class="pun">,</span><span class="pln"> </span><span class="str">"ADMIN"</span><span class="pun">);</span><span class="pln"> </span><span class="pun">}</span></code></pre> </div> </div> </div> <div class="sect3"> <h4 id="ldap-authentication"><a class="anchor" href="#ldap-authentication"></a>3.5.3. LDAP Authentication</h4> <div class="paragraph"> <p>You can find the updates to suppport LDAP based authentication. The <a href="https://github.com/spring-projects/spring-security/tree/master/samples/ldap-jc">ldap-jc sample</a> provides a complete example of using LDAP based authentication.</p> </div> <div class="listingblock"> <div class="content"> <pre style="" class="prettyprint java language-java prettyprinted"><code><span class="lit">@Autowired</span><span class="pln"> </span><span class="kwd">private</span><span class="pln"> </span><span class="typ">DataSource</span><span class="pln"> dataSource</span><span class="pun">;</span><span class="pln"> </span><span class="lit">@Autowired</span><span class="pln"> </span><span class="kwd">public</span><span class="pln"> </span><span class="kwd">void</span><span class="pln"> configureGlobal</span><span class="pun">(</span><span class="typ">AuthenticationManagerBuilder</span><span class="pln"> auth</span><span class="pun">)</span><span class="pln"> </span><span class="kwd">throws</span><span class="pln"> </span><span class="typ">Exception</span><span class="pln"> </span><span class="pun">{</span><span class="pln"> auth </span><span class="pun">.</span><span class="pln">ldapAuthentication</span><span class="pun">()</span><span class="pln"> </span><span class="pun">.</span><span class="pln">userDnPatterns</span><span class="pun">(</span><span class="str">"uid={0},ou=people"</span><span class="pun">)</span><span class="pln"> </span><span class="pun">.</span><span class="pln">groupSearchBase</span><span class="pun">(</span><span class="str">"ou=groups"</span><span class="pun">);</span><span class="pln"> </span><span class="pun">}</span></code></pre> </div> </div> <div class="paragraph"> <p>The example above uses the following LDIF and an embedded Apache DS LDAP instance.</p> </div> <div class="listingblock"> <div class="title">users.ldif</div> <div class="content"> <pre>dn: ou=groups,dc=springframework,dc=org objectclass: top objectclass: organizationalUnit ou: groups dn: ou=people,dc=springframework,dc=org objectclass: top objectclass: organizationalUnit ou: people dn: uid=admin,ou=people,dc=springframework,dc=org objectclass: top objectclass: person objectclass: organizationalPerson objectclass: inetOrgPerson cn: Rod Johnson sn: Johnson uid: admin userPassword: password dn: uid=user,ou=people,dc=springframework,dc=org objectclass: top objectclass: person objectclass: organizationalPerson objectclass: inetOrgPerson cn: Dianne Emu sn: Emu uid: user userPassword: password dn: cn=user,ou=groups,dc=springframework,dc=org objectclass: top objectclass: groupOfNames cn: user uniqueMember: uid=admin,ou=people,dc=springframework,dc=org uniqueMember: uid=user,ou=people,dc=springframework,dc=org dn: cn=admin,ou=groups,dc=springframework,dc=org objectclass: top objectclass: groupOfNames cn: admin uniqueMember: uid=admin,ou=people,dc=springframework,dc=org</pre> </div> </div> </div> </div> <div class="sect2"> <h3 id="multiple-httpsecurity"><a class="anchor" href="#multiple-httpsecurity"></a>3.6. Multiple HttpSecurity</h3> <div class="paragraph"> <p>We can configure multiple HttpSecurity instances just as we can have multiple <code><http></code> blocks. The key is to extend the <code>WebSecurityConfigurationAdapter</code> multiple times. For example, the following is an example of having a different configuration for URL’s that start with <code>/api/</code>.</p> </div> <div class="listingblock"> <div class="content"> <pre style="" class="prettyprint java language-java prettyprinted"><code><span class="lit">@Configuration</span><span class="pln"> </span><span class="lit">@EnableWebSecurity</span><span class="pln"> </span><span class="kwd">public</span><span class="pln"> </span><span class="kwd">class</span><span class="pln"> </span><span class="typ">MultiHttpSecurityConfig</span><span class="pln"> </span><span class="pun">{</span><span class="pln"> </span><span class="lit">@Autowired</span><span class="pln"> </span><span class="kwd">public</span><span class="pln"> </span><span class="kwd">void</span><span class="pln"> configureGlobal</span><span class="pun">(</span><span class="typ">AuthenticationManagerBuilder</span><span class="pln"> auth</span><span class="pun">)</span><span class="pln"> </span><span class="pun">{</span><span class="pln"> </span><i class="conum" data-value="1"></i><b><span class="pun">(</span><span class="lit">1</span><span class="pun">)</span></b><span class="pln"> auth </span><span class="pun">.</span><span class="pln">inMemoryAuthentication</span><span class="pun">()</span><span class="pln"> </span><span class="pun">.</span><span class="pln">withUser</span><span class="pun">(</span><span class="str">"user"</span><span class="pun">).</span><span class="pln">password</span><span class="pun">(</span><span class="str">"password"</span><span class="pun">).</span><span class="pln">roles</span><span class="pun">(</span><span class="str">"USER"</span><span class="pun">).</span><span class="pln">and</span><span class="pun">()</span><span class="pln"> </span><span class="pun">.</span><span class="pln">withUser</span><span class="pun">(</span><span class="str">"admin"</span><span class="pun">).</span><span class="pln">password</span><span class="pun">(</span><span class="str">"password"</span><span class="pun">).</span><span class="pln">roles</span><span class="pun">(</span><span class="str">"USER"</span><span class="pun">,</span><span class="pln"> </span><span class="str">"ADMIN"</span><span class="pun">);</span><span class="pln"> </span><span class="pun">}</span><span class="pln"> </span><span class="lit">@Configuration</span><span class="pln"> </span><span class="lit">@Order</span><span class="pun">(</span><span class="lit">1</span><span class="pun">)</span><span class="pln"> </span><i class="conum" data-value="2"></i><b><span class="pun">(</span><span class="lit">2</span><span class="pun">)</span></b><span class="pln"> </span><span class="kwd">public</span><span class="pln"> </span><span class="kwd">static</span><span class="pln"> </span><span class="kwd">class</span><span class="pln"> </span><span class="typ">ApiWebSecurityConfigurationAdapter</span><span class="pln"> </span><span class="kwd">extends</span><span class="pln"> </span><span class="typ">WebSecurityConfigurerAdapter</span><span class="pln"> </span><span class="pun">{</span><span class="pln"> </span><span class="kwd">protected</span><span class="pln"> </span><span class="kwd">void</span><span class="pln"> configure</span><span class="pun">(</span><span class="typ">HttpSecurity</span><span class="pln"> http</span><span class="pun">)</span><span class="pln"> </span><span class="kwd">throws</span><span class="pln"> </span><span class="typ">Exception</span><span class="pln"> </span><span class="pun">{</span><span class="pln"> http </span><span class="pun">.</span><span class="pln">antMatcher</span><span class="pun">(</span><span class="str">"/api/**"</span><span class="pun">)</span><span class="pln"> </span><i class="conum" data-value="3"></i><b><span class="pun">(</span><span class="lit">3</span><span class="pun">)</span></b><span class="pln"> </span><span class="pun">.</span><span class="pln">authorizeRequests</span><span class="pun">()</span><span class="pln"> </span><span class="pun">.</span><span class="pln">anyRequest</span><span class="pun">().</span><span class="pln">hasRole</span><span class="pun">(</span><span class="str">"ADMIN"</span><span class="pun">)</span><span class="pln"> </span><span class="pun">.</span><span class="pln">and</span><span class="pun">()</span><span class="pln"> </span><span class="pun">.</span><span class="pln">httpBasic</span><span class="pun">();</span><span class="pln"> </span><span class="pun">}</span><span class="pln"> </span><span class="pun">}</span><span class="pln"> </span><span class="lit">@Configuration</span><span class="pln"> </span><i class="conum" data-value="4"></i><b><span class="pun">(</span><span class="lit">4</span><span class="pun">)</span></b><span class="pln"> </span><span class="kwd">public</span><span class="pln"> </span><span class="kwd">static</span><span class="pln"> </span><span class="kwd">class</span><span class="pln"> </span><span class="typ">FormLoginWebSecurityConfigurerAdapter</span><span class="pln"> </span><span class="kwd">extends</span><span class="pln"> </span><span class="typ">WebSecurityConfigurerAdapter</span><span class="pln"> </span><span class="pun">{</span><span class="pln"> </span><span class="lit">@Override</span><span class="pln"> </span><span class="kwd">protected</span><span class="pln"> </span><span class="kwd">void</span><span class="pln"> configure</span><span class="pun">(</span><span class="typ">HttpSecurity</span><span class="pln"> http</span><span class="pun">)</span><span class="pln"> </span><span class="kwd">throws</span><span class="pln"> </span><span class="typ">Exception</span><span class="pln"> </span><span class="pun">{</span><span class="pln"> http </span><span class="pun">.</span><span class="pln">authorizeRequests</span><span class="pun">()</span><span class="pln"> </span><span class="pun">.</span><span class="pln">anyRequest</span><span class="pun">().</span><span class="pln">authenticated</span><span class="pun">()</span><span class="pln"> </span><span class="pun">.</span><span class="pln">and</span><span class="pun">()</span><span class="pln"> </span><span class="pun">.</span><span class="pln">formLogin</span><span class="pun">();</span><span class="pln"> </span><span class="pun">}</span><span class="pln"> </span><span class="pun">}</span><span class="pln"> </span><span class="pun">}</span></code></pre> </div> </div> <div class="colist arabic"> <table> <tbody><tr> <td><i class="conum" data-value="1"></i><b>1</b></td> <td>Configure Authentication as normal</td> </tr> <tr> <td><i class="conum" data-value="2"></i><b>2</b></td> <td>Create an instance of <code>WebSecurityConfigurerAdapter</code> that contains <code>@Order</code> to specify which <code>WebSecurityConfigurerAdapter</code> should be considered first.</td> </tr> <tr> <td><i class="conum" data-value="3"></i><b>3</b></td> <td>The <code>http.antMatcher</code> states that this <code>HttpSecurity</code> will only be applicable to URLs that start with <code>/api/</code></td> </tr> <tr> <td><i class="conum" data-value="4"></i><b>4</b></td> <td>Create another instance of <code>WebSecurityConfigurerAdapter</code>. If the URL does not start with <code>/api/</code> this configuration will be used. This configuration is considered after <code>ApiWebSecurityConfigurationAdapter</code> since it has an <code>@Order</code> value after <code>1</code> (no <code>@Order</code> defaults to last).</td> </tr> </tbody></table> </div> </div> <div class="sect2"> <h3 id="jc-method"><a class="anchor" href="#jc-method"></a>3.7. Method Security</h3> <div class="paragraph"> <p>From version 2.0 onwards Spring Security has improved support substantially for adding security to your service layer methods. It provides support for JSR-250 annotation security as well as the framework’s original @Secured annotation. From 3.0 you can also make use of new <a href="#el-access">expression-based annotations</a>. You can apply security to a single bean, using the intercept-methods element to decorate the bean declaration, or you can secure multiple beans across the entire service layer using the AspectJ style pointcuts.</p> </div> <div class="sect3"> <h4 id="enableglobalmethodsecurity"><a class="anchor" href="#enableglobalmethodsecurity"></a>3.7.1. EnableGlobalMethodSecurity</h4> <div class="paragraph"> <p>We can enable annotation-based security using the <code>@EnableGlobalMethodSecurity</code> annotation on any <code>@Configuration</code> instance. For example, the following would enable Spring Security’s <code>@Secured</code> annotation.</p> </div> <div class="listingblock"> <div class="content"> <pre style="" class="prettyprint java language-java prettyprinted"><code><span class="lit">@Configuration</span><span class="pln"> </span><span class="lit">@EnableGlobalMethodSecurity</span><span class="pun">(</span><span class="pln">securedEnabled </span><span class="pun">=</span><span class="pln"> </span><span class="kwd">true</span><span class="pun">)</span><span class="pln"> </span><span class="kwd">public</span><span class="pln"> </span><span class="kwd">class</span><span class="pln"> </span><span class="typ">MethodSecurityConfig</span><span class="pln"> </span><span class="pun">{</span><span class="pln"> </span><span class="com">// ...</span><span class="pln"> </span><span class="pun">}</span></code></pre> </div> </div> <div class="paragraph"> <p>Adding an annotation to a method (on an class or interface) would then limit the access to that method accordingly. Spring Security’s native annotation support defines a set of attributes for the method. These will be passed to the AccessDecisionManager for it to make the actual decision:</p> </div> <div class="listingblock"> <div class="content"> <pre style="" class="prettyprint java language-java prettyprinted"><code><span class="kwd">public</span><span class="pln"> </span><span class="kwd">interface</span><span class="pln"> </span><span class="typ">BankService</span><span class="pln"> </span><span class="pun">{</span><span class="pln"> </span><span class="lit">@Secured</span><span class="pun">(</span><span class="str">"IS_AUTHENTICATED_ANONYMOUSLY"</span><span class="pun">)</span><span class="pln"> </span><span class="kwd">public</span><span class="pln"> </span><span class="typ">Account</span><span class="pln"> readAccount</span><span class="pun">(</span><span class="typ">Long</span><span class="pln"> id</span><span class="pun">);</span><span class="pln"> </span><span class="lit">@Secured</span><span class="pun">(</span><span class="str">"IS_AUTHENTICATED_ANONYMOUSLY"</span><span class="pun">)</span><span class="pln"> </span><span class="kwd">public</span><span class="pln"> </span><span class="typ">Account</span><span class="pun">[]</span><span class="pln"> findAccounts</span><span class="pun">();</span><span class="pln"> </span><span class="lit">@Secured</span><span class="pun">(</span><span class="str">"ROLE_TELLER"</span><span class="pun">)</span><span class="pln"> </span><span class="kwd">public</span><span class="pln"> </span><span class="typ">Account</span><span class="pln"> post</span><span class="pun">(</span><span class="typ">Account</span><span class="pln"> account</span><span class="pun">,</span><span class="pln"> </span><span class="kwd">double</span><span class="pln"> amount</span><span class="pun">);</span><span class="pln"> </span><span class="pun">}</span></code></pre> </div> </div> <div class="paragraph"> <p>Support for JSR-250 annotations can be enabled using</p> </div> <div class="listingblock"> <div class="content"> <pre style="" class="prettyprint java language-java prettyprinted"><code><span class="lit">@Configuration</span><span class="pln"> </span><span class="lit">@EnableGlobalMethodSecurity</span><span class="pun">(</span><span class="pln">jsr250Enabled </span><span class="pun">=</span><span class="pln"> </span><span class="kwd">true</span><span class="pun">)</span><span class="pln"> </span><span class="kwd">public</span><span class="pln"> </span><span class="kwd">class</span><span class="pln"> </span><span class="typ">MethodSecurityConfig</span><span class="pln"> </span><span class="pun">{</span><span class="pln"> </span><span class="com">// ...</span><span class="pln"> </span><span class="pun">}</span></code></pre> </div> </div> <div class="paragraph"> <p>These are standards-based and allow simple role-based constraints to be applied but do not have the power Spring Security’s native annotations. To use the new expression-based syntax, you would use</p> </div> <div class="listingblock"> <div class="content"> <pre style="" class="prettyprint java language-java prettyprinted"><code><span class="lit">@Configuration</span><span class="pln"> </span><span class="lit">@EnableGlobalMethodSecurity</span><span class="pun">(</span><span class="pln">prePostEnabled </span><span class="pun">=</span><span class="pln"> </span><span class="kwd">true</span><span class="pun">)</span><span class="pln"> </span><span class="kwd">public</span><span class="pln"> </span><span class="kwd">class</span><span class="pln"> </span><span class="typ">MethodSecurityConfig</span><span class="pln"> </span><span class="pun">{</span><span class="pln"> </span><span class="com">// ...</span><span class="pln"> </span><span class="pun">}</span></code></pre> </div> </div> <div class="paragraph"> <p>and the equivalent Java code would be</p> </div> <div class="listingblock"> <div class="content"> <pre style="" class="prettyprint java language-java prettyprinted"><code><span class="kwd">public</span><span class="pln"> </span><span class="kwd">interface</span><span class="pln"> </span><span class="typ">BankService</span><span class="pln"> </span><span class="pun">{</span><span class="pln"> </span><span class="lit">@PreAuthorize</span><span class="pun">(</span><span class="str">"isAnonymous()"</span><span class="pun">)</span><span class="pln"> </span><span class="kwd">public</span><span class="pln"> </span><span class="typ">Account</span><span class="pln"> readAccount</span><span class="pun">(</span><span class="typ">Long</span><span class="pln"> id</span><span class="pun">);</span><span class="pln"> </span><span class="lit">@PreAuthorize</span><span class="pun">(</span><span class="str">"isAnonymous()"</span><span class="pun">)</span><span class="pln"> </span><span class="kwd">public</span><span class="pln"> </span><span class="typ">Account</span><span class="pun">[]</span><span class="pln"> findAccounts</span><span class="pun">();</span><span class="pln"> </span><span class="lit">@PreAuthorize</span><span class="pun">(</span><span class="str">"hasAuthority('ROLE_TELLER')"</span><span class="pun">)</span><span class="pln"> </span><span class="kwd">public</span><span class="pln"> </span><span class="typ">Account</span><span class="pln"> post</span><span class="pun">(</span><span class="typ">Account</span><span class="pln"> account</span><span class="pun">,</span><span class="pln"> </span><span class="kwd">double</span><span class="pln"> amount</span><span class="pun">);</span><span class="pln"> </span><span class="pun">}</span></code></pre> </div> </div> </div> <div class="sect3"> <h4 id="globalmethodsecurityconfiguration"><a class="anchor" href="#globalmethodsecurityconfiguration"></a>3.7.2. GlobalMethodSecurityConfiguration</h4> <div class="paragraph"> <p>Sometimes you may need to perform operations that are more complicated than are possible with the <code>@EnableGlobalMethodSecurity</code> annotation allow. For these instances, you can extend the <code>GlobalMethodSecurityConfiguration</code> ensuring that the <code>@EnableGlobalMethodSecurity</code> annotation is present on your subclass. For example, if you wanted to provide a custom <code>MethodSecurityExpressionHander</code>, you could use the following configuration:</p> </div> <div class="listingblock"> <div class="content"> <pre style="" class="prettyprint java language-java prettyprinted"><code><span class="lit">@Configuration</span><span class="pln"> </span><span class="lit">@EnableGlobalMethodSecurity</span><span class="pun">(</span><span class="pln">prePostEnabled </span><span class="pun">=</span><span class="pln"> </span><span class="kwd">true</span><span class="pun">)</span><span class="pln"> </span><span class="kwd">public</span><span class="pln"> </span><span class="kwd">class</span><span class="pln"> </span><span class="typ">MethodSecurityConfig</span><span class="pln"> </span><span class="kwd">extends</span><span class="pln"> </span><span class="typ">GlobalMethodSecurityConfiguration</span><span class="pln"> </span><span class="pun">{</span><span class="pln"> </span><span class="lit">@Override</span><span class="pln"> </span><span class="kwd">protected</span><span class="pln"> </span><span class="typ">MethodSecurityExpressionHandler</span><span class="pln"> createExpressionHandler</span><span class="pun">()</span><span class="pln"> </span><span class="pun">{</span><span class="pln"> </span><span class="com">// ... create and return custom MethodSecurityExpressionHandler ...</span><span class="pln"> </span><span class="kwd">return</span><span class="pln"> expressionHander</span><span class="pun">;</span><span class="pln"> </span><span class="pun">}</span><span class="pln"> </span><span class="pun">}</span></code></pre> </div> </div> <div class="paragraph"> <p>For additional information about methods that can be overriden, refer to the <code>GlobalMethodSecurityConfiguration</code> Javadoc.</p> </div> </div> </div> <div class="sect2"> <h3 id="post-processing-configured-objects"><a class="anchor" href="#post-processing-configured-objects"></a>3.8. Post Processing Configured Objects</h3> <div class="paragraph"> <p>Spring Security’s Java Configuration does not expose every property of every object that it configures. This simplifies the configuration for a majority of users. Afterall, if every property was exposed, users could use standard bean configuration.</p> </div> <div class="paragraph"> <p>While there are good reasons to not directly expose every property, users may still need more advanced configuration options. To address this Spring Security introduces the concept of an <code>ObjectPostProcessor</code> which can used to modify or replace many of the Object instances created by the Java Configuration. For example, if you wanted to configure the <code>filterSecurityPublishAuthorizationSuccess</code> property on <code>FilterSecurityInterceptor</code> you could use the following:</p> </div> <div class="listingblock"> <div class="content"> <pre style="" class="prettyprint java language-java prettyprinted"><code><span class="lit">@Override</span><span class="pln"> </span><span class="kwd">protected</span><span class="pln"> </span><span class="kwd">void</span><span class="pln"> configure</span><span class="pun">(</span><span class="typ">HttpSecurity</span><span class="pln"> http</span><span class="pun">)</span><span class="pln"> </span><span class="kwd">throws</span><span class="pln"> </span><span class="typ">Exception</span><span class="pln"> </span><span class="pun">{</span><span class="pln"> http </span><span class="pun">.</span><span class="pln">authorizeRequests</span><span class="pun">()</span><span class="pln"> </span><span class="pun">.</span><span class="pln">anyRequest</span><span class="pun">().</span><span class="pln">authenticated</span><span class="pun">()</span><span class="pln"> </span><span class="pun">.</span><span class="pln">withObjectPostProcessor</span><span class="pun">(</span><span class="kwd">new</span><span class="pln"> </span><span class="typ">ObjectPostProcessor</span><span class="pun"><</span><span class="typ">FilterSecurityInterceptor</span><span class="pun">>()</span><span class="pln"> </span><span class="pun">{</span><span class="pln"> </span><span class="kwd">public</span><span class="pln"> </span><span class="pun"><</span><span class="pln">O </span><span class="kwd">extends</span><span class="pln"> </span><span class="typ">FilterSecurityInterceptor</span><span class="pun">></span><span class="pln"> O postProcess</span><span class="pun">(</span><span class="pln"> O fsi</span><span class="pun">)</span><span class="pln"> </span><span class="pun">{</span><span class="pln"> fsi</span><span class="pun">.</span><span class="pln">setPublishAuthorizationSuccess</span><span class="pun">(</span><span class="kwd">true</span><span class="pun">);</span><span class="pln"> </span><span class="kwd">return</span><span class="pln"> fsi</span><span class="pun">;</span><span class="pln"> </span><span class="pun">}</span><span class="pln"> </span><span class="pun">});</span><span class="pln"> </span><span class="pun">}</span></code></pre> </div> </div> </div> </div> </div> <div class="sect1"> <h2 id="ns-config"><a class="anchor" href="#ns-config"></a>4. Security Namespace Configuration</h2> <div class="sectionbody"> <div class="sect2"> <h3 id="introduction-2"><a class="anchor" href="#introduction-2"></a>4.1. Introduction</h3> <div class="paragraph"> <p>Namespace configuration has been available since version 2.0 of the Spring framework. It allows you to supplement the traditional Spring beans application context syntax with elements from additional XML schema. You can find more information in the Spring <a href="http://static.springsource.org/spring/docs/3.0.x/spring-framework-reference/htmlsingle/spring-framework-reference.html">Reference Documentation</a>. A namespace element can be used simply to allow a more concise way of configuring an individual bean or, more powerfully, to define an alternative configuration syntax which more closely matches the problem domain and hides the underlying complexity from the user. A simple element may conceal the fact that multiple beans and processing steps are being added to the application context. For example, adding the following element from the security namespace to an application context will start up an embedded LDAP server for testing use within the application:</p> </div> <div class="listingblock"> <div class="content"> <pre style="" class="prettyprint xml language-xml prettyprinted"><code><span class="tag"><security:ldap-server</span><span class="pln"> </span><span class="tag">/></span></code></pre> </div> </div> <div class="paragraph"> <p>This is much simpler than wiring up the equivalent Apache Directory Server beans. The most common alternative configuration requirements are supported by attributes on the <code>ldap-server</code> element and the user is isolated from worrying about which beans they need to create and what the bean property names are. <span class="footnote">[<a id="_footnoteref_1" class="footnote" href="#_footnote_1" title="View footnote.">1</a>]</span>. Use of a good XML editor while editing the application context file should provide information on the attributes and elements that are available. We would recommend that you try out the <a href="http://www.springsource.com/products/sts">SpringSource Tool Suite</a> as it has special features for working with standard Spring namespaces.</p> </div> <div class="paragraph"> <p>To start using the security namespace in your application context, you need to have the <code>spring-security-config</code> jar on your classpath. Then all you need to do is add the schema declaration to your application context file:</p> </div> <div class="listingblock"> <div class="content"> <pre style="" class="prettyprint xml language-xml prettyprinted"><code><span class="tag"><beans</span><span class="pln"> </span><span class="atn">xmlns</span><span class="pun">=</span><span class="atv">"http://www.springframework.org/schema/beans"</span><span class="pln"> </span><span class="atn">xmlns:security</span><span class="pun">=</span><span class="atv">"http://www.springframework.org/schema/security"</span><span class="pln"> </span><span class="atn">xmlns:xsi</span><span class="pun">=</span><span class="atv">"http://www.w3.org/2001/XMLSchema-instance"</span><span class="pln"> </span><span class="atn">xsi:schemaLocation</span><span class="pun">=</span><span class="atv">"http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd http://www.springframework.org/schema/security http://www.springframework.org/schema/security/spring-security.xsd"</span><span class="tag">></span><span class="pln"> ... </span><span class="tag"></beans></span></code></pre> </div> </div> <div class="paragraph"> <p>In many of the examples you will see (and in the sample) applications, we will often use "security" as the default namespace rather than "beans", which means we can omit the prefix on all the security namespace elements, making the content easier to read. You may also want to do this if you have your application context divided up into separate files and have most of your security configuration in one of them. Your security application context file would then start like this</p> </div> <div class="listingblock"> <div class="content"> <pre style="" class="prettyprint xml language-xml prettyprinted"><code><span class="tag"><beans:beans</span><span class="pln"> </span><span class="atn">xmlns</span><span class="pun">=</span><span class="atv">"http://www.springframework.org/schema/security"</span><span class="pln"> </span><span class="atn">xmlns:beans</span><span class="pun">=</span><span class="atv">"http://www.springframework.org/schema/beans"</span><span class="pln"> </span><span class="atn">xmlns:xsi</span><span class="pun">=</span><span class="atv">"http://www.w3.org/2001/XMLSchema-instance"</span><span class="pln"> </span><span class="atn">xsi:schemaLocation</span><span class="pun">=</span><span class="atv">"http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd http://www.springframework.org/schema/security http://www.springframework.org/schema/security/spring-security.xsd"</span><span class="tag">></span><span class="pln"> ... </span><span class="tag"></beans:beans></span></code></pre> </div> </div> <div class="paragraph"> <p>We’ll assume this syntax is being used from now on in this chapter.</p> </div> <div class="sect3"> <h4 id="design-of-the-namespace"><a class="anchor" href="#design-of-the-namespace"></a>4.1.1. Design of the Namespace</h4> <div class="paragraph"> <p>The namespace is designed to capture the most common uses of the framework and provide a simplified and concise syntax for enabling them within an application. The design is based around the large-scale dependencies within the framework, and can be divided up into the following areas:</p> </div> <div class="ulist"> <ul> <li> <p><em>Web/HTTP Security</em> - the most complex part. Sets up the filters and related service beans used to apply the framework authentication mechanisms, to secure URLs, render login and error pages and much more.</p> </li> <li> <p><em>Business Object (Method) Security</em> - options for securing the service layer.</p> </li> <li> <p><em>AuthenticationManager</em> - handles authentication requests from other parts of the framework.</p> </li> <li> <p><em>AccessDecisionManager</em> - provides access decisions for web and method security. A default one will be registered, but you can also choose to use a custom one, declared using normal Spring bean syntax.</p> </li> <li> <p><em>AuthenticationProvider</em>s - mechanisms against which the authentication manager authenticates users. The namespace provides supports for several standard options and also a means of adding custom beans declared using a traditional syntax.</p> </li> <li> <p><em>UserDetailsService</em> - closely related to authentication providers, but often also required by other beans.</p> </li> </ul> </div> <div class="paragraph"> <p>We’ll see how to configure these in the following sections.</p> </div> </div> </div> <div class="sect2"> <h3 id="ns-getting-started"><a class="anchor" href="#ns-getting-started"></a>4.2. Getting Started with Security Namespace Configuration</h3> <div class="paragraph"> <p>In this section, we’ll look at how you can build up a namespace configuration to use some of the main features of the framework. Let’s assume you initially want to get up and running as quickly as possible and add authentication support and access control to an existing web application, with a few test logins. Then we’ll look at how to change over to authenticating against a database or other security repository. In later sections we’ll introduce more advanced namespace configuration options.</p> </div> <div class="sect3"> <h4 id="ns-web-xml"><a class="anchor" href="#ns-web-xml"></a>4.2.1. web.xml Configuration</h4> <div class="paragraph"> <p>The first thing you need to do is add the following filter declaration to your <code>web.xml</code> file:</p> </div> <div class="listingblock"> <div class="content"> <pre style="" class="prettyprint xml language-xml prettyprinted"><code><span class="tag"><filter></span><span class="pln"> </span><span class="tag"><filter-name></span><span class="pln">springSecurityFilterChain</span><span class="tag"></filter-name></span><span class="pln"> </span><span class="tag"><filter-class></span><span class="pln">org.springframework.web.filter.DelegatingFilterProxy</span><span class="tag"></filter-class></span><span class="pln"> </span><span class="tag"></filter></span><span class="pln"> </span><span class="tag"><filter-mapping></span><span class="pln"> </span><span class="tag"><filter-name></span><span class="pln">springSecurityFilterChain</span><span class="tag"></filter-name></span><span class="pln"> </span><span class="tag"><url-pattern></span><span class="pln">/*</span><span class="tag"></url-pattern></span><span class="pln"> </span><span class="tag"></filter-mapping></span></code></pre> </div> </div> <div class="paragraph"> <p>This provides a hook into the Spring Security web infrastructure. <code>DelegatingFilterProxy</code> is a Spring Framework class which delegates to a filter implementation which is defined as a Spring bean in your application context. In this case, the bean is named "springSecurityFilterChain", which is an internal infrastructure bean created by the namespace to handle web security. Note that you should not use this bean name yourself. Once you’ve added this to your <code>web.xml</code>, you’re ready to start editing your application context file. Web security services are configured using the <code><http></code> element.</p> </div> </div> <div class="sect3"> <h4 id="ns-minimal"><a class="anchor" href="#ns-minimal"></a>4.2.2. A Minimal <http> Configuration</h4> <div class="paragraph"> <p>All you need to enable web security to begin with is</p> </div> <div class="listingblock"> <div class="content"> <pre style="" class="prettyprint xml language-xml prettyprinted"><code><span class="tag"><http></span><span class="pln"> </span><span class="tag"><intercept-url</span><span class="pln"> </span><span class="atn">pattern</span><span class="pun">=</span><span class="atv">"/**"</span><span class="pln"> </span><span class="atn">access</span><span class="pun">=</span><span class="atv">"ROLE_USER"</span><span class="pln"> </span><span class="tag">/></span><span class="pln"> </span><span class="tag"><form-login</span><span class="pln"> </span><span class="tag">/></span><span class="pln"> </span><span class="tag"><logout</span><span class="pln"> </span><span class="tag">/></span><span class="pln"> </span><span class="tag"></http></span></code></pre> </div> </div> <div class="paragraph"> <p>Which says that we want all URLs within our application to be secured, requiring the role <code>ROLE_USER</code> to access them, we want to log in to the application using a form with username and password, and that we want a logout URL registered which will allow us to log out of the application. <code><http></code> element is the parent for all web-related namespace functionality. The <code><intercept-url></code> element defines a <code>pattern</code> which is matched against the URLs of incoming requests using an ant path style syntax <span class="footnote">[<a id="_footnoteref_2" class="footnote" href="#_footnote_2" title="View footnote.">2</a>]</span>. You can also use regular-expression matching as an alternative (see the namespace appendix for more details). The <code>access</code> attribute defines the access requirements for requests matching the given pattern. With the default configuration, this is typically a comma-separated list of roles, one of which a user must have to be allowed to make the request. The prefix"ROLE_" is a marker which indicates that a simple comparison with the user’s authorities should be made. In other words, a normal role-based check should be used. Access-control in Spring Security is not limited to the use of simple roles (hence the use of the prefix to differentiate between different types of security attributes). We’ll see later how the interpretation can vary <span class="footnote">[<a id="_footnoteref_3" class="footnote" href="#_footnote_3" title="View footnote.">3</a>]</span>.</p> </div> <div class="admonitionblock note"> <table> <tbody><tr> <td class="icon"> <i class="icon-note" title="Note"></i> </td> <td class="content"> <div class="paragraph"> <p>You can use multiple <code><intercept-url></code> elements to define different access requirements for different sets of URLs, but they will be evaluated in the order listed and the first match will be used. So you must put the most specific matches at the top. You can also add a <code>method</code> attribute to limit the match to a particular HTTP method (<code>GET</code>, <code>POST</code>, <code>PUT</code> etc.).</p> </div> </td> </tr> </tbody></table> </div> <div class="paragraph"> <p>To add some users, you can define a set of test data directly in the namespace:</p> </div> <div class="listingblock"> <div class="content"> <pre style="" class="prettyprint xml language-xml prettyprinted"><code><span class="tag"><authentication-manager></span><span class="pln"> </span><span class="tag"><authentication-provider></span><span class="pln"> </span><span class="tag"><user-service></span><span class="pln"> </span><span class="tag"><user</span><span class="pln"> </span><span class="atn">name</span><span class="pun">=</span><span class="atv">"jimi"</span><span class="pln"> </span><span class="atn">password</span><span class="pun">=</span><span class="atv">"jimispassword"</span><span class="pln"> </span><span class="atn">authorities</span><span class="pun">=</span><span class="atv">"ROLE_USER, ROLE_ADMIN"</span><span class="pln"> </span><span class="tag">/></span><span class="pln"> </span><span class="tag"><user</span><span class="pln"> </span><span class="atn">name</span><span class="pun">=</span><span class="atv">"bob"</span><span class="pln"> </span><span class="atn">password</span><span class="pun">=</span><span class="atv">"bobspassword"</span><span class="pln"> </span><span class="atn">authorities</span><span class="pun">=</span><span class="atv">"ROLE_USER"</span><span class="pln"> </span><span class="tag">/></span><span class="pln"> </span><span class="tag"></user-service></span><span class="pln"> </span><span class="tag"></authentication-provider></span><span class="pln"> </span><span class="tag"></authentication-manager></span></code></pre> </div> </div> <div class="sidebarblock"> <div class="content"> <div class="paragraph"> <p>If you are familiar with pre-namespace versions of the framework, you can probably already guess roughly what’s going on here. The <code><http></code> element is responsible for creating a <code>FilterChainProxy</code> and the filter beans which it uses. Common problems like incorrect filter ordering are no longer an issue as the filter positions are predefined.</p> </div> <div class="paragraph"> <p>The <code><authentication-provider></code> element creates a <code>DaoAuthenticationProvider</code> bean and the <code><user-service></code> element creates an <code>InMemoryDaoImpl</code>. All <code>authentication-provider</code> elements must be children of the <code><authentication-manager></code> element, which creates a <code>ProviderManager</code> and registers the authentication providers with it. You can find more detailed information on the beans that are created in the <a href="#appendix-namespace">namespace appendix</a>. It’s worth cross-checking this if you want to start understanding what the important classes in the framework are and how they are used, particularly if you want to customise things later.</p> </div> </div> </div> <div class="paragraph"> <p>The configuration above defines two users, their passwords and their roles within the application (which will be used for access control). It is also possible to load user information from a standard properties file using the <code>properties</code> attribute on <code>user-service</code>. See the section on <a href="#core-services-in-memory-service">in-memory authentication</a> for more details on the file format. Using the <code><authentication-provider></code> element means that the user information will be used by the authentication manager to process authentication requests. You can have multiple <code><authentication-provider></code> elements to define different authentication sources and each will be consulted in turn.</p> </div> <div class="paragraph"> <p>At this point you should be able to start up your application and you will be required to log in to proceed. Try it out, or try experimenting with the"tutorial" sample application that comes with the project.</p> </div> </div> <div class="sect3"> <h4 id="ns-form-and-basic"><a class="anchor" href="#ns-form-and-basic"></a>4.2.3. Form and Basic Login Options</h4> <div class="paragraph"> <p>You might be wondering where the login form came from when you were prompted to log in, since we made no mention of any HTML files or JSPs. In fact, since we didn’t explicitly set a URL for the login page, Spring Security generates one automatically, based on the features that are enabled and using standard values for the URL which processes the submitted login, the default target URL the user will be sent to after logging in and so on. However, the namespace offers plenty of support to allow you to customize these options. For example, if you want to supply your own login page, you could use:</p> </div> <div class="listingblock"> <div class="content"> <pre style="" class="prettyprint xml language-xml prettyprinted"><code><span class="tag"><http></span><span class="pln"> </span><span class="tag"><intercept-url</span><span class="pln"> </span><span class="atn">pattern</span><span class="pun">=</span><span class="atv">"/login.jsp*"</span><span class="pln"> </span><span class="atn">access</span><span class="pun">=</span><span class="atv">"IS_AUTHENTICATED_ANONYMOUSLY"</span><span class="tag">/></span><span class="pln"> </span><span class="tag"><intercept-url</span><span class="pln"> </span><span class="atn">pattern</span><span class="pun">=</span><span class="atv">"/**"</span><span class="pln"> </span><span class="atn">access</span><span class="pun">=</span><span class="atv">"ROLE_USER"</span><span class="pln"> </span><span class="tag">/></span><span class="pln"> </span><span class="tag"><form-login</span><span class="pln"> </span><span class="atn">login-page</span><span class="pun">=</span><span class="atv">'/login.jsp'</span><span class="tag">/></span><span class="pln"> </span><span class="tag"></http></span></code></pre> </div> </div> <div class="paragraph"> <p>Also note that we’ve added an extra <code>intercept-url</code> element to say that any requests for the login page should be available to anonymous users <span class="footnote">[<a id="_footnoteref_4" class="footnote" href="#_footnote_4" title="View footnote.">4</a>]</span> and also the <a href="#authz-authenticated-voter">AuthenticatedVoter</a> class for more details on how the value <code>IS_AUTHENTICATED_ANONYMOUSLY</code> is processed.]. Otherwise the request would be matched by the pattern <code>/**</code> and it wouldn’t be possible to access the login page itself! This is a common configuration error and will result in an infinite loop in the application. Spring Security will emit a warning in the log if your login page appears to be secured. It is also possible to have all requests matching a particular pattern bypass the security filter chain completely, by defining a separate <code>http</code> element for the pattern like this:</p> </div> <div class="listingblock"> <div class="content"> <pre style="" class="prettyprint xml language-xml prettyprinted"><code><span class="tag"><http</span><span class="pln"> </span><span class="atn">pattern</span><span class="pun">=</span><span class="atv">"/css/**"</span><span class="pln"> </span><span class="atn">security</span><span class="pun">=</span><span class="atv">"none"</span><span class="tag">/></span><span class="pln"> </span><span class="tag"><http</span><span class="pln"> </span><span class="atn">pattern</span><span class="pun">=</span><span class="atv">"/login.jsp*"</span><span class="pln"> </span><span class="atn">security</span><span class="pun">=</span><span class="atv">"none"</span><span class="tag">/></span><span class="pln"> </span><span class="tag"><http></span><span class="pln"> </span><span class="tag"><intercept-url</span><span class="pln"> </span><span class="atn">pattern</span><span class="pun">=</span><span class="atv">"/**"</span><span class="pln"> </span><span class="atn">access</span><span class="pun">=</span><span class="atv">"ROLE_USER"</span><span class="pln"> </span><span class="tag">/></span><span class="pln"> </span><span class="tag"><form-login</span><span class="pln"> </span><span class="atn">login-page</span><span class="pun">=</span><span class="atv">'/login.jsp'</span><span class="tag">/></span><span class="pln"> </span><span class="tag"></http></span></code></pre> </div> </div> <div class="paragraph"> <p>From Spring Security 3.1 it is now possible to use multiple <code>http</code> elements to define separate security filter chain configurations for different request patterns. If the <code>pattern</code> attribute is omitted from an <code>http</code> element, it matches all requests. Creating an unsecured pattern is a simple example of this syntax, where the pattern is mapped to an empty filter chain <span class="footnote">[<a id="_footnoteref_5" class="footnote" href="#_footnote_5" title="View footnote.">5</a>]</span>. We’ll look at this new syntax in more detail in the chapter on the <a href="#filter-chains-with-ns">Security Filter Chain</a>.</p> </div> <div class="paragraph"> <p>It’s important to realise that these unsecured requests will be completely oblivious to any Spring Security web-related configuration or additional attributes such as <code>requires-channel</code>, so you will not be able to access information on the current user or call secured methods during the request. Use <code>access='IS_AUTHENTICATED_ANONYMOUSLY'</code> as an alternative if you still want the security filter chain to be applied.</p> </div> <div class="paragraph"> <p>If you want to use basic authentication instead of form login, then change the configuration to</p> </div> <div class="listingblock"> <div class="content"> <pre style="" class="prettyprint xml language-xml prettyprinted"><code><span class="tag"><http></span><span class="pln"> </span><span class="tag"><intercept-url</span><span class="pln"> </span><span class="atn">pattern</span><span class="pun">=</span><span class="atv">"/**"</span><span class="pln"> </span><span class="atn">access</span><span class="pun">=</span><span class="atv">"ROLE_USER"</span><span class="pln"> </span><span class="tag">/></span><span class="pln"> </span><span class="tag"><http-basic</span><span class="pln"> </span><span class="tag">/></span><span class="pln"> </span><span class="tag"></http></span></code></pre> </div> </div> <div class="paragraph"> <p>Basic authentication will then take precedence and will be used to prompt for a login when a user attempts to access a protected resource. Form login is still available in this configuration if you wish to use it, for example through a login form embedded in another web page.</p> </div> <div class="sect4"> <h5 id="ns-form-target"><a class="anchor" href="#ns-form-target"></a>Setting a Default Post-Login Destination</h5> <div class="paragraph"> <p>If a form login isn’t prompted by an attempt to access a protected resource, the <code>default-target-url</code> option comes into play. This is the URL the user will be taken to after successfully logging in, and defaults to "/". You can also configure things so that the user <em>always</em> ends up at this page (regardless of whether the login was "on-demand" or they explicitly chose to log in) by setting the <code>always-use-default-target</code> attribute to "true". This is useful if your application always requires that the user starts at a "home" page, for example:</p> </div> <div class="listingblock"> <div class="content"> <pre style="" class="prettyprint xml language-xml prettyprinted"><code><span class="tag"><http</span><span class="pln"> </span><span class="atn">pattern</span><span class="pun">=</span><span class="atv">"/login.htm*"</span><span class="pln"> </span><span class="atn">security</span><span class="pun">=</span><span class="atv">"none"</span><span class="tag">/></span><span class="pln"> </span><span class="tag"><http></span><span class="pln"> </span><span class="tag"><intercept-url</span><span class="pln"> </span><span class="atn">pattern</span><span class="pun">=</span><span class="atv">'/**'</span><span class="pln"> </span><span class="atn">access</span><span class="pun">=</span><span class="atv">'ROLE_USER'</span><span class="pln"> </span><span class="tag">/></span><span class="pln"> </span><span class="tag"><form-login</span><span class="pln"> </span><span class="atn">login-page</span><span class="pun">=</span><span class="atv">'/login.htm'</span><span class="pln"> </span><span class="atn">default-target-url</span><span class="pun">=</span><span class="atv">'/home.htm'</span><span class="pln"> </span><span class="atn">always-use-default-target</span><span class="pun">=</span><span class="atv">'true'</span><span class="pln"> </span><span class="tag">/></span><span class="pln"> </span><span class="tag"></http></span></code></pre> </div> </div> <div class="paragraph"> <p>For even more control over the destination, you can use the <code>authentication-success-handler-ref</code> attribute as an alternative to <code>default-target-url</code>. The referenced bean should be an instance of <code>AuthenticationSuccessHandler</code>. You’ll find more on this in the <a href="#form-login-flow-handling">Core Filters</a> chapter and also in the namespace appendix, as well as information on how to customize the flow when authentication fails.</p> </div> </div> </div> <div class="sect3"> <h4 id="ns-logout"><a class="anchor" href="#ns-logout"></a>4.2.4. Logout Handling</h4> <div class="paragraph"> <p>The <code>logout</code> element adds support for logging out by navigating to a particular URL. The default logout URL is <code>/j_spring_security_logout</code>, but you can set it to something else using the <code>logout-url</code> attribute. More information on other available attributes may be found in the namespace appendix.</p> </div> </div> <div class="sect3"> <h4 id="ns-auth-providers"><a class="anchor" href="#ns-auth-providers"></a>4.2.5. Using other Authentication Providers</h4> <div class="paragraph"> <p>In practice you will need a more scalable source of user information than a few names added to the application context file. Most likely you will want to store your user information in something like a database or an LDAP server. LDAP namespace configuration is dealt with in the <a href="#ldap">LDAP chapter</a>, so we won’t cover it here. If you have a custom implementation of Spring Security’s <code>UserDetailsService</code>, called "myUserDetailsService" in your application context, then you can authenticate against this using</p> </div> <div class="listingblock"> <div class="content"> <pre style="" class="prettyprint xml language-xml prettyprinted"><code><span class="pln"> </span><span class="tag"><authentication-manager></span><span class="pln"> </span><span class="tag"><authentication-provider</span><span class="pln"> </span><span class="atn">user-service-ref</span><span class="pun">=</span><span class="atv">'myUserDetailsService'</span><span class="tag">/></span><span class="pln"> </span><span class="tag"></authentication-manager></span></code></pre> </div> </div> <div class="paragraph"> <p>If you want to use a database, then you can use</p> </div> <div class="listingblock"> <div class="content"> <pre style="" class="prettyprint xml language-xml prettyprinted"><code><span class="tag"><authentication-manager></span><span class="pln"> </span><span class="tag"><authentication-provider></span><span class="pln"> </span><span class="tag"><jdbc-user-service</span><span class="pln"> </span><span class="atn">data-source-ref</span><span class="pun">=</span><span class="atv">"securityDataSource"</span><span class="tag">/></span><span class="pln"> </span><span class="tag"></authentication-provider></span><span class="pln"> </span><span class="tag"></authentication-manager></span></code></pre> </div> </div> <div class="paragraph"> <p>Where "securityDataSource" is the name of a <code>DataSource</code> bean in the application context, pointing at a database containing the standard Spring Security <a href="#db_schema_users_authorities">user data tables</a>. Alternatively, you could configure a Spring Security <code>JdbcDaoImpl</code> bean and point at that using the <code>user-service-ref</code> attribute:</p> </div> <div class="listingblock"> <div class="content"> <pre style="" class="prettyprint xml language-xml prettyprinted"><code><span class="tag"><authentication-manager></span><span class="pln"> </span><span class="tag"><authentication-provider</span><span class="pln"> </span><span class="atn">user-service-ref</span><span class="pun">=</span><span class="atv">'myUserDetailsService'</span><span class="tag">/></span><span class="pln"> </span><span class="tag"></authentication-manager></span><span class="pln"> </span><span class="tag"><beans:bean</span><span class="pln"> </span><span class="atn">id</span><span class="pun">=</span><span class="atv">"myUserDetailsService"</span><span class="pln"> </span><span class="atn">class</span><span class="pun">=</span><span class="atv">"org.springframework.security.core.userdetails.jdbc.JdbcDaoImpl"</span><span class="tag">></span><span class="pln"> </span><span class="tag"><beans:property</span><span class="pln"> </span><span class="atn">name</span><span class="pun">=</span><span class="atv">"dataSource"</span><span class="pln"> </span><span class="atn">ref</span><span class="pun">=</span><span class="atv">"dataSource"</span><span class="tag">/></span><span class="pln"> </span><span class="tag"></beans:bean></span></code></pre> </div> </div> <div class="paragraph"> <p>You can also use standard <code>AuthenticationProvider</code> beans as follows</p> </div> <div class="listingblock"> <div class="content"> <pre style="" class="prettyprint xml language-xml prettyprinted"><code><span class="pln"> </span><span class="tag"><authentication-manager></span><span class="pln"> </span><span class="tag"><authentication-provider</span><span class="pln"> </span><span class="atn">ref</span><span class="pun">=</span><span class="atv">'myAuthenticationProvider'</span><span class="tag">/></span><span class="pln"> </span><span class="tag"></authentication-manager></span></code></pre> </div> </div> <div class="paragraph"> <p>where <code>myAuthenticationProvider</code> is the name of a bean in your application context which implements <code>AuthenticationProvider</code>. You can use multiple <code>authentication-provider</code> elements, in which case the providers will be queried in the order they are declared. See <a href="#ns-auth-manager">The Authentication Manager and the Namespace</a> for more on information on how the Spring Security <code>AuthenticationManager</code> is configured using the namespace.</p> </div> <div class="sect4"> <h5 id="ns-password-encoder"><a class="anchor" href="#ns-password-encoder"></a>Adding a Password Encoder</h5> <div class="paragraph"> <p>Passwords should always be encoded using a secure hashing algorithm designed for the purpose (not a standard algorithm like SHA or MD5). This is supported by the <code><password-encoder></code> element. With bcrypt encoded passwords, the original authentication provider configuration would look like this:</p> </div> <div class="listingblock"> <div class="content"> <pre style="" class="prettyprint xml language-xml prettyprinted"><code><span class="tag"><beans:bean</span><span class="pln"> </span><span class="atn">name</span><span class="pun">=</span><span class="atv">"bcryptEncoder"</span><span class="pln"> </span><span class="atn">class</span><span class="pun">=</span><span class="atv">"org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder"</span><span class="tag">/></span><span class="pln"> </span><span class="tag"><authentication-manager></span><span class="pln"> </span><span class="tag"><authentication-provider></span><span class="pln"> </span><span class="tag"><password-encoder</span><span class="pln"> </span><span class="atn">ref</span><span class="pun">=</span><span class="atv">"bcryptEncoder"</span><span class="tag">/></span><span class="pln"> </span><span class="tag"><user-service></span><span class="pln"> </span><span class="tag"><user</span><span class="pln"> </span><span class="atn">name</span><span class="pun">=</span><span class="atv">"jimi"</span><span class="pln"> </span><span class="atn">password</span><span class="pun">=</span><span class="atv">"d7e6351eaa13189a5a3641bab846c8e8c69ba39f"</span><span class="pln"> </span><span class="atn">authorities</span><span class="pun">=</span><span class="atv">"ROLE_USER, ROLE_ADMIN"</span><span class="pln"> </span><span class="tag">/></span><span class="pln"> </span><span class="tag"><user</span><span class="pln"> </span><span class="atn">name</span><span class="pun">=</span><span class="atv">"bob"</span><span class="pln"> </span><span class="atn">password</span><span class="pun">=</span><span class="atv">"4e7421b1b8765d8f9406d87e7cc6aa784c4ab97f"</span><span class="pln"> </span><span class="atn">authorities</span><span class="pun">=</span><span class="atv">"ROLE_USER"</span><span class="pln"> </span><span class="tag">/></span><span class="pln"> </span><span class="tag"></user-service></span><span class="pln"> </span><span class="tag"></authentication-provider></span><span class="pln"> </span><span class="tag"></authentication-manager></span></code></pre> </div> </div> <div class="paragraph"> <p>Bcrypt is a good choice for most cases, unless you have a legacy system which forces you to use a different algorithm. If you are using a simple hashing algorithm or, even worse, storing plain text passwords, then you should consider migrating to a more secure option like bcrypt.</p> </div> </div> </div> </div> <div class="sect2"> <h3 id="ns-web-advanced"><a class="anchor" href="#ns-web-advanced"></a>4.3. Advanced Web Features</h3> <div class="sect3"> <h4 id="ns-remember-me"><a class="anchor" href="#ns-remember-me"></a>4.3.1. Remember-Me Authentication</h4> <div class="paragraph"> <p>See the separate <a href="#remember-me">Remember-Me chapter</a> for information on remember-me namespace configuration.</p> </div> </div> <div class="sect3"> <h4 id="ns-requires-channel"><a class="anchor" href="#ns-requires-channel"></a>4.3.2. Adding HTTP/HTTPS Channel Security</h4> <div class="paragraph"> <p>If your application supports both HTTP and HTTPS, and you require that particular URLs can only be accessed over HTTPS, then this is directly supported using the <code>requires-channel</code> attribute on <code><intercept-url></code>:</p> </div> <div class="listingblock"> <div class="content"> <pre style="" class="prettyprint xml language-xml prettyprinted"><code><span class="tag"><http></span><span class="pln"> </span><span class="tag"><intercept-url</span><span class="pln"> </span><span class="atn">pattern</span><span class="pun">=</span><span class="atv">"/secure/**"</span><span class="pln"> </span><span class="atn">access</span><span class="pun">=</span><span class="atv">"ROLE_USER"</span><span class="pln"> </span><span class="atn">requires-channel</span><span class="pun">=</span><span class="atv">"https"</span><span class="tag">/></span><span class="pln"> </span><span class="tag"><intercept-url</span><span class="pln"> </span><span class="atn">pattern</span><span class="pun">=</span><span class="atv">"/**"</span><span class="pln"> </span><span class="atn">access</span><span class="pun">=</span><span class="atv">"ROLE_USER"</span><span class="pln"> </span><span class="atn">requires-channel</span><span class="pun">=</span><span class="atv">"any"</span><span class="tag">/></span><span class="pln"> ... </span><span class="tag"></http></span></code></pre> </div> </div> <div class="paragraph"> <p>With this configuration in place, if a user attempts to access anything matching the "/secure/**" pattern using HTTP, they will first be redirected to an HTTPS URL <span class="footnote">[<a id="_footnoteref_6" class="footnote" href="#_footnote_6" title="View footnote.">6</a>]</span>. The available options are "http", "https" or "any". Using the value "any" means that either HTTP or HTTPS can be used.</p> </div> <div class="paragraph"> <p>If your application uses non-standard ports for HTTP and/or HTTPS, you can specify a list of port mappings as follows:</p> </div> <div class="listingblock"> <div class="content"> <pre style="" class="prettyprint xml language-xml prettyprinted"><code><span class="tag"><http></span><span class="pln"> ... </span><span class="tag"><port-mappings></span><span class="pln"> </span><span class="tag"><port-mapping</span><span class="pln"> </span><span class="atn">http</span><span class="pun">=</span><span class="atv">"9080"</span><span class="pln"> </span><span class="atn">https</span><span class="pun">=</span><span class="atv">"9443"</span><span class="tag">/></span><span class="pln"> </span><span class="tag"></port-mappings></span><span class="pln"> </span><span class="tag"></http></span></code></pre> </div> </div> <div class="paragraph"> <p>Note that in order to be truly secure, an application should not use HTTP at all or switch between HTTP and HTTPS. It should start in HTTPS (with the user entering an HTTPS URL) and use a secure connection throughout to avoid any possibility of man-in-the-middle attacks.</p> </div> </div> <div class="sect3"> <h4 id="ns-session-mgmt"><a class="anchor" href="#ns-session-mgmt"></a>4.3.3. Session Management</h4> <div class="sect4"> <h5 id="detecting-timeouts"><a class="anchor" href="#detecting-timeouts"></a>Detecting Timeouts</h5> <div class="paragraph"> <p>You can configure Spring Security to detect the submission of an invalid session ID and redirect the user to an appropriate URL. This is achieved through the <code>session-management</code> element:</p> </div> <div class="listingblock"> <div class="content"> <pre style="" class="prettyprint xml language-xml prettyprinted"><code><span class="tag"><http></span><span class="pln"> ... </span><span class="tag"><session-management</span><span class="pln"> </span><span class="atn">invalid-session-url</span><span class="pun">=</span><span class="atv">"/invalidSession.htm"</span><span class="pln"> </span><span class="tag">/></span><span class="pln"> </span><span class="tag"></http></span></code></pre> </div> </div> <div class="paragraph"> <p>Note that if you use this mechanism to detect session timeouts, it may falsely report an error if the user logs out and then logs back in without closing the browser. This is because the session cookie is not cleared when you invalidate the session and will be resubmitted even if the user has logged out. You may be able to explicitly delete the JSESSIONID cookie on logging out, for example by using the following syntax in the logout handler:</p> </div> <div class="listingblock"> <div class="content"> <pre style="" class="prettyprint xml language-xml prettyprinted"><code><span class="tag"><http></span><span class="pln"> </span><span class="tag"><logout</span><span class="pln"> </span><span class="atn">delete-cookies</span><span class="pun">=</span><span class="atv">"JSESSIONID"</span><span class="pln"> </span><span class="tag">/></span><span class="pln"> </span><span class="tag"></http></span></code></pre> </div> </div> <div class="paragraph"> <p>Unfortunately this can’t be guaranteed to work with every servlet container, so you will need to test it in your environment</p> </div> <div class="admonitionblock note"> <table> <tbody><tr> <td class="icon"> <i class="icon-note" title="Note"></i> </td> <td class="content"> <div class="paragraph"> <p>If you are running your application behind a proxy, you may also be able to remove the session cookie by configuring the proxy server. For example, using Apache HTTPD’s mod_headers, the following directive would delete the <code>JSESSIONID</code> cookie by expiring it in the response to a logout request (assuming the application is deployed under the path <code>/tutorial</code>):</p> </div> <div class="listingblock"> <div class="content"> <pre style="" class="prettyprint xml language-xml prettyprinted"><code><span class="tag"><LocationMatch</span><span class="pln"> </span><span class="atv">"/tutorial/j_spring_security_logout"</span><span class="tag">></span><span class="pln"> Header always set Set-Cookie "JSESSIONID=;Path=/tutorial;Expires=Thu, 01 Jan 1970 00:00:00 GMT" </span><span class="tag"></LocationMatch></span></code></pre> </div> </div> </td> </tr> </tbody></table> </div> </div> <div class="sect4"> <h5 id="ns-concurrent-sessions"><a class="anchor" href="#ns-concurrent-sessions"></a>Concurrent Session Control</h5> <div class="paragraph"> <p>If you wish to place constraints on a single user’s ability to log in to your application, Spring Security supports this out of the box with the following simple additions. First you need to add the following listener to your <code>web.xml</code> file to keep Spring Security updated about session lifecycle events:</p> </div> <div class="listingblock"> <div class="content"> <pre style="" class="prettyprint xml language-xml prettyprinted"><code><span class="tag"><listener></span><span class="pln"> </span><span class="tag"><listener-class></span><span class="pln"> org.springframework.security.web.session.HttpSessionEventPublisher </span><span class="tag"></listener-class></span><span class="pln"> </span><span class="tag"></listener></span></code></pre> </div> </div> <div class="paragraph"> <p>Then add the following lines to your application context:</p> </div> <div class="listingblock"> <div class="content"> <pre style="" class="prettyprint xml language-xml prettyprinted"><code><span class="tag"><http></span><span class="pln"> ... </span><span class="tag"><session-management></span><span class="pln"> </span><span class="tag"><concurrency-control</span><span class="pln"> </span><span class="atn">max-sessions</span><span class="pun">=</span><span class="atv">"1"</span><span class="pln"> </span><span class="tag">/></span><span class="pln"> </span><span class="tag"></session-management></span><span class="pln"> </span><span class="tag"></http></span></code></pre> </div> </div> <div class="paragraph"> <p>This will prevent a user from logging in multiple times - a second login will cause the first to be invalidated. Often you would prefer to prevent a second login, in which case you can use</p> </div> <div class="listingblock"> <div class="content"> <pre style="" class="prettyprint xml language-xml prettyprinted"><code><span class="tag"><http></span><span class="pln"> ... </span><span class="tag"><session-management></span><span class="pln"> </span><span class="tag"><concurrency-control</span><span class="pln"> </span><span class="atn">max-sessions</span><span class="pun">=</span><span class="atv">"1"</span><span class="pln"> </span><span class="atn">error-if-maximum-exceeded</span><span class="pun">=</span><span class="atv">"true"</span><span class="pln"> </span><span class="tag">/></span><span class="pln"> </span><span class="tag"></session-management></span><span class="pln"> </span><span class="tag"></http></span></code></pre> </div> </div> <div class="paragraph"> <p>The second login will then be rejected. By "rejected", we mean that the user will be sent to the <code>authentication-failure-url</code> if form-based login is being used. If the second authentication takes place through another non-interactive mechanism, such as "remember-me", an "unauthorized" (401) error will be sent to the client. If instead you want to use an error page, you can add the attribute <code>session-authentication-error-url</code> to the <code>session-management</code> element.</p> </div> <div class="paragraph"> <p>If you are using a customized authentication filter for form-based login, then you have to configure concurrent session control support explicitly. More details can be found in the <a href="#session-mgmt">Session Management chapter</a>.</p> </div> </div> <div class="sect4"> <h5 id="ns-session-fixation"><a class="anchor" href="#ns-session-fixation"></a>Session Fixation Attack Protection</h5> <div class="paragraph"> <p><a href="http://en.wikipedia.org/wiki/Session_fixation">Session fixation</a> attacks are a potential risk where it is possible for a malicious attacker to create a session by accessing a site, then persuade another user to log in with the same session (by sending them a link containing the session identifier as a parameter, for example). Spring Security protects against this automatically by creating a new session or otherwise changing the session ID when a user logs in. If you don’t require this protection, or it conflicts with some other requirement, you can control the behavior using the <code>session-fixation-protection</code> attribute on <code><session-management></code>, which has four options</p> </div> <div class="ulist"> <ul> <li> <p><code>none</code> - Don’t do anything. The original session will be retained.</p> </li> <li> <p><code>newSession</code> - Create a new "clean" session, without copying the existing session data (Spring Security-related attributes will still be copied).</p> </li> <li> <p><code>migrateSession</code> - Create a new session and copy all existing session attributes to the new session. This is the default in Servlet 3.0 or older containers.</p> </li> <li> <p><code>changeSessionId</code> - Do not create a new session. Instead, use the session fixation protection provided by the Servlet container (<code>HttpServletRequest#changeSessionId()</code>). This option is only available in Servlet 3.1 (Java EE 7) and newer containers. Specifying it in older containers will result in an exception. This is the default in Servlet 3.1 and newer containers.</p> </li> </ul> </div> <div class="paragraph"> <p>When session fixation protection occurs, it results in a <code>SessionFixationProtectionEvent</code> being published in the application context. If you use <code>changeSessionId</code>, this protection will <em>also</em> result in any <code>javax.servlet.http.HttpSessionIdListener</code> s being notified, so use caution if your code listens for both events. See the <a href="#session-mgmt">Session Management</a> chapter for additional information.</p> </div> </div> </div> <div class="sect3"> <h4 id="ns-openid"><a class="anchor" href="#ns-openid"></a>4.3.4. OpenID Support</h4> <div class="paragraph"> <p>The namespace supports <a href="http://openid.net/">OpenID</a> login either instead of, or in addition to normal form-based login, with a simple change:</p> </div> <div class="listingblock"> <div class="content"> <pre style="" class="prettyprint xml language-xml prettyprinted"><code><span class="tag"><http></span><span class="pln"> </span><span class="tag"><intercept-url</span><span class="pln"> </span><span class="atn">pattern</span><span class="pun">=</span><span class="atv">"/**"</span><span class="pln"> </span><span class="atn">access</span><span class="pun">=</span><span class="atv">"ROLE_USER"</span><span class="pln"> </span><span class="tag">/></span><span class="pln"> </span><span class="tag"><openid-login</span><span class="pln"> </span><span class="tag">/></span><span class="pln"> </span><span class="tag"></http></span></code></pre> </div> </div> <div class="paragraph"> <p>You should then register yourself with an OpenID provider (such as myopenid.com), and add the user information to your in-memory <code><user-service></code> :</p> </div> <div class="listingblock"> <div class="content"> <pre style="" class="prettyprint xml language-xml prettyprinted"><code><span class="tag"><user</span><span class="pln"> </span><span class="atn">name</span><span class="pun">=</span><span class="atv">"http://jimi.hendrix.myopenid.com/"</span><span class="pln"> </span><span class="atn">authorities</span><span class="pun">=</span><span class="atv">"ROLE_USER"</span><span class="pln"> </span><span class="tag">/></span></code></pre> </div> </div> <div class="paragraph"> <p>You should be able to login using the <code>myopenid.com</code> site to authenticate. It is also possible to select a specific <code>UserDetailsService</code> bean for use OpenID by setting the <code>user-service-ref</code> attribute on the <code>openid-login</code> element. See the previous section on <a href="#ns-auth-providers">authentication providers</a> for more information. Note that we have omitted the password attribute from the above user configuration, since this set of user data is only being used to load the authorities for the user. A random password will be generate internally, preventing you from accidentally using this user data as an authentication source elsewhere in your configuration.</p> </div> <div class="sect4"> <h5 id="attribute-exchange"><a class="anchor" href="#attribute-exchange"></a>Attribute Exchange</h5> <div class="paragraph"> <p>Support for OpenID <a href="http://openid.net/specs/openid-attribute-exchange-1_0.html">attribute exchange</a>. As an example, the following configuration would attempt to retrieve the email and full name from the OpenID provider, for use by the application:</p> </div> <div class="listingblock"> <div class="content"> <pre style="" class="prettyprint xml language-xml prettyprinted"><code><span class="tag"><openid-login></span><span class="pln"> </span><span class="tag"><attribute-exchange></span><span class="pln"> </span><span class="tag"><openid-attribute</span><span class="pln"> </span><span class="atn">name</span><span class="pun">=</span><span class="atv">"email"</span><span class="pln"> </span><span class="atn">type</span><span class="pun">=</span><span class="atv">"http://axschema.org/contact/email"</span><span class="pln"> </span><span class="atn">required</span><span class="pun">=</span><span class="atv">"true"</span><span class="tag">/></span><span class="pln"> </span><span class="tag"><openid-attribute</span><span class="pln"> </span><span class="atn">name</span><span class="pun">=</span><span class="atv">"name"</span><span class="pln"> </span><span class="atn">type</span><span class="pun">=</span><span class="atv">"http://axschema.org/namePerson"</span><span class="tag">/></span><span class="pln"> </span><span class="tag"></attribute-exchange></span><span class="pln"> </span><span class="tag"></openid-login></span></code></pre> </div> </div> <div class="paragraph"> <p>The "type" of each OpenID attribute is a URI, determined by a particular schema, in this case <a href="http://axschema.org/">http://axschema.org/</a>. If an attribute must be retrieved for successful authentication, the <code>required</code> attribute can be set. The exact schema and attributes supported will depend on your OpenID provider. The attribute values are returned as part of the authentication process and can be accessed afterwards using the following code:</p> </div> <div class="listingblock"> <div class="content"> <pre style="" class="prettyprint java language-java prettyprinted"><code><span class="typ">OpenIDAuthenticationToken</span><span class="pln"> token </span><span class="pun">=</span><span class="pln"> </span><span class="pun">(</span><span class="typ">OpenIDAuthenticationToken</span><span class="pun">)</span><span class="typ">SecurityContextHolder</span><span class="pun">.</span><span class="pln">getContext</span><span class="pun">().</span><span class="pln">getAuthentication</span><span class="pun">();</span><span class="pln"> </span><span class="typ">List</span><span class="pun"><</span><span class="typ">OpenIDAttribute</span><span class="pun">></span><span class="pln"> attributes </span><span class="pun">=</span><span class="pln"> token</span><span class="pun">.</span><span class="pln">getAttributes</span><span class="pun">();</span></code></pre> </div> </div> <div class="paragraph"> <p>The <code>OpenIDAttribute</code> contains the attribute type and the retrieved value (or values in the case of multi-valued attributes). We’ll see more about how the <code>SecurityContextHolder</code> class is used when we look at core Spring Security components in the <a href="#core-components">technical overview</a> chapter. Multiple attribute exchange configurations are also be supported, if you wish to use multiple identity providers. You can supply multiple <code>attribute-exchange</code> elements, using an <code>identifier-matcher</code> attribute on each. This contains a regular expression which will be matched against the OpenID identifier supplied by the user. See the OpenID sample application in the codebase for an example configuration, providing different attribute lists for the Google, Yahoo and MyOpenID providers.</p> </div> </div> </div> <div class="sect3"> <h4 id="ns-headers"><a class="anchor" href="#ns-headers"></a>4.3.5. Response Headers</h4> <div class="paragraph"> <p>For additional information on how to customize the headers element refer to the <a href="#headers">Security HTTP Response Headers</a> section of the reference.</p> </div> </div> <div class="sect3"> <h4 id="ns-custom-filters"><a class="anchor" href="#ns-custom-filters"></a>4.3.6. Adding in Your Own Filters</h4> <div class="paragraph"> <p>If you’ve used Spring Security before, you’ll know that the framework maintains a chain of filters in order to apply its services. You may want to add your own filters to the stack at particular locations or use a Spring Security filter for which there isn’t currently a namespace configuration option (CAS, for example). Or you might want to use a customized version of a standard namespace filter, such as the <code>UsernamePasswordAuthenticationFilter</code> which is created by the <code><form-login></code> element, taking advantage of some of the extra configuration options which are available by using the bean explicitly. How can you do this with namespace configuration, since the filter chain is not directly exposed?</p> </div> <div class="paragraph"> <p>The order of the filters is always strictly enforced when using the namespace. When the application context is being created, the filter beans are sorted by the namespace handling code and the standard Spring Security filters each have an alias in the namespace and a well-known position.</p> </div> <div class="admonitionblock note"> <table> <tbody><tr> <td class="icon"> <i class="icon-note" title="Note"></i> </td> <td class="content"> <div class="paragraph"> <p>In previous versions, the sorting took place after the filter instances had been created, during post-processing of the application context. In version 3.0+ the sorting is now done at the bean metadata level, before the classes have been instantiated. This has implications for how you add your own filters to the stack as the entire filter list must be known during the parsing of the <code><http></code> element, so the syntax has changed slightly in 3.0.</p> </div> </td> </tr> </tbody></table> </div> <div class="paragraph"> <p>The filters, aliases and namespace elements/attributes which create the filters are shown in <a href="#filter-stack">Standard Filter Aliases and Ordering</a>. The filters are listed in the order in which they occur in the filter chain.</p> </div> <table id="filter-stack" class="tableblock frame-all grid-all" style="width:100%; "> <caption class="title">Table 1. Standard Filter Aliases and Ordering</caption> <colgroup> <col style="width:33%;"> <col style="width:33%;"> <col style="width:33%;"> </colgroup> <thead> <tr> <th class="tableblock halign-left valign-top">Alias</th> <th class="tableblock halign-left valign-top">Filter Class</th> <th class="tableblock halign-left valign-top">Namespace Element or Attribute</th> </tr> </thead> <tbody> <tr> <td class="tableblock halign-left valign-top"><p class="tableblock">CHANNEL_FILTER</p></td> <td class="tableblock halign-left valign-top"><p class="tableblock"><code>ChannelProcessingFilter</code></p></td> <td class="tableblock halign-left valign-top"><p class="tableblock"><code>http/intercept-url@requires-channel</code></p></td> </tr> <tr> <td class="tableblock halign-left valign-top"><p class="tableblock">SECURITY_CONTEXT_FILTER</p></td> <td class="tableblock halign-left valign-top"><p class="tableblock"><code>SecurityContextPersistenceFilter</code></p></td> <td class="tableblock halign-left valign-top"><p class="tableblock"><code>http</code></p></td> </tr> <tr> <td class="tableblock halign-left valign-top"><p class="tableblock">CONCURRENT_SESSION_FILTER</p></td> <td class="tableblock halign-left valign-top"><p class="tableblock"><code>ConcurrentSessionFilter</code></p></td> <td class="tableblock halign-left valign-top"><p class="tableblock"><code>session-management/concurrency-control</code></p></td> </tr> <tr> <td class="tableblock halign-left valign-top"><p class="tableblock">HEADERS_FILTER</p></td> <td class="tableblock halign-left valign-top"><p class="tableblock"><code>HeaderWriterFilter</code></p></td> <td class="tableblock halign-left valign-top"><p class="tableblock"><code>http/headers</code></p></td> </tr> <tr> <td class="tableblock halign-left valign-top"><p class="tableblock">CSRF_FILTER</p></td> <td class="tableblock halign-left valign-top"><p class="tableblock"><code>CsrfFilter</code></p></td> <td class="tableblock halign-left valign-top"><p class="tableblock"><code>http/csrf</code></p></td> </tr> <tr> <td class="tableblock halign-left valign-top"><p class="tableblock">LOGOUT_FILTER</p></td> <td class="tableblock halign-left valign-top"><p class="tableblock"><code>LogoutFilter</code></p></td> <td class="tableblock halign-left valign-top"><p class="tableblock"><code>http/logout</code></p></td> </tr> <tr> <td class="tableblock halign-left valign-top"><p class="tableblock">X509_FILTER</p></td> <td class="tableblock halign-left valign-top"><p class="tableblock"><code>X509AuthenticationFilter</code></p></td> <td class="tableblock halign-left valign-top"><p class="tableblock"><code>http/x509</code></p></td> </tr> <tr> <td class="tableblock halign-left valign-top"><p class="tableblock">PRE_AUTH_FILTER</p></td> <td class="tableblock halign-left valign-top"><p class="tableblock"><code>AstractPreAuthenticatedProcessingFilter</code> Subclasses</p></td> <td class="tableblock halign-left valign-top"><p class="tableblock">N/A</p></td> </tr> <tr> <td class="tableblock halign-left valign-top"><p class="tableblock">CAS_FILTER</p></td> <td class="tableblock halign-left valign-top"><p class="tableblock"><code>CasAuthenticationFilter</code></p></td> <td class="tableblock halign-left valign-top"><p class="tableblock">N/A</p></td> </tr> <tr> <td class="tableblock halign-left valign-top"><p class="tableblock">FORM_LOGIN_FILTER</p></td> <td class="tableblock halign-left valign-top"><p class="tableblock"><code>UsernamePasswordAuthenticationFilter</code></p></td> <td class="tableblock halign-left valign-top"><p class="tableblock"><code>http/form-login</code></p></td> </tr> <tr> <td class="tableblock halign-left valign-top"><p class="tableblock">BASIC_AUTH_FILTER</p></td> <td class="tableblock halign-left valign-top"><p class="tableblock"><code>BasicAuthenticationFilter</code></p></td> <td class="tableblock halign-left valign-top"><p class="tableblock"><code>http/http-basic</code></p></td> </tr> <tr> <td class="tableblock halign-left valign-top"><p class="tableblock">SERVLET_API_SUPPORT_FILTER</p></td> <td class="tableblock halign-left valign-top"><p class="tableblock"><code>SecurityContextHolderAwareRequestFilter</code></p></td> <td class="tableblock halign-left valign-top"><p class="tableblock"><code>http/@servlet-api-provision</code></p></td> </tr> <tr> <td class="tableblock halign-left valign-top"><p class="tableblock">JAAS_API_SUPPORT_FILTER</p></td> <td class="tableblock halign-left valign-top"><p class="tableblock"><code>JaasApiIntegrationFilter</code></p></td> <td class="tableblock halign-left valign-top"><p class="tableblock"><code>http/@jaas-api-provision</code></p></td> </tr> <tr> <td class="tableblock halign-left valign-top"><p class="tableblock">REMEMBER_ME_FILTER</p></td> <td class="tableblock halign-left valign-top"><p class="tableblock"><code>RememberMeAuthenticationFilter</code></p></td> <td class="tableblock halign-left valign-top"><p class="tableblock"><code>http/remember-me</code></p></td> </tr> <tr> <td class="tableblock halign-left valign-top"><p class="tableblock">ANONYMOUS_FILTER</p></td> <td class="tableblock halign-left valign-top"><p class="tableblock"><code>AnonymousAuthenticationFilter</code></p></td> <td class="tableblock halign-left valign-top"><p class="tableblock"><code>http/anonymous</code></p></td> </tr> <tr> <td class="tableblock halign-left valign-top"><p class="tableblock">SESSION_MANAGEMENT_FILTER</p></td> <td class="tableblock halign-left valign-top"><p class="tableblock"><code>SessionManagementFilter</code></p></td> <td class="tableblock halign-left valign-top"><p class="tableblock"><code>session-management</code></p></td> </tr> <tr> <td class="tableblock halign-left valign-top"><p class="tableblock">EXCEPTION_TRANSLATION_FILTER</p></td> <td class="tableblock halign-left valign-top"><p class="tableblock"><code>ExceptionTranslationFilter</code></p></td> <td class="tableblock halign-left valign-top"><p class="tableblock"><code>http</code></p></td> </tr> <tr> <td class="tableblock halign-left valign-top"><p class="tableblock">FILTER_SECURITY_INTERCEPTOR</p></td> <td class="tableblock halign-left valign-top"><p class="tableblock"><code>FilterSecurityInterceptor</code></p></td> <td class="tableblock halign-left valign-top"><p class="tableblock"><code>http</code></p></td> </tr> <tr> <td class="tableblock halign-left valign-top"><p class="tableblock">SWITCH_USER_FILTER</p></td> <td class="tableblock halign-left valign-top"><p class="tableblock"><code>SwitchUserFilter</code></p></td> <td class="tableblock halign-left valign-top"><p class="tableblock">N/A</p></td> </tr> </tbody> </table> <div class="paragraph"> <p>You can add your own filter to the stack, using the <code>custom-filter</code> element and one of these names to specify the position your filter should appear at:</p> </div> <div class="listingblock"> <div class="content"> <pre style="" class="prettyprint xml language-xml prettyprinted"><code><span class="tag"><http></span><span class="pln"> </span><span class="tag"><custom-filter</span><span class="pln"> </span><span class="atn">position</span><span class="pun">=</span><span class="atv">"FORM_LOGIN_FILTER"</span><span class="pln"> </span><span class="atn">ref</span><span class="pun">=</span><span class="atv">"myFilter"</span><span class="pln"> </span><span class="tag">/></span><span class="pln"> </span><span class="tag"></http></span><span class="pln"> </span><span class="tag"><beans:bean</span><span class="pln"> </span><span class="atn">id</span><span class="pun">=</span><span class="atv">"myFilter"</span><span class="pln"> </span><span class="atn">class</span><span class="pun">=</span><span class="atv">"com.mycompany.MySpecialAuthenticationFilter"</span><span class="tag">/></span></code></pre> </div> </div> <div class="paragraph"> <p>You can also use the <code>after</code> or <code>before</code> attributes if you want your filter to be inserted before or after another filter in the stack. The names "FIRST" and "LAST" can be used with the <code>position</code> attribute to indicate that you want your filter to appear before or after the entire stack, respectively.</p> </div> <div class="admonitionblock tip"> <table> <tbody><tr> <td class="icon"> <i class="icon-tip" title="Tip"></i> </td> <td class="content"> <div class="title">Avoiding filter position conflicts</div> <div class="paragraph"> <p>If you are inserting a custom filter which may occupy the same position as one of the standard filters created by the namespace then it’s important that you don’t include the namespace versions by mistake. Remove any elements which create filters whose functionality you want to replace.</p> </div> <div class="paragraph"> <p>Note that you can’t replace filters which are created by the use of the <code><http></code> element itself - <code>SecurityContextPersistenceFilter</code>, <code>ExceptionTranslationFilter</code> or <code>FilterSecurityInterceptor</code>. Some other filters are added by default, but you can disable them. An <code>AnonymousAuthenticationFilter</code> is added by default and unless you have <a href="#ns-session-fixation">session-fixation protection</a> disabled, a <code>SessionManagementFilter</code> will also be added to the filter chain.</p> </div> </td> </tr> </tbody></table> </div> <div class="paragraph"> <p>If you’re replacing a namespace filter which requires an authentication entry point (i.e. where the authentication process is triggered by an attempt by an unauthenticated user to access to a secured resource), you will need to add a custom entry point bean too.</p> </div> <div class="sect4"> <h5 id="ns-entry-point-ref"><a class="anchor" href="#ns-entry-point-ref"></a>Setting a Custom AuthenticationEntryPoint</h5> <div class="paragraph"> <p>If you aren’t using form login, OpenID or basic authentication through the namespace, you may want to define an authentication filter and entry point using a traditional bean syntax and link them into the namespace, as we’ve just seen. The corresponding <code>AuthenticationEntryPoint</code> can be set using the <code>entry-point-ref</code> attribute on the <code><http></code> element.</p> </div> <div class="paragraph"> <p>The CAS sample application is a good example of the use of custom beans with the namespace, including this syntax. If you aren’t familiar with authentication entry points, they are discussed in the <a href="#tech-intro-auth-entry-point">technical overview</a> chapter.</p> </div> </div> </div> </div> <div class="sect2"> <h3 id="ns-method-security"><a class="anchor" href="#ns-method-security"></a>4.4. Method Security</h3> <div class="paragraph"> <p>From version 2.0 onwards Spring Security has improved support substantially for adding security to your service layer methods. It provides support for JSR-250 annotation security as well as the framework’s original <code>@Secured</code> annotation. From 3.0 you can also make use of new <a href="#el-access">expression-based annotations</a>. You can apply security to a single bean, using the <code>intercept-methods</code> element to decorate the bean declaration, or you can secure multiple beans across the entire service layer using the AspectJ style pointcuts.</p> </div> <div class="sect3"> <h4 id="ns-global-method"><a class="anchor" href="#ns-global-method"></a>4.4.1. The <global-method-security> Element</h4> <div class="paragraph"> <p>This element is used to enable annotation-based security in your application (by setting the appropriate attributes on the element), and also to group together security pointcut declarations which will be applied across your entire application context. You should only declare one <code><global-method-security></code> element. The following declaration would enable support for Spring Security’s <code>@Secured</code>:</p> </div> <div class="listingblock"> <div class="content"> <pre style="" class="prettyprint xml language-xml prettyprinted"><code><span class="tag"><global-method-security</span><span class="pln"> </span><span class="atn">secured-annotations</span><span class="pun">=</span><span class="atv">"enabled"</span><span class="pln"> </span><span class="tag">/></span></code></pre> </div> </div> <div class="paragraph"> <p>Adding an annotation to a method (on an class or interface) would then limit the access to that method accordingly. Spring Security’s native annotation support defines a set of attributes for the method. These will be passed to the <code>AccessDecisionManager</code> for it to make the actual decision:</p> </div> <div class="listingblock"> <div class="content"> <pre style="" class="prettyprint java language-java prettyprinted"><code><span class="kwd">public</span><span class="pln"> </span><span class="kwd">interface</span><span class="pln"> </span><span class="typ">BankService</span><span class="pln"> </span><span class="pun">{</span><span class="pln"> </span><span class="lit">@Secured</span><span class="pun">(</span><span class="str">"IS_AUTHENTICATED_ANONYMOUSLY"</span><span class="pun">)</span><span class="pln"> </span><span class="kwd">public</span><span class="pln"> </span><span class="typ">Account</span><span class="pln"> readAccount</span><span class="pun">(</span><span class="typ">Long</span><span class="pln"> id</span><span class="pun">);</span><span class="pln"> </span><span class="lit">@Secured</span><span class="pun">(</span><span class="str">"IS_AUTHENTICATED_ANONYMOUSLY"</span><span class="pun">)</span><span class="pln"> </span><span class="kwd">public</span><span class="pln"> </span><span class="typ">Account</span><span class="pun">[]</span><span class="pln"> findAccounts</span><span class="pun">();</span><span class="pln"> </span><span class="lit">@Secured</span><span class="pun">(</span><span class="str">"ROLE_TELLER"</span><span class="pun">)</span><span class="pln"> </span><span class="kwd">public</span><span class="pln"> </span><span class="typ">Account</span><span class="pln"> post</span><span class="pun">(</span><span class="typ">Account</span><span class="pln"> account</span><span class="pun">,</span><span class="pln"> </span><span class="kwd">double</span><span class="pln"> amount</span><span class="pun">);</span><span class="pln"> </span><span class="pun">}</span></code></pre> </div> </div> <div class="paragraph"> <p>Support for JSR-250 annotations can be enabled using</p> </div> <div class="listingblock"> <div class="content"> <pre style="" class="prettyprint xml language-xml prettyprinted"><code><span class="tag"><global-method-security</span><span class="pln"> </span><span class="atn">jsr250-annotations</span><span class="pun">=</span><span class="atv">"enabled"</span><span class="pln"> </span><span class="tag">/></span></code></pre> </div> </div> <div class="paragraph"> <p>These are standards-based and allow simple role-based constraints to be applied but do not have the power Spring Security’s native annotations. To use the new expression-based syntax, you would use</p> </div> <div class="listingblock"> <div class="content"> <pre style="" class="prettyprint xml language-xml prettyprinted"><code><span class="tag"><global-method-security</span><span class="pln"> </span><span class="atn">pre-post-annotations</span><span class="pun">=</span><span class="atv">"enabled"</span><span class="pln"> </span><span class="tag">/></span></code></pre> </div> </div> <div class="paragraph"> <p>and the equivalent Java code would be</p> </div> <div class="listingblock"> <div class="content"> <pre style="" class="prettyprint java language-java prettyprinted"><code><span class="kwd">public</span><span class="pln"> </span><span class="kwd">interface</span><span class="pln"> </span><span class="typ">BankService</span><span class="pln"> </span><span class="pun">{</span><span class="pln"> </span><span class="lit">@PreAuthorize</span><span class="pun">(</span><span class="str">"isAnonymous()"</span><span class="pun">)</span><span class="pln"> </span><span class="kwd">public</span><span class="pln"> </span><span class="typ">Account</span><span class="pln"> readAccount</span><span class="pun">(</span><span class="typ">Long</span><span class="pln"> id</span><span class="pun">);</span><span class="pln"> </span><span class="lit">@PreAuthorize</span><span class="pun">(</span><span class="str">"isAnonymous()"</span><span class="pun">)</span><span class="pln"> </span><span class="kwd">public</span><span class="pln"> </span><span class="typ">Account</span><span class="pun">[]</span><span class="pln"> findAccounts</span><span class="pun">();</span><span class="pln"> </span><span class="lit">@PreAuthorize</span><span class="pun">(</span><span class="str">"hasAuthority('ROLE_TELLER')"</span><span class="pun">)</span><span class="pln"> </span><span class="kwd">public</span><span class="pln"> </span><span class="typ">Account</span><span class="pln"> post</span><span class="pun">(</span><span class="typ">Account</span><span class="pln"> account</span><span class="pun">,</span><span class="pln"> </span><span class="kwd">double</span><span class="pln"> amount</span><span class="pun">);</span><span class="pln"> </span><span class="pun">}</span></code></pre> </div> </div> <div class="paragraph"> <p>Expression-based annotations are a good choice if you need to define simple rules that go beyond checking the role names against the user’s list of authorities.</p> </div> <div class="admonitionblock note"> <table> <tbody><tr> <td class="icon"> <i class="icon-note" title="Note"></i> </td> <td class="content"> <div class="paragraph"> <p>The annotated methods will only be secured for instances which are defined as Spring beans (in the same application context in which method-security is enabled). If you want to secure instances which are not created by Spring (using the <code>new</code> operator, for example) then you need to use AspectJ.</p> </div> </td> </tr> </tbody></table> </div> <div class="admonitionblock note"> <table> <tbody><tr> <td class="icon"> <i class="icon-note" title="Note"></i> </td> <td class="content"> <div class="paragraph"> <p>You can enable more than one type of annotation in the same application, but only one type should be used for any interface or class as the behaviour will not be well-defined otherwise. If two annotations are found which apply to a particular method, then only one of them will be applied.</p> </div> </td> </tr> </tbody></table> </div> <div class="sect4"> <h5 id="ns-protect-pointcut"><a class="anchor" href="#ns-protect-pointcut"></a>Adding Security Pointcuts using protect-pointcut</h5> <div class="paragraph"> <p>The use of <code>protect-pointcut</code> is particularly powerful, as it allows you to apply security to many beans with only a simple declaration. Consider the following example:</p> </div> <div class="listingblock"> <div class="content"> <pre style="" class="prettyprint xml language-xml prettyprinted"><code><span class="tag"><global-method-security></span><span class="pln"> </span><span class="tag"><protect-pointcut</span><span class="pln"> </span><span class="atn">expression</span><span class="pun">=</span><span class="atv">"execution(* com.mycompany.*Service.*(..))"</span><span class="pln"> </span><span class="atn">access</span><span class="pun">=</span><span class="atv">"ROLE_USER"</span><span class="tag">/></span><span class="pln"> </span><span class="tag"></global-method-security></span></code></pre> </div> </div> <div class="paragraph"> <p>This will protect all methods on beans declared in the application context whose classes are in the <code>com.mycompany</code> package and whose class names end in "Service". Only users with the <code>ROLE_USER</code> role will be able to invoke these methods. As with URL matching, the most specific matches must come first in the list of pointcuts, as the first matching expression will be used. Security annotations take precedence over pointcuts.</p> </div> </div> </div> </div> <div class="sect2"> <h3 id="ns-access-manager"><a class="anchor" href="#ns-access-manager"></a>4.5. The Default AccessDecisionManager</h3> <div class="paragraph"> <p>This section assumes you have some knowledge of the underlying architecture for access-control within Spring Security. If you don’t you can skip it and come back to it later, as this section is only really relevant for people who need to do some customization in order to use more than simple role-based security.</p> </div> <div class="paragraph"> <p>When you use a namespace configuration, a default instance of <code>AccessDecisionManager</code> is automatically registered for you and will be used for making access decisions for method invocations and web URL access, based on the access attributes you specify in your <code>intercept-url</code> and <code>protect-pointcut</code> declarations (and in annotations if you are using annotation secured methods).</p> </div> <div class="paragraph"> <p>The default strategy is to use an <code>AffirmativeBased</code> <code>AccessDecisionManager</code> with a <code>RoleVoter</code> and an <code>AuthenticatedVoter</code>. You can find out more about these in the chapter on <a href="#authz-arch">authorization</a>.</p> </div> <div class="sect3"> <h4 id="ns-custom-access-mgr"><a class="anchor" href="#ns-custom-access-mgr"></a>4.5.1. Customizing the AccessDecisionManager</h4> <div class="paragraph"> <p>If you need to use a more complicated access control strategy then it is easy to set an alternative for both method and web security.</p> </div> <div class="paragraph"> <p>For method security, you do this by setting the <code>access-decision-manager-ref</code> attribute on <code>global-method-security</code> to the <code>id</code> of the appropriate <code>AccessDecisionManager</code> bean in the application context:</p> </div> <div class="listingblock"> <div class="content"> <pre style="" class="prettyprint xml language-xml prettyprinted"><code><span class="tag"><global-method-security</span><span class="pln"> </span><span class="atn">access-decision-manager-ref</span><span class="pun">=</span><span class="atv">"myAccessDecisionManagerBean"</span><span class="tag">></span><span class="pln"> ... </span><span class="tag"></global-method-security></span></code></pre> </div> </div> <div class="paragraph"> <p>The syntax for web security is the same, but on the <code>http</code> element:</p> </div> <div class="listingblock"> <div class="content"> <pre style="" class="prettyprint xml language-xml prettyprinted"><code><span class="tag"><http</span><span class="pln"> </span><span class="atn">access-decision-manager-ref</span><span class="pun">=</span><span class="atv">"myAccessDecisionManagerBean"</span><span class="tag">></span><span class="pln"> ... </span><span class="tag"></http></span></code></pre> </div> </div> </div> </div> <div class="sect2"> <h3 id="ns-auth-manager"><a class="anchor" href="#ns-auth-manager"></a>4.6. The Authentication Manager and the Namespace</h3> <div class="paragraph"> <p>The main interface which provides authentication services in Spring Security is the <code>AuthenticationManager</code>. This is usually an instance of Spring Security’s <code>ProviderManager</code> class, which you may already be familiar with if you’ve used the framework before. If not, it will be covered later, in the <a href="#tech-intro-authentication">technical overview chapter</a>. The bean instance is registered using the <code>authentication-manager</code> namespace element. You can’t use a custom <code>AuthenticationManager</code> if you are using either HTTP or method security through the namespace, but this should not be a problem as you have full control over the <code>AuthenticationProvider</code> s that are used.</p> </div> <div class="paragraph"> <p>You may want to register additional <code>AuthenticationProvider</code> beans with the <code>ProviderManager</code> and you can do this using the <code><authentication-provider></code> element with the <code>ref</code> attribute, where the value of the attribute is the name of the provider bean you want to add. For example:</p> </div> <div class="listingblock"> <div class="content"> <pre style="" class="prettyprint xml language-xml prettyprinted"><code><span class="tag"><authentication-manager></span><span class="pln"> </span><span class="tag"><authentication-provider</span><span class="pln"> </span><span class="atn">ref</span><span class="pun">=</span><span class="atv">"casAuthenticationProvider"</span><span class="tag">/></span><span class="pln"> </span><span class="tag"></authentication-manager></span><span class="pln"> </span><span class="tag"><bean</span><span class="pln"> </span><span class="atn">id</span><span class="pun">=</span><span class="atv">"casAuthenticationProvider"</span><span class="pln"> </span><span class="atn">class</span><span class="pun">=</span><span class="atv">"org.springframework.security.cas.authentication.CasAuthenticationProvider"</span><span class="tag">></span><span class="pln"> ... </span><span class="tag"></bean></span></code></pre> </div> </div> <div class="paragraph"> <p>Another common requirement is that another bean in the context may require a reference to the <code>AuthenticationManager</code>. You can easily register an alias for the <code>AuthenticationManager</code> and use this name elsewhere in your application context.</p> </div> <div class="listingblock"> <div class="content"> <pre style="" class="prettyprint xml language-xml prettyprinted"><code><span class="tag"><security:authentication-manager</span><span class="pln"> </span><span class="atn">alias</span><span class="pun">=</span><span class="atv">"authenticationManager"</span><span class="tag">></span><span class="pln"> ... </span><span class="tag"></security:authentication-manager></span><span class="pln"> </span><span class="tag"><bean</span><span class="pln"> </span><span class="atn">id</span><span class="pun">=</span><span class="atv">"customizedFormLoginFilter"</span><span class="pln"> </span><span class="atn">class</span><span class="pun">=</span><span class="atv">"com.somecompany.security.web.CustomFormLoginFilter"</span><span class="tag">></span><span class="pln"> </span><span class="tag"><property</span><span class="pln"> </span><span class="atn">name</span><span class="pun">=</span><span class="atv">"authenticationManager"</span><span class="pln"> </span><span class="atn">ref</span><span class="pun">=</span><span class="atv">"authenticationManager"</span><span class="tag">/></span><span class="pln"> ... </span><span class="tag"></bean></span></code></pre> </div> </div> </div> </div> </div> <div class="sect1"> <h2 id="sample-apps"><a class="anchor" href="#sample-apps"></a>5. Sample Applications</h2> <div class="sectionbody"> <div class="paragraph"> <p>There are several sample web applications that are available with the project. To avoid an overly large download, only the "tutorial" and "contacts" samples are included in the distribution zip file. The others can be built directly from the source which you can obtain as described in <a href="#get-source">the introduction</a>. It’s easy to build the project yourself and there’s more information on the project web site at <a href="http://spring.io/spring-security/">http://spring.io/spring-security/</a>. All paths referred to in this chapter are relative to the project source directory.</p> </div> <div class="sect2"> <h3 id="tutorial-sample"><a class="anchor" href="#tutorial-sample"></a>5.1. Tutorial Sample</h3> <div class="paragraph"> <p>The tutorial sample is a nice basic example to get you started. It uses simple namespace configuration throughout. The compiled application is included in the distribution zip file, ready to be deployed into your web container (<code>spring-security-samples-tutorial-3.1.x.war</code>). The <a href="#ns-form-and-basic">form-based</a> authentication mechanism is used in combination with the commonly-used <a href="#remember-me">remember-me</a> authentication provider to automatically remember the login using cookies.</p> </div> <div class="paragraph"> <p>We recommend you start with the tutorial sample, as the XML is minimal and easy to follow. Most importantly, you can easily add this one XML file (and its corresponding <code>web.xml</code> entries) to your existing application. Only when this basic integration is achieved do we suggest you attempt adding in method authorization or domain object security.</p> </div> </div> <div class="sect2"> <h3 id="contacts-sample"><a class="anchor" href="#contacts-sample"></a>5.2. Contacts</h3> <div class="paragraph"> <p>The Contacts Sample is an advanced example in that it illustrates the more powerful features of domain object access control lists (ACLs) in addition to basic application security. The application provides an interface with which the users are able to administer a simple database of contacts (the domain objects).</p> </div> <div class="paragraph"> <p>To deploy, simply copy the WAR file from Spring Security distribution into your container’s <code>webapps</code> directory. The war should be called <code>spring-security-samples-contacts-3.1.x.war</code> (the appended version number will vary depending on what release you are using).</p> </div> <div class="paragraph"> <p>After starting your container, check the application can load. Visit <a href="http://localhost:8080/contacts">http://localhost:8080/contacts</a> (or whichever URL is appropriate for your web container and the WAR you deployed).</p> </div> <div class="paragraph"> <p>Next, click "Debug". You will be prompted to authenticate, and a series of usernames and passwords are suggested on that page. Simply authenticate with any of these and view the resulting page. It should contain a success message similar to the following:</p> </div> <div class="listingblock"> <div class="content"> <pre>Security Debug Information Authentication object is of type: org.springframework.security.authentication.UsernamePasswordAuthenticationToken Authentication object as a String: org.springframework.security.authentication.UsernamePasswordAuthenticationToken@1f127853: Principal: org.springframework.security.core.userdetails.User@b07ed00: Username: rod; \ Password: [PROTECTED]; Enabled: true; AccountNonExpired: true; credentialsNonExpired: true; AccountNonLocked: true; \ Granted Authorities: ROLE_SUPERVISOR, ROLE_USER; \ Password: [PROTECTED]; Authenticated: true; \ Details: org.springframework.security.web.authentication.WebAuthenticationDetails@0: \ RemoteIpAddress: 127.0.0.1; SessionId: 8fkp8t83ohar; \ Granted Authorities: ROLE_SUPERVISOR, ROLE_USER Authentication object holds the following granted authorities: ROLE_SUPERVISOR (getAuthority(): ROLE_SUPERVISOR) ROLE_USER (getAuthority(): ROLE_USER) Success! Your web filters appear to be properly configured! </pre> </div> </div> <div class="paragraph"> <p>Once you successfully receive the above message, return to the sample application’s home page and click "Manage". You can then try out the application. Notice that only the contacts available to the currently logged on user are displayed, and only users with <code>ROLE_SUPERVISOR</code> are granted access to delete their contacts. Behind the scenes, the <code>MethodSecurityInterceptor</code> is securing the business objects.</p> </div> <div class="paragraph"> <p>The application allows you to modify the access control lists associated with different contacts. Be sure to give this a try and understand how it works by reviewing the application context XML files.</p> </div> </div> <div class="sect2"> <h3 id="ldap-sample"><a class="anchor" href="#ldap-sample"></a>5.3. LDAP Sample</h3> <div class="paragraph"> <p>The LDAP sample application provides a basic configuration and sets up both a namespace configuration and an equivalent configuration using traditional beans, both in the same application context file. This means there are actually two identical authentication providers configured in this application.</p> </div> </div> <div class="sect2"> <h3 id="openid-sample"><a class="anchor" href="#openid-sample"></a>5.4. OpenID Sample</h3> <div class="paragraph"> <p>The OpenID sample demonstrates how to use the namespace to configure OpenID and how to set up <a href="http://openid.net/specs/openid-attribute-exchange-1_0.html">attribute exchange</a> configurations for Google, Yahoo and MyOpenID identity providers (you can experiment with adding others if you wish). It uses the JQuery-based <a href="http://code.google.com/p/openid-selector/">openid-selector</a> project to provide a user-friendly login page which allows the user to easily select a provider, rather than typing in the full OpenID identifier.</p> </div> <div class="paragraph"> <p>The application differs from normal authentication scenarios in that it allows any user to access the site (provided their OpenID authentication is successful). The first time you login, you will get a "Welcome [your name]"" message. If you logout and log back in (with the same OpenID identity) then this should change to "Welcome Back". This is achieved by using a custom <code>UserDetailsService</code> which assigns a standard role to any user and stores the identities internally in a map. Obviously a real application would use a database instead. Have a look at the source form more information. This class also takes into account the fact that different attributes may be returned from different providers and builds the name with which it addresses the user accordingly.</p> </div> </div> <div class="sect2"> <h3 id="cas-sample"><a class="anchor" href="#cas-sample"></a>5.5. CAS Sample</h3> <div class="paragraph"> <p>The CAS sample requires that you run both a CAS server and CAS client. It isn’t included in the distribution so you should check out the project code as described in <a href="#get-source">the introduction</a>. You’ll find the relevant files under the <code>sample/cas</code> directory. There’s also a <code>Readme.txt</code> file in there which explains how to run both the server and the client directly from the source tree, complete with SSL support.</p> </div> </div> <div class="sect2"> <h3 id="jaas-sample"><a class="anchor" href="#jaas-sample"></a>5.6. JAAS Sample</h3> <div class="paragraph"> <p>The JAAS sample is very simple example of how to use a JAAS LoginModule with Spring Security. The provided LoginModule will successfully authenticate a user if the username equals the password otherwise a LoginException is thrown. The AuthorityGranter used in this example always grants the role ROLE_USER. The sample application also demonstrates how to run as the JAAS Subject returned by the LoginModule by setting <a href="#nsa-http-jaas-api-provision">jaas-api-provision</a> equal to "true".</p> </div> </div> <div class="sect2"> <h3 id="preauth-sample"><a class="anchor" href="#preauth-sample"></a>5.7. Pre-Authentication Sample</h3> <div class="paragraph"> <p>This sample application demonstrates how to wire up beans from the <a href="#preauth">pre-authentication</a> framework to make use of login information from a Java EE container. The user name and roles are those setup by the container.</p> </div> <div class="paragraph"> <p>The code is in <code>samples/preauth</code>.</p> </div> </div> </div> </div> <div class="sect1"> <h2 id="community"><a class="anchor" href="#community"></a>6. Spring Security Community</h2> <div class="sectionbody"> <div class="sect2"> <h3 id="jira"><a class="anchor" href="#jira"></a>6.1. Issue Tracking</h3> <div class="paragraph"> <p>Spring Security uses JIRA to manage bug reports and enhancement requests. If you find a bug, please log a report using JIRA. Do not log it on the support forum, mailing list or by emailing the project’s developers. Such approaches are ad-hoc and we prefer to manage bugs using a more formal process.</p> </div> <div class="paragraph"> <p>If possible, in your issue report please provide a JUnit test that demonstrates any incorrect behaviour. Or, better yet, provide a patch that corrects the issue. Similarly, enhancements are welcome to be logged in the issue tracker, although we only accept enhancement requests if you include corresponding unit tests. This is necessary to ensure project test coverage is adequately maintained.</p> </div> <div class="paragraph"> <p>You can access the issue tracker at <a href="http://jira.springsource.org/browse/SEC">http://jira.springsource.org/browse/SEC</a>.</p> </div> </div> <div class="sect2"> <h3 id="becoming-involved"><a class="anchor" href="#becoming-involved"></a>6.2. Becoming Involved</h3> <div class="paragraph"> <p>We welcome your involvement in the Spring Security project. There are many ways of contributing, including reading the forum and responding to questions from other people, writing new code, improving existing code, assisting with documentation, developing samples or tutorials, or simply making suggestions.</p> </div> </div> <div class="sect2"> <h3 id="further-info"><a class="anchor" href="#further-info"></a>6.3. Further Information</h3> <div class="paragraph"> <p>Questions and comments on Spring Security are welcome. You can use the Spring Community Forum web site at <a href="http://forum.springsource.org/">http://forum.springsource.org</a> to discuss Spring Security with other users of the framework. Remember to use JIRA for bug reports, as explained above.</p> </div> </div> </div> </div> <h1 id="overall-architecture" class="sect0"><a class="anchor" href="#overall-architecture"></a>Architecture and Implementation</h1> <div class="paragraph"> <p>Once you are familiar with setting up and running some namespace-configuration based applications, you may wish to develop more of an understanding of how the framework actually works behind the namespace facade. Like most software, Spring Security has certain central interfaces, classes and conceptual abstractions that are commonly used throughout the framework. In this part of the reference guide we will look at some of these and see how they work together to support authentication and access-control within Spring Security.</p> </div> <div class="sect1"> <h2 id="technical-overview"><a class="anchor" href="#technical-overview"></a>1. Technical Overview</h2> <div class="sectionbody"> <div class="sect2"> <h3 id="runtime-environment"><a class="anchor" href="#runtime-environment"></a>1.1. Runtime Environment</h3> <div class="paragraph"> <p>Spring Security 3.0 requires a Java 5.0 Runtime Environment or higher. As Spring Security aims to operate in a self-contained manner, there is no need to place any special configuration files into your Java Runtime Environment. In particular, there is no need to configure a special Java Authentication and Authorization Service (JAAS) policy file or place Spring Security into common classpath locations.</p> </div> <div class="paragraph"> <p>Similarly, if you are using an EJB Container or Servlet Container there is no need to put any special configuration files anywhere, nor include Spring Security in a server classloader. All the required files will be contained within your application.</p> </div> <div class="paragraph"> <p>This design offers maximum deployment time flexibility, as you can simply copy your target artifact (be it a JAR, WAR or EAR) from one system to another and it will immediately work.</p> </div> </div> <div class="sect2"> <h3 id="core-components"><a class="anchor" href="#core-components"></a>1.2. Core Components</h3> <div class="paragraph"> <p>In Spring Security 3.0, the contents of the <code>spring-security-core</code> jar were stripped down to the bare minimum. It no longer contains any code related to web-application security, LDAP or namespace configuration. We’ll take a look here at some of the Java types that you’ll find in the core module. They represent the building blocks of the the framework, so if you ever need to go beyond a simple namespace configuration then it’s important that you understand what they are, even if you don’t actually need to interact with them directly.</p> </div> <div class="sect3"> <h4 id="securitycontextholder-securitycontext-and-authentication-objects"><a class="anchor" href="#securitycontextholder-securitycontext-and-authentication-objects"></a>1.2.1. SecurityContextHolder, SecurityContext and Authentication Objects</h4> <div class="paragraph"> <p>The most fundamental object is <code>SecurityContextHolder</code>. This is where we store details of the present security context of the application, which includes details of the principal currently using the application. By default the <code>SecurityContextHolder</code> uses a <code>ThreadLocal</code> to store these details, which means that the security context is always available to methods in the same thread of execution, even if the security context is not explicitly passed around as an argument to those methods. Using a <code>ThreadLocal</code> in this way is quite safe if care is taken to clear the thread after the present principal’s request is processed. Of course, Spring Security takes care of this for you automatically so there is no need to worry about it.</p> </div> <div class="paragraph"> <p>Some applications aren’t entirely suitable for using a <code>ThreadLocal</code>, because of the specific way they work with threads. For example, a Swing client might want all threads in a Java Virtual Machine to use the same security context. <code>SecurityContextHolder</code> can be configured with a strategy on startup to specify how you would like the context to be stored. For a standalone application you would use the <code>SecurityContextHolder.MODE_GLOBAL</code> strategy. Other applications might want to have threads spawned by the secure thread also assume the same security identity. This is achieved by using <code>SecurityContextHolder.MODE_INHERITABLETHREADLOCAL</code>. You can change the mode from the default <code>SecurityContextHolder.MODE_THREADLOCAL</code> in two ways. The first is to set a system property, the second is to call a static method on <code>SecurityContextHolder</code>. Most applications won’t need to change from the default, but if you do, take a look at the JavaDocs for <code>SecurityContextHolder</code> to learn more.</p> </div> <div class="sect4"> <h5 id="obtaining-information-about-the-current-user"><a class="anchor" href="#obtaining-information-about-the-current-user"></a>Obtaining information about the current user</h5> <div class="paragraph"> <p>Inside the <code>SecurityContextHolder</code> we store details of the principal currently interacting with the application. Spring Security uses an <code>Authentication</code> object to represent this information. You won’t normally need to create an <code>Authentication</code> object yourself, but it is fairly common for users to query the <code>Authentication</code> object. You can use the following code block - from anywhere in your application - to obtain the name of the currently authenticated user, for example:</p> </div> <div class="listingblock"> <div class="content"> <pre style="" class="prettyprint java language-java prettyprinted"><code><span class="pln"> </span><span class="typ">Object</span><span class="pln"> principal </span><span class="pun">=</span><span class="pln"> </span><span class="typ">SecurityContextHolder</span><span class="pun">.</span><span class="pln">getContext</span><span class="pun">().</span><span class="pln">getAuthentication</span><span class="pun">().</span><span class="pln">getPrincipal</span><span class="pun">();</span><span class="pln"> </span><span class="kwd">if</span><span class="pln"> </span><span class="pun">(</span><span class="pln">principal </span><span class="kwd">instanceof</span><span class="pln"> </span><span class="typ">UserDetails</span><span class="pun">)</span><span class="pln"> </span><span class="pun">{</span><span class="pln"> </span><span class="typ">String</span><span class="pln"> username </span><span class="pun">=</span><span class="pln"> </span><span class="pun">((</span><span class="typ">UserDetails</span><span class="pun">)</span><span class="pln">principal</span><span class="pun">).</span><span class="pln">getUsername</span><span class="pun">();</span><span class="pln"> </span><span class="pun">}</span><span class="pln"> </span><span class="kwd">else</span><span class="pln"> </span><span class="pun">{</span><span class="pln"> </span><span class="typ">String</span><span class="pln"> username </span><span class="pun">=</span><span class="pln"> principal</span><span class="pun">.</span><span class="pln">toString</span><span class="pun">();</span><span class="pln"> </span><span class="pun">}</span></code></pre> </div> </div> <div class="paragraph"> <p>The object returned by the call to <code>getContext()</code> is an instance of the <code>SecurityContext</code> interface. This is the object that is kept in thread-local storage. As we’ll see below, most authentication mechanisms withing Spring Security return an instance of <code>UserDetails</code> as the principal.</p> </div> </div> </div> <div class="sect3"> <h4 id="tech-userdetailsservice"><a class="anchor" href="#tech-userdetailsservice"></a>1.2.2. The UserDetailsService</h4> <div class="paragraph"> <p>Another item to note from the above code fragment is that you can obtain a principal from the <code>Authentication</code> object. The principal is just an <code>Object</code>. Most of the time this can be cast into a <code>UserDetails</code> object. <code>UserDetails</code> is a core interface in Spring Security. It represents a principal, but in an extensible and application-specific way. Think of <code>UserDetails</code> as the adapter between your own user database and what Spring Security needs inside the <code>SecurityContextHolder</code>. Being a representation of something from your own user database, quite often you will cast the <code>UserDetails</code> to the original object that your application provided, so you can call business-specific methods (like`getEmail()<code>, `getEmployeeNumber()</code> and so on).</p> </div> <div class="paragraph"> <p>By now you’re probably wondering, so when do I provide a <code>UserDetails</code> object? How do I do that? I thought you said this thing was declarative and I didn’t need to write any Java code - what gives? The short answer is that there is a special interface called <code>UserDetailsService</code>. The only method on this interface accepts a <code>String</code>-based username argument and returns a <code>UserDetails</code>:</p> </div> <div class="listingblock"> <div class="content"> <pre style="" class="prettyprint java language-java prettyprinted"><code><span class="pln"> </span><span class="typ">UserDetails</span><span class="pln"> loadUserByUsername</span><span class="pun">(</span><span class="typ">String</span><span class="pln"> username</span><span class="pun">)</span><span class="pln"> </span><span class="kwd">throws</span><span class="pln"> </span><span class="typ">UsernameNotFoundException</span><span class="pun">;</span></code></pre> </div> </div> <div class="paragraph"> <p>This is the most common approach to loading information for a user within Spring Security and you will see it used throughout the framework whenever information on a user is required.</p> </div> <div class="paragraph"> <p>On successful authentication, <code>UserDetails</code> is used to build the <code>Authentication</code> object that is stored in the <code>SecurityContextHolder</code> (more on this <a href="#tech-intro-authentication">below</a>). The good news is that we provide a number of <code>UserDetailsService</code> implementations, including one that uses an in-memory map (<code>InMemoryDaoImpl</code>) and another that uses JDBC (<code>JdbcDaoImpl</code>). Most users tend to write their own, though, with their implementations often simply sitting on top of an existing Data Access Object (DAO) that represents their employees, customers, or other users of the application. Remember the advantage that whatever your <code>UserDetailsService</code> returns can always be obtained from the <code>SecurityContextHolder</code> using the above code fragment.</p> </div> <div class="admonitionblock note"> <table> <tbody><tr> <td class="icon"> <i class="icon-note" title="Note"></i> </td> <td class="content"> <div class="paragraph"> <p>There is often some confusion about <code>UserDetailsService</code>. It is purely a DAO for user data and performs no other function other than to supply that data to other components within the framework. In particular, it <em>does not</em> authenticate the user, which is done by the <code>AuthenticationManager</code>. In many cases it makes more sense to <a href="#core-services-authentication-manager">implement <code>AuthenticationProvider</code></a> directly if you require a custom authentication process.</p> </div> </td> </tr> </tbody></table> </div> </div> <div class="sect3"> <h4 id="tech-granted-authority"><a class="anchor" href="#tech-granted-authority"></a>1.2.3. GrantedAuthority</h4> <div class="paragraph"> <p>Besides the principal, another important method provided by <code>Authentication</code> is <code>getAuthorities()</code>. This method provides an array of <code>GrantedAuthority</code> objects. A <code>GrantedAuthority</code> is, not surprisingly, an authority that is granted to the principal. Such authorities are usually "roles", such as <code>ROLE_ADMINISTRATOR</code> or <code>ROLE_HR_SUPERVISOR</code>. These roles are later on configured for web authorization, method authorization and domain object authorization. Other parts of Spring Security are capable of interpreting these authorities, and expect them to be present. <code>GrantedAuthority</code> objects are usually loaded by the <code>UserDetailsService</code>.</p> </div> <div class="paragraph"> <p>Usually the <code>GrantedAuthority</code> objects are application-wide permissions. They are not specific to a given domain object. Thus, you wouldn’t likely have a <code>GrantedAuthority</code> to represent a permission to <code>Employee</code> object number 54, because if there are thousands of such authorities you would quickly run out of memory (or, at the very least, cause the application to take a long time to authenticate a user). Of course, Spring Security is expressly designed to handle this common requirement, but you’d instead use the project’s domain object security capabilities for this purpose.</p> </div> </div> <div class="sect3"> <h4 id="summary"><a class="anchor" href="#summary"></a>1.2.4. Summary</h4> <div class="paragraph"> <p>Just to recap, the major building blocks of Spring Security that we’ve seen so far are:</p> </div> <div class="ulist"> <ul> <li> <p><code>SecurityContextHolder</code>, to provide access to the <code>SecurityContext</code>.</p> </li> <li> <p><code>SecurityContext</code>, to hold the <code>Authentication</code> and possibly request-specific security information.</p> </li> <li> <p><code>Authentication</code>, to represent the principal in a Spring Security-specific manner.</p> </li> <li> <p><code>GrantedAuthority</code>, to reflect the application-wide permissions granted to a principal.</p> </li> <li> <p><code>UserDetails</code>, to provide the necessary information to build an Authentication object from your application’s DAOs or other source of security data.</p> </li> <li> <p><code>UserDetailsService</code>, to create a <code>UserDetails</code> when passed in a <code>String</code>-based username (or certificate ID or the like).</p> </li> </ul> </div> <div class="paragraph"> <p>Now that you’ve gained an understanding of these repeatedly-used components, let’s take a closer look at the process of authentication.</p> </div> </div> </div> <div class="sect2"> <h3 id="tech-intro-authentication"><a class="anchor" href="#tech-intro-authentication"></a>1.3. Authentication</h3> <div class="paragraph"> <p>Spring Security can participate in many different authentication environments. While we recommend people use Spring Security for authentication and not integrate with existing Container Managed Authentication, it is nevertheless supported - as is integrating with your own proprietary authentication system.</p> </div> <div class="sect3"> <h4 id="what-is-authentication-in-spring-security"><a class="anchor" href="#what-is-authentication-in-spring-security"></a>1.3.1. What is authentication in Spring Security?</h4> <div class="paragraph"> <p>Let’s consider a standard authentication scenario that everyone is familiar with.</p> </div> <div class="olist arabic"> <ol class="arabic"> <li> <p>A user is prompted to log in with a username and password.</p> </li> <li> <p>The system (successfully) verifies that the password is correct for the username.</p> </li> <li> <p>The context information for that user is obtained (their list of roles and so on).</p> </li> <li> <p>A security context is established for the user</p> </li> <li> <p>The user proceeds, potentially to perform some operation which is potentially protected by an access control mechanism which checks the required permissions for the operation against the current security context information.</p> </li> </ol> </div> <div class="paragraph"> <p>The first three items constitute the authentication process so we’ll take a look at how these take place within Spring Security.</p> </div> <div class="olist arabic"> <ol class="arabic"> <li> <p>The username and password are obtained and combined into an instance of <code>UsernamePasswordAuthenticationToken</code> (an instance of the <code>Authentication</code> interface, which we saw earlier).</p> </li> <li> <p>The token is passed to an instance of <code>AuthenticationManager</code> for validation.</p> </li> <li> <p>The <code>AuthenticationManager</code> returns a fully populated <code>Authentication</code> instance on successful authentication.</p> </li> <li> <p>The security context is established by calling <code>SecurityContextHolder.getContext().setAuthentication(...)</code>, passing in the returned authentication object.</p> </li> </ol> </div> <div class="paragraph"> <p>From that point on, the user is considered to be authenticated. Let’s look at some code as an example.</p> </div> <div class="listingblock"> <div class="content"> <pre style="" class="prettyprint java language-java prettyprinted"><code><span class="kwd">import</span><span class="pln"> org</span><span class="pun">.</span><span class="pln">springframework</span><span class="pun">.</span><span class="pln">security</span><span class="pun">.</span><span class="pln">authentication</span><span class="pun">.*;</span><span class="pln"> </span><span class="kwd">import</span><span class="pln"> org</span><span class="pun">.</span><span class="pln">springframework</span><span class="pun">.</span><span class="pln">security</span><span class="pun">.</span><span class="pln">core</span><span class="pun">.*;</span><span class="pln"> </span><span class="kwd">import</span><span class="pln"> org</span><span class="pun">.</span><span class="pln">springframework</span><span class="pun">.</span><span class="pln">security</span><span class="pun">.</span><span class="pln">core</span><span class="pun">.</span><span class="pln">authority</span><span class="pun">.</span><span class="typ">SimpleGrantedAuthority</span><span class="pun">;</span><span class="pln"> </span><span class="kwd">import</span><span class="pln"> org</span><span class="pun">.</span><span class="pln">springframework</span><span class="pun">.</span><span class="pln">security</span><span class="pun">.</span><span class="pln">core</span><span class="pun">.</span><span class="pln">context</span><span class="pun">.</span><span class="typ">SecurityContextHolder</span><span class="pun">;</span><span class="pln"> </span><span class="kwd">public</span><span class="pln"> </span><span class="kwd">class</span><span class="pln"> </span><span class="typ">AuthenticationExample</span><span class="pln"> </span><span class="pun">{</span><span class="pln"> </span><span class="kwd">private</span><span class="pln"> </span><span class="kwd">static</span><span class="pln"> </span><span class="typ">AuthenticationManager</span><span class="pln"> am </span><span class="pun">=</span><span class="pln"> </span><span class="kwd">new</span><span class="pln"> </span><span class="typ">SampleAuthenticationManager</span><span class="pun">();</span><span class="pln"> </span><span class="kwd">public</span><span class="pln"> </span><span class="kwd">static</span><span class="pln"> </span><span class="kwd">void</span><span class="pln"> main</span><span class="pun">(</span><span class="typ">String</span><span class="pun">[]</span><span class="pln"> args</span><span class="pun">)</span><span class="pln"> </span><span class="kwd">throws</span><span class="pln"> </span><span class="typ">Exception</span><span class="pln"> </span><span class="pun">{</span><span class="pln"> </span><span class="typ">BufferedReader</span><span class="pln"> in </span><span class="pun">=</span><span class="pln"> </span><span class="kwd">new</span><span class="pln"> </span><span class="typ">BufferedReader</span><span class="pun">(</span><span class="kwd">new</span><span class="pln"> </span><span class="typ">InputStreamReader</span><span class="pun">(</span><span class="typ">System</span><span class="pun">.</span><span class="pln">in</span><span class="pun">));</span><span class="pln"> </span><span class="kwd">while</span><span class="pun">(</span><span class="kwd">true</span><span class="pun">)</span><span class="pln"> </span><span class="pun">{</span><span class="pln"> </span><span class="typ">System</span><span class="pun">.</span><span class="pln">out</span><span class="pun">.</span><span class="pln">println</span><span class="pun">(</span><span class="str">"Please enter your username:"</span><span class="pun">);</span><span class="pln"> </span><span class="typ">String</span><span class="pln"> name </span><span class="pun">=</span><span class="pln"> in</span><span class="pun">.</span><span class="pln">readLine</span><span class="pun">();</span><span class="pln"> </span><span class="typ">System</span><span class="pun">.</span><span class="pln">out</span><span class="pun">.</span><span class="pln">println</span><span class="pun">(</span><span class="str">"Please enter your password:"</span><span class="pun">);</span><span class="pln"> </span><span class="typ">String</span><span class="pln"> password </span><span class="pun">=</span><span class="pln"> in</span><span class="pun">.</span><span class="pln">readLine</span><span class="pun">();</span><span class="pln"> </span><span class="kwd">try</span><span class="pln"> </span><span class="pun">{</span><span class="pln"> </span><span class="typ">Authentication</span><span class="pln"> request </span><span class="pun">=</span><span class="pln"> </span><span class="kwd">new</span><span class="pln"> </span><span class="typ">UsernamePasswordAuthenticationToken</span><span class="pun">(</span><span class="pln">name</span><span class="pun">,</span><span class="pln"> password</span><span class="pun">);</span><span class="pln"> </span><span class="typ">Authentication</span><span class="pln"> result </span><span class="pun">=</span><span class="pln"> am</span><span class="pun">.</span><span class="pln">authenticate</span><span class="pun">(</span><span class="pln">request</span><span class="pun">);</span><span class="pln"> </span><span class="typ">SecurityContextHolder</span><span class="pun">.</span><span class="pln">getContext</span><span class="pun">().</span><span class="pln">setAuthentication</span><span class="pun">(</span><span class="pln">result</span><span class="pun">);</span><span class="pln"> </span><span class="kwd">break</span><span class="pun">;</span><span class="pln"> </span><span class="pun">}</span><span class="pln"> </span><span class="kwd">catch</span><span class="pun">(</span><span class="typ">AuthenticationException</span><span class="pln"> e</span><span class="pun">)</span><span class="pln"> </span><span class="pun">{</span><span class="pln"> </span><span class="typ">System</span><span class="pun">.</span><span class="pln">out</span><span class="pun">.</span><span class="pln">println</span><span class="pun">(</span><span class="str">"Authentication failed: "</span><span class="pln"> </span><span class="pun">+</span><span class="pln"> e</span><span class="pun">.</span><span class="pln">getMessage</span><span class="pun">());</span><span class="pln"> </span><span class="pun">}</span><span class="pln"> </span><span class="pun">}</span><span class="pln"> </span><span class="typ">System</span><span class="pun">.</span><span class="pln">out</span><span class="pun">.</span><span class="pln">println</span><span class="pun">(</span><span class="str">"Successfully authenticated. Security context contains: "</span><span class="pln"> </span><span class="pun">+</span><span class="pln"> </span><span class="typ">SecurityContextHolder</span><span class="pun">.</span><span class="pln">getContext</span><span class="pun">().</span><span class="pln">getAuthentication</span><span class="pun">());</span><span class="pln"> </span><span class="pun">}</span><span class="pln"> </span><span class="pun">}</span><span class="pln"> </span><span class="kwd">class</span><span class="pln"> </span><span class="typ">SampleAuthenticationManager</span><span class="pln"> </span><span class="kwd">implements</span><span class="pln"> </span><span class="typ">AuthenticationManager</span><span class="pln"> </span><span class="pun">{</span><span class="pln"> </span><span class="kwd">static</span><span class="pln"> </span><span class="kwd">final</span><span class="pln"> </span><span class="typ">List</span><span class="pun"><</span><span class="typ">GrantedAuthority</span><span class="pun">></span><span class="pln"> AUTHORITIES </span><span class="pun">=</span><span class="pln"> </span><span class="kwd">new</span><span class="pln"> </span><span class="typ">ArrayList</span><span class="pun"><</span><span class="typ">GrantedAuthority</span><span class="pun">>();</span><span class="pln"> </span><span class="kwd">static</span><span class="pln"> </span><span class="pun">{</span><span class="pln"> AUTHORITIES</span><span class="pun">.</span><span class="pln">add</span><span class="pun">(</span><span class="kwd">new</span><span class="pln"> </span><span class="typ">SimpleGrantedAuthority</span><span class="pun">(</span><span class="str">"ROLE_USER"</span><span class="pun">));</span><span class="pln"> </span><span class="pun">}</span><span class="pln"> </span><span class="kwd">public</span><span class="pln"> </span><span class="typ">Authentication</span><span class="pln"> authenticate</span><span class="pun">(</span><span class="typ">Authentication</span><span class="pln"> auth</span><span class="pun">)</span><span class="pln"> </span><span class="kwd">throws</span><span class="pln"> </span><span class="typ">AuthenticationException</span><span class="pln"> </span><span class="pun">{</span><span class="pln"> </span><span class="kwd">if</span><span class="pln"> </span><span class="pun">(</span><span class="pln">auth</span><span class="pun">.</span><span class="pln">getName</span><span class="pun">().</span><span class="pln">equals</span><span class="pun">(</span><span class="pln">auth</span><span class="pun">.</span><span class="pln">getCredentials</span><span class="pun">()))</span><span class="pln"> </span><span class="pun">{</span><span class="pln"> </span><span class="kwd">return</span><span class="pln"> </span><span class="kwd">new</span><span class="pln"> </span><span class="typ">UsernamePasswordAuthenticationToken</span><span class="pun">(</span><span class="pln">auth</span><span class="pun">.</span><span class="pln">getName</span><span class="pun">(),</span><span class="pln"> auth</span><span class="pun">.</span><span class="pln">getCredentials</span><span class="pun">(),</span><span class="pln"> AUTHORITIES</span><span class="pun">);</span><span class="pln"> </span><span class="pun">}</span><span class="pln"> </span><span class="kwd">throw</span><span class="pln"> </span><span class="kwd">new</span><span class="pln"> </span><span class="typ">BadCredentialsException</span><span class="pun">(</span><span class="str">"Bad Credentials"</span><span class="pun">);</span><span class="pln"> </span><span class="pun">}</span><span class="pln"> </span><span class="pun">}</span></code></pre> </div> </div> <div class="paragraph"> <p>Here we have written a little program that asks the user to enter a username and password and performs the above sequence. The <code>AuthenticationManager</code> which we’ve implemented here will authenticate any user whose username and password are the same. It assigns a single role to every user. The output from the above will be something like:</p> </div> <div class="listingblock"> <div class="content"> <pre style="" class="prettyprint txt language-txt prettyprinted"><code><span class="pln"> </span><span class="typ">Please</span><span class="pln"> enter your username</span><span class="pun">:</span><span class="pln"> bob </span><span class="typ">Please</span><span class="pln"> enter your password</span><span class="pun">:</span><span class="pln"> password </span><span class="typ">Authentication</span><span class="pln"> failed</span><span class="pun">:</span><span class="pln"> </span><span class="typ">Bad</span><span class="pln"> </span><span class="typ">Credentials</span><span class="pln"> </span><span class="typ">Please</span><span class="pln"> enter your username</span><span class="pun">:</span><span class="pln"> bob </span><span class="typ">Please</span><span class="pln"> enter your password</span><span class="pun">:</span><span class="pln"> bob </span><span class="typ">Successfully</span><span class="pln"> authenticated</span><span class="pun">.</span><span class="pln"> </span><span class="typ">Security</span><span class="pln"> context contains</span><span class="pun">:</span><span class="pln"> \ org</span><span class="pun">.</span><span class="pln">springframework</span><span class="pun">.</span><span class="pln">security</span><span class="pun">.</span><span class="pln">authentication</span><span class="pun">.</span><span class="typ">UsernamePasswordAuthenticationToken@441d0230</span><span class="pun">:</span><span class="pln"> \ </span><span class="typ">Principal</span><span class="pun">:</span><span class="pln"> bob</span><span class="pun">;</span><span class="pln"> </span><span class="typ">Password</span><span class="pun">:</span><span class="pln"> </span><span class="pun">[</span><span class="pln">PROTECTED</span><span class="pun">];</span><span class="pln"> \ </span><span class="typ">Authenticated</span><span class="pun">:</span><span class="pln"> </span><span class="kwd">true</span><span class="pun">;</span><span class="pln"> </span><span class="typ">Details</span><span class="pun">:</span><span class="pln"> </span><span class="kwd">null</span><span class="pun">;</span><span class="pln"> \ </span><span class="typ">Granted</span><span class="pln"> </span><span class="typ">Authorities</span><span class="pun">:</span><span class="pln"> ROLE_USER</span></code></pre> </div> </div> <div class="paragraph"> <p>Note that you don’t normally need to write any code like this. The process will normally occur internally, in a web authentication filter for example. We’ve just included the code here to show that the question of what actually constitutes authentication in Spring Security has quite a simple answer. A user is authenticated when the <code>SecurityContextHolder</code> contains a fully populated <code>Authentication</code> object.</p> </div> </div> <div class="sect3"> <h4 id="setting-the-securitycontextholder-contents-directly"><a class="anchor" href="#setting-the-securitycontextholder-contents-directly"></a>1.3.2. Setting the SecurityContextHolder Contents Directly</h4> <div class="paragraph"> <p>In fact, Spring Security doesn’t mind how you put the <code>Authentication</code> object inside the <code>SecurityContextHolder</code>. The only critical requirement is that the <code>SecurityContextHolder</code> contains an <code>Authentication</code> which represents a principal before the <code>AbstractSecurityInterceptor</code> (which we’ll see more about later) needs to authorize a user operation.</p> </div> <div class="paragraph"> <p>You can (and many users do) write their own filters or MVC controllers to provide interoperability with authentication systems that are not based on Spring Security. For example, you might be using Container-Managed Authentication which makes the current user available from a ThreadLocal or JNDI location. Or you might work for a company that has a legacy proprietary authentication system, which is a corporate "standard" over which you have little control. In situations like this it’s quite easy to get Spring Security to work, and still provide authorization capabilities. All you need to do is write a filter (or equivalent) that reads the third-party user information from a location, build a Spring Security-specific <code>Authentication</code> object, and put it into the <code>SecurityContextHolder</code>. In this case you also need to think about things which are normally taken care of automatically by the built-in authentication infrastructure. For example, you might need to pre-emptively create an HTTP session to <a href="#tech-intro-sec-context-persistence">cache the context between requests</a>, before you write the response to the client <span class="footnote">[<a id="_footnoteref_7" class="footnote" href="#_footnote_7" title="View footnote.">7</a>]</span>.</p> </div> <div class="paragraph"> <p>If you’re wondering how the <code>AuthenticationManager</code> is implemented in a real world example, we’ll look at that in the <a href="#core-services-authentication-manager">core services chapter</a>.</p> </div> </div> </div> <div class="sect2"> <h3 id="tech-intro-web-authentication"><a class="anchor" href="#tech-intro-web-authentication"></a>1.4. Authentication in a Web Application</h3> <div class="paragraph"> <p>Now let’s explore the situation where you are using Spring Security in a web application (without <code>web.xml</code> security enabled). How is a user authenticated and the security context established?</p> </div> <div class="paragraph"> <p>Consider a typical web application’s authentication process:</p> </div> <div class="olist arabic"> <ol class="arabic"> <li> <p>You visit the home page, and click on a link.</p> </li> <li> <p>A request goes to the server, and the server decides that you’ve asked for a protected resource.</p> </li> <li> <p>As you’re not presently authenticated, the server sends back a response indicating that you must authenticate. The response will either be an HTTP response code, or a redirect to a particular web page.</p> </li> <li> <p>Depending on the authentication mechanism, your browser will either redirect to the specific web page so that you can fill out the form, or the browser will somehow retrieve your identity (via a BASIC authentication dialogue box, a cookie, a X.509 certificate etc.).</p> </li> <li> <p>The browser will send back a response to the server. This will either be an HTTP POST containing the contents of the form that you filled out, or an HTTP header containing your authentication details.</p> </li> <li> <p>Next the server will decide whether or not the presented credentials are valid. If they’re valid, the next step will happen. If they’re invalid, usually your browser will be asked to try again (so you return to step two above).</p> </li> <li> <p>The original request that you made to cause the authentication process will be retried. Hopefully you’ve authenticated with sufficient granted authorities to access the protected resource. If you have sufficient access, the request will be successful. Otherwise, you’ll receive back an HTTP error code 403, which means "forbidden".</p> </li> </ol> </div> <div class="paragraph"> <p>Spring Security has distinct classes responsible for most of the steps described above. The main participants (in the order that they are used) are the <code>ExceptionTranslationFilter</code>, an <code>AuthenticationEntryPoint</code> and an "authentication mechanism", which is responsible for calling the <code>AuthenticationManager</code> which we saw in the previous section.</p> </div> <div class="sect3"> <h4 id="exceptiontranslationfilter"><a class="anchor" href="#exceptiontranslationfilter"></a>1.4.1. ExceptionTranslationFilter</h4> <div class="paragraph"> <p><code>ExceptionTranslationFilter</code> is a Spring Security filter that has responsibility for detecting any Spring Security exceptions that are thrown. Such exceptions will generally be thrown by an <code>AbstractSecurityInterceptor</code>, which is the main provider of authorization services. We will discuss <code>AbstractSecurityInterceptor</code> in the next section, but for now we just need to know that it produces Java exceptions and knows nothing about HTTP or how to go about authenticating a principal. Instead the <code>ExceptionTranslationFilter</code> offers this service, with specific responsibility for either returning error code 403 (if the principal has been authenticated and therefore simply lacks sufficient access - as per step seven above), or launching an <code>AuthenticationEntryPoint</code> (if the principal has not been authenticated and therefore we need to go commence step three).</p> </div> </div> <div class="sect3"> <h4 id="tech-intro-auth-entry-point"><a class="anchor" href="#tech-intro-auth-entry-point"></a>1.4.2. AuthenticationEntryPoint</h4> <div class="paragraph"> <p>The <code>AuthenticationEntryPoint</code> is responsible for step three in the above list. As you can imagine, each web application will have a default authentication strategy (well, this can be configured like nearly everything else in Spring Security, but let’s keep it simple for now). Each major authentication system will have its own <code>AuthenticationEntryPoint</code> implementation, which typically performs one of the actions described in step 3.</p> </div> </div> <div class="sect3"> <h4 id="authentication-mechanism"><a class="anchor" href="#authentication-mechanism"></a>1.4.3. Authentication Mechanism</h4> <div class="paragraph"> <p>Once your browser submits your authentication credentials (either as an HTTP form post or HTTP header) there needs to be something on the server that"collects" these authentication details. By now we’re at step six in the above list. In Spring Security we have a special name for the function of collecting authentication details from a user agent (usually a web browser), referring to it as the "authentication mechanism". Examples are form-base login and Basic authentication. Once the authentication details have been collected from the user agent, an <code>Authentication</code>"request" object is built and then presented to the <code>AuthenticationManager</code>.</p> </div> <div class="paragraph"> <p>After the authentication mechanism receives back the fully-populated <code>Authentication</code> object, it will deem the request valid, put the <code>Authentication</code> into the <code>SecurityContextHolder</code>, and cause the original request to be retried (step seven above). If, on the other hand, the <code>AuthenticationManager</code> rejected the request, the authentication mechanism will ask the user agent to retry (step two above).</p> </div> </div> <div class="sect3"> <h4 id="tech-intro-sec-context-persistence"><a class="anchor" href="#tech-intro-sec-context-persistence"></a>1.4.4. Storing the SecurityContext between requests</h4> <div class="paragraph"> <p>Depending on the type of application, there may need to be a strategy in place to store the security context between user operations. In a typical web application, a user logs in once and is subsequently identified by their session Id. The server caches the principal information for the duration session. In Spring Security, the responsibility for storing the <code>SecurityContext</code> between requests falls to the <code>SecurityContextPersistenceFilter</code>, which by default stores the context as an <code>HttpSession</code> attribute between HTTP requests. It restores the context to the <code>SecurityContextHolder</code> for each request and, crucially, clears the <code>SecurityContextHolder</code> when the request completes. You shouldn’t interact directly with the <code>HttpSession</code> for security purposes. There is simply no justification for doing so - always use the <code>SecurityContextHolder</code> instead.</p> </div> <div class="paragraph"> <p>Many other types of application (for example, a stateless RESTful web service) do not use HTTP sessions and will re-authenticate on every request. However, it is still important that the <code>SecurityContextPersistenceFilter</code> is included in the chain to make sure that the <code>SecurityContextHolder</code> is cleared after each request.</p> </div> <div class="admonitionblock note"> <table> <tbody><tr> <td class="icon"> <i class="icon-note" title="Note"></i> </td> <td class="content"> <div class="paragraph"> <p>In an application which receives concurrent requests in a single session, the same <code>SecurityContext</code> instance will be shared between threads. Even though a <code>ThreadLocal</code> is being used, it is the same instance that is retrieved from the <code>HttpSession</code> for each thread. This has implications if you wish to temporarily change the context under which a thread is running. If you just use <code>SecurityContextHolder.getContext()</code>, and call <code>setAuthentication(anAuthentication)</code> on the returned context object, then the <code>Authentication</code> object will change in <em>all</em> concurrent threads which share the same <code>SecurityContext</code> instance. You can customize the behaviour of <code>SecurityContextPersistenceFilter</code> to create a completely new <code>SecurityContext</code> for each request, preventing changes in one thread from affecting another. Alternatively you can create a new instance just at the point where you temporarily change the context. The method <code>SecurityContextHolder.createEmptyContext()</code> always returns a new context instance.</p> </div> </td> </tr> </tbody></table> </div> </div> </div> <div class="sect2"> <h3 id="tech-intro-access-control"><a class="anchor" href="#tech-intro-access-control"></a>1.5. Access-Control (Authorization) in Spring Security</h3> <div class="paragraph"> <p>The main interface responsible for making access-control decisions in Spring Security is the <code>AccessDecisionManager</code>. It has a <code>decide</code> method which takes an <code>Authentication</code> object representing the principal requesting access, a "secure object" (see below) and a list of security metadata attributes which apply for the object (such as a list of roles which are required for access to be granted).</p> </div> <div class="sect3"> <h4 id="security-and-aop-advice"><a class="anchor" href="#security-and-aop-advice"></a>1.5.1. Security and AOP Advice</h4> <div class="paragraph"> <p>If you’re familiar with AOP, you’d be aware there are different types of advice available: before, after, throws and around. An around advice is very useful, because an advisor can elect whether or not to proceed with a method invocation, whether or not to modify the response, and whether or not to throw an exception. Spring Security provides an around advice for method invocations as well as web requests. We achieve an around advice for method invocations using Spring’s standard AOP support and we achieve an around advice for web requests using a standard Filter.</p> </div> <div class="paragraph"> <p>For those not familiar with AOP, the key point to understand is that Spring Security can help you protect method invocations as well as web requests. Most people are interested in securing method invocations on their services layer. This is because the services layer is where most business logic resides in current-generation Java EE applications. If you just need to secure method invocations in the services layer, Spring’s standard AOP will be adequate. If you need to secure domain objects directly, you will likely find that AspectJ is worth considering.</p> </div> <div class="paragraph"> <p>You can elect to perform method authorization using AspectJ or Spring AOP, or you can elect to perform web request authorization using filters. You can use zero, one, two or three of these approaches together. The mainstream usage pattern is to perform some web request authorization, coupled with some Spring AOP method invocation authorization on the services layer.</p> </div> </div> <div class="sect3"> <h4 id="secure-objects"><a class="anchor" href="#secure-objects"></a>1.5.2. Secure Objects and the AbstractSecurityInterceptor</h4> <div class="paragraph"> <p>So what <em>is</em> a "secure object" anyway? Spring Security uses the term to refer to any object that can have security (such as an authorization decision) applied to it. The most common examples are method invocations and web requests.</p> </div> <div class="paragraph"> <p>Each supported secure object type has its own interceptor class, which is a subclass of <code>AbstractSecurityInterceptor</code>. Importantly, by the time the <code>AbstractSecurityInterceptor</code> is called, the <code>SecurityContextHolder</code> will contain a valid <code>Authentication</code> if the principal has been authenticated.</p> </div> <div class="paragraph"> <p><code>AbstractSecurityInterceptor</code> provides a consistent workflow for handling secure object requests, typically:</p> </div> <div class="olist arabic"> <ol class="arabic"> <li> <p>Look up the "configuration attributes" associated with the present request</p> </li> <li> <p>Submitting the secure object, current <code>Authentication</code> and configuration attributes to the <code>AccessDecisionManager</code> for an authorization decision</p> </li> <li> <p>Optionally change the <code>Authentication</code> under which the invocation takes place</p> </li> <li> <p>Allow the secure object invocation to proceed (assuming access was granted)</p> </li> <li> <p>Call the <code>AfterInvocationManager</code> if configured, once the invocation has returned. If the invocation raised an exception, the <code>AfterInvocationManager</code> will not be invoked.</p> </li> </ol> </div> <div class="sect4"> <h5 id="tech-intro-config-attributes"><a class="anchor" href="#tech-intro-config-attributes"></a>What are Configuration Attributes?</h5> <div class="paragraph"> <p>A "configuration attribute" can be thought of as a String that has special meaning to the classes used by <code>AbstractSecurityInterceptor</code>. They are represented by the interface <code>ConfigAttribute</code> within the framework. They may be simple role names or have more complex meaning, depending on the how sophisticated the <code>AccessDecisionManager</code> implementation is. The <code>AbstractSecurityInterceptor</code> is configured with a <code>SecurityMetadataSource</code> which it uses to look up the attributes for a secure object. Usually this configuration will be hidden from the user. Configuration attributes will be entered as annotations on secured methods or as access attributes on secured URLs. For example, when we saw something like <code><intercept-url pattern='/secure/**' access='ROLE_A,ROLE_B'/></code> in the namespace introduction, this is saying that the configuration attributes <code>ROLE_A</code> and <code>ROLE_B</code> apply to web requests matching the given pattern. In practice, with the default <code>AccessDecisionManager</code> configuration, this means that anyone who has a <code>GrantedAuthority</code> matching either of these two attributes will be allowed access. Strictly speaking though, they are just attributes and the interpretation is dependent on the <code>AccessDecisionManager</code> implementation. The use of the prefix <code>ROLE_</code> is a marker to indicate that these attributes are roles and should be consumed by Spring Security’s`RoleVoter`. This is only relevant when a voter-based <code>AccessDecisionManager</code> is in use. We’ll see how the <code>AccessDecisionManager</code> is implemented in the <a href="#authz-arch">authorization chapter</a>.</p> </div> </div> <div class="sect4"> <h5 id="runasmanager"><a class="anchor" href="#runasmanager"></a>RunAsManager</h5> <div class="paragraph"> <p>Assuming <code>AccessDecisionManager</code> decides to allow the request, the <code>AbstractSecurityInterceptor</code> will normally just proceed with the request. Having said that, on rare occasions users may want to replace the <code>Authentication</code> inside the <code>SecurityContext</code> with a different <code>Authentication</code>, which is handled by the <code>AccessDecisionManager</code> calling a <code>RunAsManager</code>. This might be useful in reasonably unusual situations, such as if a services layer method needs to call a remote system and present a different identity. Because Spring Security automatically propagates security identity from one server to another (assuming you’re using a properly-configured RMI or HttpInvoker remoting protocol client), this may be useful.</p> </div> </div> <div class="sect4"> <h5 id="afterinvocationmanager"><a class="anchor" href="#afterinvocationmanager"></a>AfterInvocationManager</h5> <div class="paragraph"> <p>Following the secure object invocation proceeding and then returning - which may mean a method invocation completing or a filter chain proceeding - the <code>AbstractSecurityInterceptor</code> gets one final chance to handle the invocation. At this stage the <code>AbstractSecurityInterceptor</code> is interested in possibly modifying the return object. We might want this to happen because an authorization decision couldn’t be made "on the way in" to a secure object invocation. Being highly pluggable, <code>AbstractSecurityInterceptor</code> will pass control to an <code>AfterInvocationManager</code> to actually modify the object if needed. This class can even entirely replace the object, or throw an exception, or not change it in any way as it chooses. The after-invocation checks will only be executed if the invocation is successful. If an exception occurs, the additional checks will be skipped.</p> </div> <div class="paragraph"> <p><code>AbstractSecurityInterceptor</code> and its related objects are shown in <a href="#abstract-security-interceptor">Security interceptors and the "secure object" model</a></p> </div> <div id="abstract-security-interceptor" class="imageblock"> <div class="content"> <img src="Spring%20Security%20Reference_files/security-interception.png" alt="Abstract Security Interceptor"> </div> <div class="title">Figure 1. Security interceptors and the "secure object" model</div> </div> </div> <div class="sect4"> <h5 id="extending-the-secure-object-model"><a class="anchor" href="#extending-the-secure-object-model"></a>Extending the Secure Object Model</h5> <div class="paragraph"> <p>Only developers contemplating an entirely new way of intercepting and authorizing requests would need to use secure objects directly. For example, it would be possible to build a new secure object to secure calls to a messaging system. Anything that requires security and also provides a way of intercepting a call (like the AOP around advice semantics) is capable of being made into a secure object. Having said that, most Spring applications will simply use the three currently supported secure object types (AOP Alliance <code>MethodInvocation</code>, AspectJ <code>JoinPoint</code> and web request <code>FilterInvocation</code>) with complete transparency.</p> </div> </div> </div> </div> <div class="sect2"> <h3 id="localization"><a class="anchor" href="#localization"></a>1.6. Localization</h3> <div class="paragraph"> <p>Spring Security supports localization of exception messages that end users are likely to see. If your application is designed for English-speaking users, you don’t need to do anything as by default all Security Security messages are in English. If you need to support other locales, everything you need to know is contained in this section.</p> </div> <div class="paragraph"> <p>All exception messages can be localized, including messages related to authentication failures and access being denied (authorization failures). Exceptions and logging messages that are focused on developers or system deployers (including incorrect attributes, interface contract violations, using incorrect constructors, startup time validation, debug-level logging) are not localized and instead are hard-coded in English within Spring Security’s code.</p> </div> <div class="paragraph"> <p>Shipping in the <code>spring-security-core-xx.jar</code> you will find an <code>org.springframework.security</code> package that in turn contains a <code>messages.properties</code> file, as well as localized versions for some common languages. This should be referred to by your`ApplicationContext`, as Spring Security classes implement Spring’s <code>MessageSourceAware</code> interface and expect the message resolver to be dependency injected at application context startup time. Usually all you need to do is register a bean inside your application context to refer to the messages. An example is shown below:</p> </div> <div class="listingblock"> <div class="content"> <pre style="" class="prettyprint xml language-xml prettyprinted"><code><span class="tag"><bean</span><span class="pln"> </span><span class="atn">id</span><span class="pun">=</span><span class="atv">"messageSource"</span><span class="pln"> </span><span class="atn">class</span><span class="pun">=</span><span class="atv">"org.springframework.context.support.ReloadableResourceBundleMessageSource"</span><span class="tag">></span><span class="pln"> </span><span class="tag"><property</span><span class="pln"> </span><span class="atn">name</span><span class="pun">=</span><span class="atv">"basename"</span><span class="pln"> </span><span class="atn">value</span><span class="pun">=</span><span class="atv">"classpath:org/springframework/security/messages"</span><span class="tag">/></span><span class="pln"> </span><span class="tag"></bean></span></code></pre> </div> </div> <div class="paragraph"> <p>The <code>messages.properties</code> is named in accordance with standard resource bundles and represents the default language supported by Spring Security messages. This default file is in English.</p> </div> <div class="paragraph"> <p>If you wish to customize the <code>messages.properties</code> file, or support other languages, you should copy the file, rename it accordingly, and register it inside the above bean definition. There are not a large number of message keys inside this file, so localization should not be considered a major initiative. If you do perform localization of this file, please consider sharing your work with the community by logging a JIRA task and attaching your appropriately-named localized version of <code>messages.properties</code>.</p> </div> <div class="paragraph"> <p>Spring Security relies on Spring’s localization support in order to actually lookup the appropriate message. In order for this to work, you have to make sure that the locale from the incoming request is stored in Spring’s <code>org.springframework.context.i18n.LocaleContextHolder</code>. Spring MVC’s <code>DispatcherServlet</code> does this for your application automatically, but since Spring Security’s filters are invoked before this, the <code>LocaleContextHolder</code> needs to be set up to contain the correct <code>Locale</code> before the filters are called. You can either do this in a filter yourself (which must come before the Spring Security filters in`web.xml`) or you can use Spring’s <code>RequestContextFilter</code>. Please refer to the Spring Framework documentation for further details on using localization with Spring.</p> </div> <div class="paragraph"> <p>The "contacts" sample application is set up to use localized messages.</p> </div> </div> </div> </div> <div class="sect1"> <h2 id="core-services"><a class="anchor" href="#core-services"></a>2. Core Services</h2> <div class="sectionbody"> <div class="paragraph"> <p>Now that we have a high-level overview of the Spring Security architecture and its core classes, let’s take a closer look at one or two of the core interfaces and their implementations, in particular the <code>AuthenticationManager</code>, <code>UserDetailsService</code> and the <code>AccessDecisionManager</code>. These crop up regularly throughout the remainder of this document so it’s important you know how they are configured and how they operate.</p> </div> <div class="sect2"> <h3 id="core-services-authentication-manager"><a class="anchor" href="#core-services-authentication-manager"></a>2.1. The AuthenticationManager, ProviderManager and AuthenticationProvider</h3> <div class="paragraph"> <p>The <code>AuthenticationManager</code> is just an interface, so the implementation can be anything we choose, but how does it work in practice? What if we need to check multiple authentication databases or a combination of different authentication services such as a database and an LDAP server?</p> </div> <div class="paragraph"> <p>The default implementation in Spring Security is called <code>ProviderManager</code> and rather than handling the authentication request itself, it delegates to a list of configured <code>AuthenticationProvider</code> s, each of which is queried in turn to see if it can perform the authentication. Each provider will either throw an exception or return a fully populated <code>Authentication</code> object. Remember our good friends, <code>UserDetails</code> and <code>UserDetailsService</code>? If not, head back to the previous chapter and refresh your memory. The most common approach to verifying an authentication request is to load the corresponding <code>UserDetails</code> and check the loaded password against the one that has been entered by the user. This is the approach used by the <code>DaoAuthenticationProvider</code> (see below). The loaded <code>UserDetails</code> object - and particularly the <code>GrantedAuthority</code> s it contains - will be used when building the fully populated <code>Authentication</code> object which is returned from a successful authentication and stored in the <code>SecurityContext</code>.</p> </div> <div class="paragraph"> <p>If you are using the namespace, an instance of <code>ProviderManager</code> is created and maintained internally, and you add providers to it by using the namespace authentication provider elements (see <a href="#ns-auth-manager">the namespace chapter</a>). In this case, you should not declare a <code>ProviderManager</code> bean in your application context. However, if you are not using the namespace then you would declare it like so:</p> </div> <div class="listingblock"> <div class="content"> <pre style="" class="prettyprint xml language-xml prettyprinted"><code><span class="pln"> </span><span class="tag"><bean</span><span class="pln"> </span><span class="atn">id</span><span class="pun">=</span><span class="atv">"authenticationManager"</span><span class="pln"> </span><span class="atn">class</span><span class="pun">=</span><span class="atv">"org.springframework.security.authentication.ProviderManager"</span><span class="tag">></span><span class="pln"> </span><span class="tag"><property</span><span class="pln"> </span><span class="atn">name</span><span class="pun">=</span><span class="atv">"providers"</span><span class="tag">></span><span class="pln"> </span><span class="tag"><list></span><span class="pln"> </span><span class="tag"><ref</span><span class="pln"> </span><span class="atn">local</span><span class="pun">=</span><span class="atv">"daoAuthenticationProvider"</span><span class="tag">/></span><span class="pln"> </span><span class="tag"><ref</span><span class="pln"> </span><span class="atn">local</span><span class="pun">=</span><span class="atv">"anonymousAuthenticationProvider"</span><span class="tag">/></span><span class="pln"> </span><span class="tag"><ref</span><span class="pln"> </span><span class="atn">local</span><span class="pun">=</span><span class="atv">"ldapAuthenticationProvider"</span><span class="tag">/></span><span class="pln"> </span><span class="tag"></list></span><span class="pln"> </span><span class="tag"></property></span><span class="pln"> </span><span class="tag"></bean></span></code></pre> </div> </div> <div class="paragraph"> <p>In the above example we have three providers. They are tried in the order shown (which is implied by the use of a <code>List</code>), with each provider able to attempt authentication, or skip authentication by simply returning <code>null</code>. If all implementations return null, the <code>ProviderManager</code> will throw a <code>ProviderNotFoundException</code>. If you’re interested in learning more about chaining providers, please refer to the <code>ProviderManager</code> JavaDocs.</p> </div> <div class="paragraph"> <p>Authentication mechanisms such as a web form-login processing filter are injected with a reference to the <code>ProviderManager</code> and will call it to handle their authentication requests. The providers you require will sometimes be interchangeable with the authentication mechanisms, while at other times they will depend on a specific authentication mechanism. For example, <code>DaoAuthenticationProvider</code> and <code>LdapAuthenticationProvider</code> are compatible with any mechanism which submits a simple username/password authentication request and so will work with form-based logins or HTTP Basic authentication. On the other hand, some authentication mechanisms create an authentication request object which can only be interpreted by a single type of <code>AuthenticationProvider</code>. An example of this would be JA-SIG CAS, which uses the notion of a service ticket and so can therefore only be authenticated by a <code>CasAuthenticationProvider</code>. You needn’t be too concerned about this, because if you forget to register a suitable provider, you’ll simply receive a <code>ProviderNotFoundException</code> when an attempt to authenticate is made.</p> </div> <div class="sect3"> <h4 id="core-services-erasing-credentials"><a class="anchor" href="#core-services-erasing-credentials"></a>2.1.1. Erasing Credentials on Successful Authentication</h4> <div class="paragraph"> <p>By default (from Spring Security 3.1 onwards) the <code>ProviderManager</code> will attempt to clear any sensitive credentials information from the <code>Authentication</code> object which is returned by a successful authentication request. This prevents information like passwords being retained longer than necessary.</p> </div> <div class="paragraph"> <p>This may cause issues when you are using a cache of user objects, for example, to improve performance in a stateless application. If the <code>Authentication</code> contains a reference to an object in the cache (such as a <code>UserDetails</code> instance) and this has its credentials removed, then it will no longer be possible to authenticate against the cached value. You need to take this into account if you are using a cache. An obvious solution is to make a copy of the object first, either in the cache implementation or in the <code>AuthenticationProvider</code> which creates the returned <code>Authentication</code> object. Alternatively, you can disable the <code>eraseCredentialsAfterAuthentication</code> property on <code>ProviderManager</code>. See the Javadoc for more information.</p> </div> </div> <div class="sect3"> <h4 id="core-services-dao-provider"><a class="anchor" href="#core-services-dao-provider"></a>2.1.2. DaoAuthenticationProvider</h4> <div class="paragraph"> <p>The simplest <code>AuthenticationProvider</code> implemented by Spring Security is <code>DaoAuthenticationProvider</code>, which is also one of the earliest supported by the framework. It leverages a <code>UserDetailsService</code> (as a DAO) in order to lookup the username, password and <code>GrantedAuthority</code> s. It authenticates the user simply by comparing the password submitted in a <code>UsernamePasswordAuthenticationToken</code> against the one loaded by the <code>UserDetailsService</code>. Configuring the provider is quite simple:</p> </div> <div class="listingblock"> <div class="content"> <pre style="" class="prettyprint xml language-xml prettyprinted"><code><span class="pln"> </span><span class="tag"><bean</span><span class="pln"> </span><span class="atn">id</span><span class="pun">=</span><span class="atv">"daoAuthenticationProvider"</span><span class="pln"> </span><span class="atn">class</span><span class="pun">=</span><span class="atv">"org.springframework.security.authentication.dao.DaoAuthenticationProvider"</span><span class="tag">></span><span class="pln"> </span><span class="tag"><property</span><span class="pln"> </span><span class="atn">name</span><span class="pun">=</span><span class="atv">"userDetailsService"</span><span class="pln"> </span><span class="atn">ref</span><span class="pun">=</span><span class="atv">"inMemoryDaoImpl"</span><span class="tag">/></span><span class="pln"> </span><span class="tag"><property</span><span class="pln"> </span><span class="atn">name</span><span class="pun">=</span><span class="atv">"passwordEncoder"</span><span class="pln"> </span><span class="atn">ref</span><span class="pun">=</span><span class="atv">"passwordEncoder"</span><span class="tag">/></span><span class="pln"> </span><span class="tag"></bean></span></code></pre> </div> </div> <div class="paragraph"> <p>The <code>PasswordEncoder</code> is optional. A <code>PasswordEncoder</code> provides encoding and decoding of passwords presented in the <code>UserDetails</code> object that is returned from the configured <code>UserDetailsService</code>. This will be discussed in more detail <a href="#core-services-password-encoding">below</a>.</p> </div> </div> </div> <div class="sect2"> <h3 id="userdetailsservice-implementations"><a class="anchor" href="#userdetailsservice-implementations"></a>2.2. UserDetailsService Implementations</h3> <div class="paragraph"> <p>As mentioned in the earlier in this reference guide, most authentication providers take advantage of the <code>UserDetails</code> and <code>UserDetailsService</code> interfaces. Recall that the contract for <code>UserDetailsService</code> is a single method:</p> </div> <div class="listingblock"> <div class="content"> <pre style="" class="prettyprint java language-java prettyprinted"><code><span class="typ">UserDetails</span><span class="pln"> loadUserByUsername</span><span class="pun">(</span><span class="typ">String</span><span class="pln"> username</span><span class="pun">)</span><span class="pln"> </span><span class="kwd">throws</span><span class="pln"> </span><span class="typ">UsernameNotFoundException</span><span class="pun">;</span></code></pre> </div> </div> <div class="paragraph"> <p>The returned <code>UserDetails</code> is an interface that provides getters that guarantee non-null provision of authentication information such as the username, password, granted authorities and whether the user account is enabled or disabled. Most authentication providers will use a`UserDetailsService`, even if the username and password are not actually used as part of the authentication decision. They may use the returned <code>UserDetails</code> object just for its <code>GrantedAuthority</code> information, because some other system (like LDAP or X.509 or CAS etc) has undertaken the responsibility of actually validating the credentials.</p> </div> <div class="paragraph"> <p>Given <code>UserDetailsService</code> is so simple to implement, it should be easy for users to retrieve authentication information using a persistence strategy of their choice. Having said that, Spring Security does include a couple of useful base implementations, which we’ll look at below.</p> </div> <div class="sect3"> <h4 id="core-services-in-memory-service"><a class="anchor" href="#core-services-in-memory-service"></a>2.2.1. In-Memory Authentication</h4> <div class="paragraph"> <p>Is easy to use create a custom <code>UserDetailsService</code> implementation that extracts information from a persistence engine of choice, but many applications do not require such complexity. This is particularly true if you’re building a prototype application or just starting integrating Spring Security, when you don’t really want to spend time configuring databases or writing <code>UserDetailsService</code> implementations. For this sort of situation, a simple option is to use the <code>user-service</code> element from the security <a href="#ns-minimal">namespace</a>:</p> </div> <div class="listingblock"> <div class="content"> <pre style="" class="prettyprint xml language-xml prettyprinted"><code><span class="tag"><user-service</span><span class="pln"> </span><span class="atn">id</span><span class="pun">=</span><span class="atv">"userDetailsService"</span><span class="tag">></span><span class="pln"> </span><span class="tag"><user</span><span class="pln"> </span><span class="atn">name</span><span class="pun">=</span><span class="atv">"jimi"</span><span class="pln"> </span><span class="atn">password</span><span class="pun">=</span><span class="atv">"jimispassword"</span><span class="pln"> </span><span class="atn">authorities</span><span class="pun">=</span><span class="atv">"ROLE_USER, ROLE_ADMIN"</span><span class="pln"> </span><span class="tag">/></span><span class="pln"> </span><span class="tag"><user</span><span class="pln"> </span><span class="atn">name</span><span class="pun">=</span><span class="atv">"bob"</span><span class="pln"> </span><span class="atn">password</span><span class="pun">=</span><span class="atv">"bobspassword"</span><span class="pln"> </span><span class="atn">authorities</span><span class="pun">=</span><span class="atv">"ROLE_USER"</span><span class="pln"> </span><span class="tag">/></span><span class="pln"> </span><span class="tag"></user-service></span></code></pre> </div> </div> <div class="paragraph"> <p>This also supports the use of an external properties file:</p> </div> <div class="listingblock"> <div class="content"> <pre style="" class="prettyprint xml language-xml prettyprinted"><code><span class="tag"><user-service</span><span class="pln"> </span><span class="atn">id</span><span class="pun">=</span><span class="atv">"userDetailsService"</span><span class="pln"> </span><span class="atn">properties</span><span class="pun">=</span><span class="atv">"users.properties"</span><span class="tag">/></span></code></pre> </div> </div> <div class="paragraph"> <p>The properties file should contain entries in the form</p> </div> <div class="listingblock"> <div class="content"> <pre style="" class="prettyprint txt language-txt prettyprinted"><code><span class="pln">username</span><span class="pun">=</span><span class="pln">password</span><span class="pun">,</span><span class="pln">grantedAuthority</span><span class="pun">[,</span><span class="pln">grantedAuthority</span><span class="pun">][,</span><span class="pln">enabled</span><span class="pun">|</span><span class="pln">disabled</span><span class="pun">]</span></code></pre> </div> </div> <div class="paragraph"> <p>For example</p> </div> <div class="listingblock"> <div class="content"> <pre style="" class="prettyprint txt language-txt prettyprinted"><code><span class="pln">jimi</span><span class="pun">=</span><span class="pln">jimispassword</span><span class="pun">,</span><span class="pln">ROLE_USER</span><span class="pun">,</span><span class="pln">ROLE_ADMIN</span><span class="pun">,</span><span class="pln">enabled bob</span><span class="pun">=</span><span class="pln">bobspassword</span><span class="pun">,</span><span class="pln">ROLE_USER</span><span class="pun">,</span><span class="pln">enabled</span></code></pre> </div> </div> </div> <div class="sect3"> <h4 id="core-services-jdbc-user-service"><a class="anchor" href="#core-services-jdbc-user-service"></a>2.2.2. JdbcDaoImpl</h4> <div class="paragraph"> <p>Spring Security also includes a <code>UserDetailsService</code> that can obtain authentication information from a JDBC data source. Internally Spring JDBC is used, so it avoids the complexity of a fully-featured object relational mapper (ORM) just to store user details. If your application does use an ORM tool, you might prefer to write a custom <code>UserDetailsService</code> to reuse the mapping files you’ve probably already created. Returning to <code>JdbcDaoImpl</code>, an example configuration is shown below:</p> </div> <div class="listingblock"> <div class="content"> <pre style="" class="prettyprint xml language-xml prettyprinted"><code><span class="tag"><bean</span><span class="pln"> </span><span class="atn">id</span><span class="pun">=</span><span class="atv">"dataSource"</span><span class="pln"> </span><span class="atn">class</span><span class="pun">=</span><span class="atv">"org.springframework.jdbc.datasource.DriverManagerDataSource"</span><span class="tag">></span><span class="pln"> </span><span class="tag"><property</span><span class="pln"> </span><span class="atn">name</span><span class="pun">=</span><span class="atv">"driverClassName"</span><span class="pln"> </span><span class="atn">value</span><span class="pun">=</span><span class="atv">"org.hsqldb.jdbcDriver"</span><span class="tag">/></span><span class="pln"> </span><span class="tag"><property</span><span class="pln"> </span><span class="atn">name</span><span class="pun">=</span><span class="atv">"url"</span><span class="pln"> </span><span class="atn">value</span><span class="pun">=</span><span class="atv">"jdbc:hsqldb:hsql://localhost:9001"</span><span class="tag">/></span><span class="pln"> </span><span class="tag"><property</span><span class="pln"> </span><span class="atn">name</span><span class="pun">=</span><span class="atv">"username"</span><span class="pln"> </span><span class="atn">value</span><span class="pun">=</span><span class="atv">"sa"</span><span class="tag">/></span><span class="pln"> </span><span class="tag"><property</span><span class="pln"> </span><span class="atn">name</span><span class="pun">=</span><span class="atv">"password"</span><span class="pln"> </span><span class="atn">value</span><span class="pun">=</span><span class="atv">""</span><span class="tag">/></span><span class="pln"> </span><span class="tag"></bean></span><span class="pln"> </span><span class="tag"><bean</span><span class="pln"> </span><span class="atn">id</span><span class="pun">=</span><span class="atv">"userDetailsService"</span><span class="pln"> </span><span class="atn">class</span><span class="pun">=</span><span class="atv">"org.springframework.security.core.userdetails.jdbc.JdbcDaoImpl"</span><span class="tag">></span><span class="pln"> </span><span class="tag"><property</span><span class="pln"> </span><span class="atn">name</span><span class="pun">=</span><span class="atv">"dataSource"</span><span class="pln"> </span><span class="atn">ref</span><span class="pun">=</span><span class="atv">"dataSource"</span><span class="tag">/></span><span class="pln"> </span><span class="tag"></bean></span></code></pre> </div> </div> <div class="paragraph"> <p>You can use different relational database management systems by modifying the <code>DriverManagerDataSource</code> shown above. You can also use a global data source obtained from JNDI, as with any other Spring configuration.</p> </div> <div class="sect4"> <h5 id="authority-groups"><a class="anchor" href="#authority-groups"></a>Authority Groups</h5> <div class="paragraph"> <p>By default, <code>JdbcDaoImpl</code> loads the authorities for a single user with the assumption that the authorities are mapped directly to users (see the <a href="#appendix-schema">database schema appendix</a>). An alternative approach is to partition the authorities into groups and assign groups to the user. Some people prefer this approach as a means of administering user rights. See the <code>JdbcDaoImpl</code> Javadoc for more information on how to enable the use of group authorities. The group schema is also included in the appendix.</p> </div> </div> </div> </div> <div class="sect2"> <h3 id="core-services-password-encoding"><a class="anchor" href="#core-services-password-encoding"></a>2.3. Password Encoding</h3> <div class="paragraph"> <p>Spring Security’s <code>PasswordEncoder</code> interface is used to support the use of passwords which are encoded in some way in persistent storage. You should never store passwords in plain text. Always use a one-way password hashing algorithm such as bcrypt which uses a built-in salt value which is different for each stored password. Do not use a plain hash function such as MD5 or SHA, or even a salted version. Bcrypt is deliberately designed to be slow and to hinder offline password cracking, whereas standard hash algorithms are fast and can easily be used to test thousands of passwords in parallel on custom hardware. You might think this doesn’t apply to you since your password database is secure and offline attacks aren’t a risk. If so, do some research and read up on all the high-profile sites which have been compromised in this way and have been pilloried for storing their passwords insecurely. It’s best to be on the safe side. Using <code>org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder"</code> is a good choice for security. There are also compatible implementations in other common programming languages so it a good choice for interoperability too.</p> </div> <div class="paragraph"> <p>If you are using a legacy system which already has hashed passwords, then you will need to use an encoder which matches your current algorithm, at least until you can migrate your users to a more secure scheme (usually this will involve asking the user to set a new password, since hashes are irreversible). Spring Security has a package containing legacy password encoding implementation, namely, <code>org.springframework.security.authentication.encoding</code>. The <code>DaoAuthenticationProvider</code> can be injected with either the new or legacy <code>PasswordEncoder</code> types.</p> </div> <div class="sect3"> <h4 id="what-is-a-hash"><a class="anchor" href="#what-is-a-hash"></a>2.3.1. What is a hash?</h4> <div class="paragraph"> <p>Password hashing is not unique to Spring Security but is a common source of confusion for users who are not familiar with the concept. A hash (or digest) algorithm is a one-way function which produces a piece of fixed-length output data (the hash) from some input data, such as a password. As an example, the MD5 hash of the string "password" (in hexadecimal) is</p> </div> <div class="listingblock"> <div class="content"> <pre style="" class="prettyprint txt language-txt prettyprinted"><code><span class="lit">5f4dcc3b5aa765d61d8327deb882cf99</span></code></pre> </div> </div> <div class="paragraph"> <p>A hash is "one-way" in the sense that it is very difficult (effectively impossible) to obtain the original input given the hash value, or indeed any possible input which would produce that hash value. This property makes hash values very useful for authentication purposes. They can be stored in your user database as an alternative to plaintext passwords and even if the values are compromised they do not immediately reveal a password which can be used to login. Note that this also means you have no way of recovering the password once it is encoded.</p> </div> </div> <div class="sect3"> <h4 id="adding-salt-to-a-hash"><a class="anchor" href="#adding-salt-to-a-hash"></a>2.3.2. Adding Salt to a Hash</h4> <div class="paragraph"> <p>One potential problem with the use of password hashes that it is relatively easy to get round the one-way property of the hash if a common word is used for the input. People tend to choose similar passwords and huge dictionaries of these from previously hacked sites are available online. For example, if you search for the hash value <code>5f4dcc3b5aa765d61d8327deb882cf99</code> using google, you will quickly find the original word "password". In a similar way, an attacker can build a dictionary of hashes from a standard word list and use this to lookup the original password. One way to help prevent this is to have a suitably strong password policy to try to prevent common words from being used. Another is to use a"salt" when calculating the hashes. This is an additional string of known data for each user which is combined with the password before calculating the hash. Ideally the data should be as random as possible, but in practice any salt value is usually preferable to none. Using a salt means that an attacker has to build a separate dictionary of hashes for each salt value, making the attack more complicated (but not impossible).</p> </div> <div class="paragraph"> <p>Bcrypt automatically generates a random salt value for each password when it is encoded, and stores it in the bcrypt string in a standard format.</p> </div> <div class="admonitionblock note"> <table> <tbody><tr> <td class="icon"> <i class="icon-note" title="Note"></i> </td> <td class="content"> <div class="paragraph"> <p>The legacy approach to handling salt was to inject a <code>SaltSource</code> into the <code>DaoAuthenticationProvider</code>, which would obtain a salt value for a particular user and pass it to the <code>PasswordEncoder</code>. Using bcrypt means you don’t have worry about the details of salt handling (such as where the the value is stored), as it is all done internally. So we’d strongly recommend you use bcrypt unless you already have a system in place which stores the salt separately.</p> </div> </td> </tr> </tbody></table> </div> </div> <div class="sect3"> <h4 id="hashing-and-authentication"><a class="anchor" href="#hashing-and-authentication"></a>2.3.3. Hashing and Authentication</h4> <div class="paragraph"> <p>When an authentication provider (such as Spring Security’s <code>DaoAuthenticationProvider</code>) needs to check the password in a submitted authentication request against the known value for a user, and the stored password is encoded in some way, then the submitted value must be encoded using exactly the same algorithm. It’s up to you to check that these are compatible as Spring Security has no control over the persistent values. If you add password hashing to your authentication configuration in Spring Security, and your database contains plaintext passwords, then there is no way authentication can succeed. Even if you are aware that your database is using MD5 to encode the passwords, for example, and your application is configured to use Spring Security’s <code>Md5PasswordEncoder</code>, there are still things that can go wrong. The database may have the passwords encoded in Base 64, for example while the encoder is using hexadecimal strings (the default). Alternatively your database may be using upper-case while the output from the encoder is lower-case. Make sure you write a test to check the output from your configured password encoder with a known password and salt combination and check that it matches the database value before going further and attempting to authenticate through your application. Using a standard like bcrypt will avoid these issues.</p> </div> <div class="paragraph"> <p>If you want to generate encoded passwords directly in Java for storage in your user database, then you can use the <code>encode</code> method on the <code>PasswordEncoder</code>.</p> </div> </div> </div> </div> </div> <h1 id="web-app-security" class="sect0"><a class="anchor" href="#web-app-security"></a>Web Application Security</h1> <div class="paragraph"> <p>Most Spring Security users will be using the framework in applications which make user of HTTP and the Servlet API. In this part, we’ll take a look at how Spring Security provides authentication and access-control features for the web layer of an application. We’ll look behind the facade of the namespace and see which classes and interfaces are actually assembled to provide web-layer security. In some situations it is necessary to use traditional bean configuration to provide full control over the configuration, so we’ll also see how to configure these classes directly without the namespace.</p> </div> <div class="sect1"> <h2 id="security-filter-chain"><a class="anchor" href="#security-filter-chain"></a>1. The Security Filter Chain</h2> <div class="sectionbody"> <div class="paragraph"> <p>Spring Security’s web infrastructure is based entirely on standard servlet filters. It doesn’t use servlets or any other servlet-based frameworks (such as Spring MVC) internally, so it has no strong links to any particular web technology. It deals in <code>HttpServletRequest</code> s and <code>HttpServletResponse</code> s and doesn’t care whether the requests come from a browser, a web service client, an <code>HttpInvoker</code> or an AJAX application.</p> </div> <div class="paragraph"> <p>Spring Security maintains a filter chain internally where each of the filters has a particular responsibility and filters are added or removed from the configuration depending on which services are required. The ordering of the filters is important as there are dependencies between them. If you have been using <a href="#ns-config">namespace configuration</a>, then the filters are automatically configured for you and you don’t have to define any Spring beans explicitly but here may be times when you want full control over the security filter chain, either because you are using features which aren’t supported in the namespace, or you are using your own customized versions of classes.</p> </div> <div class="sect2"> <h3 id="delegating-filter-proxy"><a class="anchor" href="#delegating-filter-proxy"></a>1.1. DelegatingFilterProxy</h3> <div class="paragraph"> <p>When using servlet filters, you obviously need to declare them in your <code>web.xml</code>, or they will be ignored by the servlet container. In Spring Security, the filter classes are also Spring beans defined in the application context and thus able to take advantage of Spring’s rich dependency-injection facilities and lifecycle interfaces. Spring’s <code>DelegatingFilterProxy</code> provides the link between <code>web.xml</code> and the application context.</p> </div> <div class="paragraph"> <p>When using <code>DelegatingFilterProxy</code>, you will see something like this in the <code>web.xml</code> file:</p> </div> <div class="listingblock"> <div class="content"> <pre style="" class="prettyprint xml language-xml prettyprinted"><code><span class="tag"><filter></span><span class="pln"> </span><span class="tag"><filter-name></span><span class="pln">myFilter</span><span class="tag"></filter-name></span><span class="pln"> </span><span class="tag"><filter-class></span><span class="pln">org.springframework.web.filter.DelegatingFilterProxy</span><span class="tag"></filter-class></span><span class="pln"> </span><span class="tag"></filter></span><span class="pln"> </span><span class="tag"><filter-mapping></span><span class="pln"> </span><span class="tag"><filter-name></span><span class="pln">myFilter</span><span class="tag"></filter-name></span><span class="pln"> </span><span class="tag"><url-pattern></span><span class="pln">/*</span><span class="tag"></url-pattern></span><span class="pln"> </span><span class="tag"></filter-mapping></span></code></pre> </div> </div> <div class="paragraph"> <p>Notice that the filter is actually a <code>DelegatingFilterProxy</code>, and not the class that will actually implement the logic of the filter. What <code>DelegatingFilterProxy</code> does is delegate the <code>Filter</code>'s methods through to a bean which is obtained from the Spring application context. This enables the bean to benefit from the Spring web application context lifecycle support and configuration flexibility. The bean must implement <code>javax.servlet.Filter</code> and it must have the same name as that in the <code>filter-name</code> element. Read the Javadoc for <code>DelegatingFilterProxy</code> for more information</p> </div> </div> <div class="sect2"> <h3 id="filter-chain-proxy"><a class="anchor" href="#filter-chain-proxy"></a>1.2. FilterChainProxy</h3> <div class="paragraph"> <p>Spring Security’s web infrastructure should only be used by delegating to an instance of <code>FilterChainProxy</code>. The security filters should not be used by themselves. In theory you could declare each Spring Security filter bean that you require in your application context file and add a corresponding <code>DelegatingFilterProxy</code> entry to <code>web.xml</code> for each filter, making sure that they are ordered correctly, but this would be cumbersome and would clutter up the <code>web.xml</code> file quickly if you have a lot of filters. <code>FilterChainProxy</code> lets us add a single entry to <code>web.xml</code> and deal entirely with the application context file for managing our web security beans. It is wired using a <code>DelegatingFilterProxy</code>, just like in the example above, but with the <code>filter-name</code> set to the bean name "filterChainProxy". The filter chain is then declared in the application context with the same bean name. Here’s an example:</p> </div> <div class="listingblock"> <div class="content"> <pre style="" class="prettyprint xml language-xml prettyprinted"><code><span class="tag"><bean</span><span class="pln"> </span><span class="atn">id</span><span class="pun">=</span><span class="atv">"filterChainProxy"</span><span class="pln"> </span><span class="atn">class</span><span class="pun">=</span><span class="atv">"org.springframework.security.web.FilterChainProxy"</span><span class="tag">></span><span class="pln"> </span><span class="tag"><constructor-arg></span><span class="pln"> </span><span class="tag"><list></span><span class="pln"> </span><span class="tag"><sec:filter-chain</span><span class="pln"> </span><span class="atn">pattern</span><span class="pun">=</span><span class="atv">"/restful/**"</span><span class="pln"> </span><span class="atn">filters</span><span class="pun">=</span><span class="atv">" securityContextPersistenceFilterWithASCFalse, basicAuthenticationFilter, exceptionTranslationFilter, filterSecurityInterceptor"</span><span class="pln"> </span><span class="tag">/></span><span class="pln"> </span><span class="tag"><sec:filter-chain</span><span class="pln"> </span><span class="atn">pattern</span><span class="pun">=</span><span class="atv">"/**"</span><span class="pln"> </span><span class="atn">filters</span><span class="pun">=</span><span class="atv">" securityContextPersistenceFilterWithASCTrue, formLoginFilter, exceptionTranslationFilter, filterSecurityInterceptor"</span><span class="pln"> </span><span class="tag">/></span><span class="pln"> </span><span class="tag"></list></span><span class="pln"> </span><span class="tag"></constructor-arg></span><span class="pln"> </span><span class="tag"></bean></span></code></pre> </div> </div> <div class="paragraph"> <p>The namespace element <code>filter-chain</code> is used for convenience to set up the security filter chain(s) which are required within the application. <span class="footnote">[<a id="_footnoteref_8" class="footnote" href="#_footnote_8" title="View footnote.">8</a>]</span>. It maps a particular URL pattern to a list of filters built up from the bean names specified in the <code>filters</code> element, and combines them in a bean of type <code>SecurityFilterChain</code>. The <code>pattern</code> attribute takes an Ant Paths and the most specific URIs should appear first <span class="footnote">[<a id="_footnoteref_9" class="footnote" href="#_footnote_9" title="View footnote.">9</a>]</span>. At runtime the <code>FilterChainProxy</code> will locate the first URI pattern that matches the current web request and the list of filter beans specified by the <code>filters</code> attribute will be applied to that request. The filters will be invoked in the order they are defined, so you have complete control over the filter chain which is applied to a particular URL.</p> </div> <div class="paragraph"> <p>You may have noticed we have declared two <code>SecurityContextPersistenceFilter</code> s in the filter chain ( <code>ASC</code> is short for <code>allowSessionCreation</code>, a property of <code>SecurityContextPersistenceFilter</code>). As web services will never present a <code>jsessionid</code> on future requests, creating <code>HttpSession</code> s for such user agents would be wasteful. If you had a high-volume application which required maximum scalability, we recommend you use the approach shown above. For smaller applications, using a single <code>SecurityContextPersistenceFilter</code> (with its default <code>allowSessionCreation</code> as <code>true</code>) would likely be sufficient.</p> </div> <div class="paragraph"> <p>Note that <code>FilterChainProxy</code> does not invoke standard filter lifecycle methods on the filters it is configured with. We recommend you use Spring’s application context lifecycle interfaces as an alternative, just as you would for any other Spring bean.</p> </div> <div class="paragraph"> <p>When we looked at how to set up web security using <a href="#ns-web-xml">namespace configuration</a>, we used a <code>DelegatingFilterProxy</code> with the name "springSecurityFilterChain". You should now be able to see that this is the name of the <code>FilterChainProxy</code> which is created by the namespace.</p> </div> <div class="sect3"> <h4 id="bypassing-the-filter-chain"><a class="anchor" href="#bypassing-the-filter-chain"></a>1.2.1. Bypassing the Filter Chain</h4> <div class="paragraph"> <p>You can use the attribute <code>filters = "none"</code> as an alternative to supplying a filter bean list. This will omit the request pattern from the security filter chain entirely. Note that anything matching this path will then have no authentication or authorization services applied and will be freely accessible. If you want to make use of the contents of the <code>SecurityContext</code> contents during a request, then it must have passed through the security filter chain. Otherwise the <code>SecurityContextHolder</code> will not have been populated and the contents will be null.</p> </div> </div> </div> <div class="sect2"> <h3 id="filter-ordering"><a class="anchor" href="#filter-ordering"></a>1.3. Filter Ordering</h3> <div class="paragraph"> <p>The order that filters are defined in the chain is very important. Irrespective of which filters you are actually using, the order should be as follows:</p> </div> <div class="ulist"> <ul> <li> <p><code>ChannelProcessingFilter</code>, because it might need to redirect to a different protocol</p> </li> <li> <p><code>SecurityContextPersistenceFilter</code>, so a <code>SecurityContext</code> can be set up in the <code>SecurityContextHolder</code> at the beginning of a web request, and any changes to the <code>SecurityContext</code> can be copied to the <code>HttpSession</code> when the web request ends (ready for use with the next web request)</p> </li> <li> <p><code>ConcurrentSessionFilter</code>, because it uses the <code>SecurityContextHolder</code> functionality and needs to update the <code>SessionRegistry</code> to reflect ongoing requests from the principal</p> </li> <li> <p>Authentication processing mechanisms - <code>UsernamePasswordAuthenticationFilter</code>, <code>CasAuthenticationFilter</code>, <code>BasicAuthenticationFilter</code> etc - so that the <code>SecurityContextHolder</code> can be modified to contain a valid <code>Authentication</code> request token</p> </li> <li> <p>The <code>SecurityContextHolderAwareRequestFilter</code>, if you are using it to install a Spring Security aware <code>HttpServletRequestWrapper</code> into your servlet container</p> </li> <li> <p>The <code>JaasApiIntegrationFilter</code>, if a <code>JaasAuthenticationToken</code> is in the <code>SecurityContextHolder</code> this will process the <code>FilterChain</code> as the <code>Subject</code> in the <code>JaasAuthenticationToken</code></p> </li> <li> <p><code>RememberMeAuthenticationFilter</code>, so that if no earlier authentication processing mechanism updated the <code>SecurityContextHolder</code>, and the request presents a cookie that enables remember-me services to take place, a suitable remembered <code>Authentication</code> object will be put there</p> </li> <li> <p><code>AnonymousAuthenticationFilter</code>, so that if no earlier authentication processing mechanism updated the <code>SecurityContextHolder</code>, an anonymous <code>Authentication</code> object will be put there</p> </li> <li> <p><code>ExceptionTranslationFilter</code>, to catch any Spring Security exceptions so that either an HTTP error response can be returned or an appropriate <code>AuthenticationEntryPoint</code> can be launched</p> </li> <li> <p><code>FilterSecurityInterceptor</code>, to protect web URIs and raise exceptions when access is denied</p> </li> </ul> </div> </div> <div class="sect2"> <h3 id="request-matching"><a class="anchor" href="#request-matching"></a>1.4. Request Matching and HttpFirewall</h3> <div class="paragraph"> <p>Spring Security has several areas where patterns you have defined are tested against incoming requests in order to decide how the request should be handled. This occurs when the <code>FilterChainProxy</code> decides which filter chain a request should be passed through and also when the <code>FilterSecurityInterceptor</code> decides which security constraints apply to a request. It’s important to understand what the mechanism is and what URL value is used when testing against the patterns that you define.</p> </div> <div class="paragraph"> <p>The Servlet Specification defines several properties for the <code>HttpServletRequest</code> which are accessible via getter methods, and which we might want to match against. These are the <code>contextPath</code>, <code>servletPath</code>, <code>pathInfo</code> and <code>queryString</code>. Spring Security is only interested in securing paths within the application, so the <code>contextPath</code> is ignored. Unfortunately, the servlet spec does not define exactly what the values of <code>servletPath</code> and <code>pathInfo</code> will contain for a particular request URI. For example, each path segment of a URL may contain parameters, as defined in <a href="http://www.ietf.org/rfc/rfc2396.txt">RFC 2396</a> <span class="footnote">[<a id="_footnoteref_10" class="footnote" href="#_footnote_10" title="View footnote.">10</a>]</span>. The Specification does not clearly state whether these should be included in the <code>servletPath</code> and <code>pathInfo</code> values and the behaviour varies between different servlet containers. There is a danger that when an application is deployed in a container which does not strip path parameters from these values, an attacker could add them to the requested URL in order to cause a pattern match to succeed or fail unexpectedly. <span class="footnote">[<a id="_footnoteref_11" class="footnote" href="#_footnote_11" title="View footnote.">11</a>]</span>. Other variations in the incoming URL are also possible. For example, it could contain path-traversal sequences (like <code>/../</code>) or multiple forward slashes (<code>//</code>) which could also cause pattern-matches to fail. Some containers normalize these out before performing the servlet mapping, but others don’t. To protect against issues like these, <code>FilterChainProxy</code> uses an <code>HttpFirewall</code> strategy to check and wrap the request. Un-normalized requests are automatically rejected by default, and path parameters and duplicate slashes are removed for matching purposes. <span class="footnote">[<a id="_footnoteref_12" class="footnote" href="#_footnote_12" title="View footnote.">12</a>]</span>. It is therefore essential that a <code>FilterChainProxy</code> is used to manage the security filter chain. Note that the <code>servletPath</code> and <code>pathInfo</code> values are decoded by the container, so your application should not have any valid paths which contain semi-colons, as these parts will be removed for matching purposes.</p> </div> <div class="paragraph"> <p>As mentioned above, the default strategy is to use Ant-style paths for matching and this is likely to be the best choice for most users. The strategy is implemented in the class <code>AntPathRequestMatcher</code> which uses Spring’s <code>AntPathMatcher</code> to perform a case-insensitive match of the pattern against the concatenated <code>servletPath</code> and <code>pathInfo</code>, ignoring the <code>queryString</code>.</p> </div> <div class="paragraph"> <p>If for some reason, you need a more powerful matching strategy, you can use regular expressions. The strategy implementation is then`RegexRequestMatcher`. See the Javadoc for this class for more information.</p> </div> <div class="paragraph"> <p>In practice we recommend that you use method security at your service layer, to control access to your application, and do not rely entirely on the use of security constraints defined at the web-application level. URLs change and it is difficult to take account of all the possible URLs that an application might support and how requests might be manipulated. You should try and restrict yourself to using a few simple ant paths which are simple to understand. Always try to use a"deny-by-default" approach where you have a catch-all wildcard ( <code>/**</code> or <code>**</code>) defined last and denying access.</p> </div> <div class="paragraph"> <p>Security defined at the service layer is much more robust and harder to bypass, so you should always take advantage of Spring Security’s method security options.</p> </div> </div> <div class="sect2"> <h3 id="use-with-other-filter-based-frameworks"><a class="anchor" href="#use-with-other-filter-based-frameworks"></a>1.5. Use with other Filter-Based Frameworks</h3> <div class="paragraph"> <p>If you’re using some other framework that is also filter-based, then you need to make sure that the Spring Security filters come first. This enables the <code>SecurityContextHolder</code> to be populated in time for use by the other filters. Examples are the use of SiteMesh to decorate your web pages or a web framework like Wicket which uses a filter to handle its requests.</p> </div> </div> <div class="sect2"> <h3 id="filter-chains-with-ns"><a class="anchor" href="#filter-chains-with-ns"></a>1.6. Advanced Namespace Configuration</h3> <div class="paragraph"> <p>As we saw earlier in the namespace chapter, it’s possible to use multiple <code>http</code> elements to define different security configurations for different URL patterns. Each element creates a filter chain within the internal <code>FilterChainProxy</code> and the URL pattern that should be mapped to it. The elements will be added in the order they are declared, so the most specific patterns must again be declared first. Here’s another example, for a similar situation to that above, where the application supports both a stateless RESTful API and also a normal web application which users log into using a form.</p> </div> <div class="listingblock"> <div class="content"> <pre style="" class="prettyprint xml language-xml prettyprinted"><code><span class="com"><!-- Stateless RESTful service using Basic authentication --></span><span class="pln"> </span><span class="tag"><http</span><span class="pln"> </span><span class="atn">pattern</span><span class="pun">=</span><span class="atv">"/restful/**"</span><span class="pln"> </span><span class="atn">create-session</span><span class="pun">=</span><span class="atv">"stateless"</span><span class="tag">></span><span class="pln"> </span><span class="tag"><intercept-url</span><span class="pln"> </span><span class="atn">pattern</span><span class="pun">=</span><span class="atv">'/**'</span><span class="pln"> </span><span class="atn">access</span><span class="pun">=</span><span class="atv">'ROLE_REMOTE'</span><span class="pln"> </span><span class="tag">/></span><span class="pln"> </span><span class="tag"><http-basic</span><span class="pln"> </span><span class="tag">/></span><span class="pln"> </span><span class="tag"></http></span><span class="pln"> </span><span class="com"><!-- Empty filter chain for the login page --></span><span class="pln"> </span><span class="tag"><http</span><span class="pln"> </span><span class="atn">pattern</span><span class="pun">=</span><span class="atv">"/login.htm*"</span><span class="pln"> </span><span class="atn">security</span><span class="pun">=</span><span class="atv">"none"</span><span class="tag">/></span><span class="pln"> </span><span class="com"><!-- Additional filter chain for normal users, matching all other requests --></span><span class="pln"> </span><span class="tag"><http></span><span class="pln"> </span><span class="tag"><intercept-url</span><span class="pln"> </span><span class="atn">pattern</span><span class="pun">=</span><span class="atv">'/**'</span><span class="pln"> </span><span class="atn">access</span><span class="pun">=</span><span class="atv">'ROLE_USER'</span><span class="pln"> </span><span class="tag">/></span><span class="pln"> </span><span class="tag"><form-login</span><span class="pln"> </span><span class="atn">login-page</span><span class="pun">=</span><span class="atv">'/login.htm'</span><span class="pln"> </span><span class="atn">default-target-url</span><span class="pun">=</span><span class="atv">"/home.htm"</span><span class="tag">/></span><span class="pln"> </span><span class="tag"><logout</span><span class="pln"> </span><span class="tag">/></span><span class="pln"> </span><span class="tag"></http></span></code></pre> </div> </div> </div> </div> </div> <div class="sect1"> <h2 id="core-web-filters"><a class="anchor" href="#core-web-filters"></a>2. Core Security Filters</h2> <div class="sectionbody"> <div class="paragraph"> <p>There are some key filters which will always be used in a web application which uses Spring Security, so we’ll look at these and their supporting classes and interfaces first. We won’t cover every feature, so be sure to look at the Javadoc for them if you want to get the complete picture.</p> </div> <div class="sect2"> <h3 id="filter-security-interceptor"><a class="anchor" href="#filter-security-interceptor"></a>2.1. FilterSecurityInterceptor</h3> <div class="paragraph"> <p>We’ve already seen <code>FilterSecurityInterceptor</code> briefly when discussing <a href="#tech-intro-access-control">access-control in general</a>, and we’ve already used it with the namespace where the <code><intercept-url></code> elements are combined to configure it internally. Now we’ll see how to explicitly configure it for use with a`FilterChainProxy`, along with its companion filter <code>ExceptionTranslationFilter</code>. A typical configuration example is shown below:</p> </div> <div class="listingblock"> <div class="content"> <pre style="" class="prettyprint xml language-xml prettyprinted"><code><span class="tag"><bean</span><span class="pln"> </span><span class="atn">id</span><span class="pun">=</span><span class="atv">"filterSecurityInterceptor"</span><span class="pln"> </span><span class="atn">class</span><span class="pun">=</span><span class="atv">"org.springframework.security.web.access.intercept.FilterSecurityInterceptor"</span><span class="tag">></span><span class="pln"> </span><span class="tag"><property</span><span class="pln"> </span><span class="atn">name</span><span class="pun">=</span><span class="atv">"authenticationManager"</span><span class="pln"> </span><span class="atn">ref</span><span class="pun">=</span><span class="atv">"authenticationManager"</span><span class="tag">/></span><span class="pln"> </span><span class="tag"><property</span><span class="pln"> </span><span class="atn">name</span><span class="pun">=</span><span class="atv">"accessDecisionManager"</span><span class="pln"> </span><span class="atn">ref</span><span class="pun">=</span><span class="atv">"accessDecisionManager"</span><span class="tag">/></span><span class="pln"> </span><span class="tag"><property</span><span class="pln"> </span><span class="atn">name</span><span class="pun">=</span><span class="atv">"securityMetadataSource"</span><span class="tag">></span><span class="pln"> </span><span class="tag"><security:filter-security-metadata-source></span><span class="pln"> </span><span class="tag"><security:intercept-url</span><span class="pln"> </span><span class="atn">pattern</span><span class="pun">=</span><span class="atv">"/secure/super/**"</span><span class="pln"> </span><span class="atn">access</span><span class="pun">=</span><span class="atv">"ROLE_WE_DONT_HAVE"</span><span class="tag">/></span><span class="pln"> </span><span class="tag"><security:intercept-url</span><span class="pln"> </span><span class="atn">pattern</span><span class="pun">=</span><span class="atv">"/secure/**"</span><span class="pln"> </span><span class="atn">access</span><span class="pun">=</span><span class="atv">"ROLE_SUPERVISOR,ROLE_TELLER"</span><span class="tag">/></span><span class="pln"> </span><span class="tag"></security:filter-security-metadata-source></span><span class="pln"> </span><span class="tag"></property></span><span class="pln"> </span><span class="tag"></bean></span></code></pre> </div> </div> <div class="paragraph"> <p><code>FilterSecurityInterceptor</code> is responsible for handling the security of HTTP resources. It requires a reference to an <code>AuthenticationManager</code> and an <code>AccessDecisionManager</code>. It is also supplied with configuration attributes that apply to different HTTP URL requests. Refer back to <a href="#tech-intro-config-attributes">the original discussion on these</a> in the technical introduction.</p> </div> <div class="paragraph"> <p>The <code>FilterSecurityInterceptor</code> can be configured with configuration attributes in two ways. The first, which is shown above, is using the <code><filter-security-metadata-source></code> namespace element. This is similar to the <code><http></code> element from the namespace chapter but the <code><intercept-url></code> child elements only use the <code>pattern</code> and <code>access</code> attributes. Commas are used to delimit the different configuration attributes that apply to each HTTP URL. The second option is to write your own`SecurityMetadataSource`, but this is beyond the scope of this document. Irrespective of the approach used, the <code>SecurityMetadataSource</code> is responsible for returning a <code>List<ConfigAttribute></code> containing all of the configuration attributes associated with a single secure HTTP URL.</p> </div> <div class="paragraph"> <p>It should be noted that the <code>FilterSecurityInterceptor.setSecurityMetadataSource()</code> method actually expects an instance of <code>FilterInvocationSecurityMetadataSource</code>. This is a marker interface which subclasses`SecurityMetadataSource`. It simply denotes the <code>SecurityMetadataSource</code> understands <code>FilterInvocation</code> s. In the interests of simplicity we’ll continue to refer to the <code>FilterInvocationSecurityMetadataSource</code> as a <code>SecurityMetadataSource</code>, as the distinction is of little relevance to most users.</p> </div> <div class="paragraph"> <p>The <code>SecurityMetadataSource</code> created by the namespace syntax obtains the configuration attributes for a particular <code>FilterInvocation</code> by matching the request URL against the configured <code>pattern</code> attributes. This behaves in the same way as it does for namespace configuration. The default is to treat all expressions as Apache Ant paths and regular expressions are also supported for more complex cases. The <code>path-type</code> attribute is used to specify the type of pattern being used. It is not possible to mix expression syntaxes within the same definition. As an example, the previous configuration using regular expressions instead of Ant paths would be written as follows:</p> </div> <div class="listingblock"> <div class="content"> <pre style="" class="prettyprint xml language-xml prettyprinted"><code><span class="tag"><bean</span><span class="pln"> </span><span class="atn">id</span><span class="pun">=</span><span class="atv">"filterInvocationInterceptor"</span><span class="pln"> </span><span class="atn">class</span><span class="pun">=</span><span class="atv">"org.springframework.security.web.access.intercept.FilterSecurityInterceptor"</span><span class="tag">></span><span class="pln"> </span><span class="tag"><property</span><span class="pln"> </span><span class="atn">name</span><span class="pun">=</span><span class="atv">"authenticationManager"</span><span class="pln"> </span><span class="atn">ref</span><span class="pun">=</span><span class="atv">"authenticationManager"</span><span class="tag">/></span><span class="pln"> </span><span class="tag"><property</span><span class="pln"> </span><span class="atn">name</span><span class="pun">=</span><span class="atv">"accessDecisionManager"</span><span class="pln"> </span><span class="atn">ref</span><span class="pun">=</span><span class="atv">"accessDecisionManager"</span><span class="tag">/></span><span class="pln"> </span><span class="tag"><property</span><span class="pln"> </span><span class="atn">name</span><span class="pun">=</span><span class="atv">"runAsManager"</span><span class="pln"> </span><span class="atn">ref</span><span class="pun">=</span><span class="atv">"runAsManager"</span><span class="tag">/></span><span class="pln"> </span><span class="tag"><property</span><span class="pln"> </span><span class="atn">name</span><span class="pun">=</span><span class="atv">"securityMetadataSource"</span><span class="tag">></span><span class="pln"> </span><span class="tag"><security:filter-security-metadata-source</span><span class="pln"> </span><span class="atn">path-type</span><span class="pun">=</span><span class="atv">"regex"</span><span class="tag">></span><span class="pln"> </span><span class="tag"><security:intercept-url</span><span class="pln"> </span><span class="atn">pattern</span><span class="pun">=</span><span class="atv">"\A/secure/super/.*\Z"</span><span class="pln"> </span><span class="atn">access</span><span class="pun">=</span><span class="atv">"ROLE_WE_DONT_HAVE"</span><span class="tag">/></span><span class="pln"> </span><span class="tag"><security:intercept-url</span><span class="pln"> </span><span class="atn">pattern</span><span class="pun">=</span><span class="atv">"\A/secure/.*\"</span><span class="pln"> </span><span class="atn">access</span><span class="pun">=</span><span class="atv">"ROLE_SUPERVISOR,ROLE_TELLER"</span><span class="tag">/></span><span class="pln"> </span><span class="tag"></security:filter-security-metadata-source></span><span class="pln"> </span><span class="tag"></property></span><span class="pln"> </span><span class="tag"></bean></span></code></pre> </div> </div> <div class="paragraph"> <p>Patterns are always evaluated in the order they are defined. Thus it is important that more specific patterns are defined higher in the list than less specific patterns. This is reflected in our example above, where the more specific <code>/secure/super/</code> pattern appears higher than the less specific <code>/secure/</code> pattern. If they were reversed, the <code>/secure/</code> pattern would always match and the <code>/secure/super/</code> pattern would never be evaluated.</p> </div> </div> <div class="sect2"> <h3 id="exception-translation-filter"><a class="anchor" href="#exception-translation-filter"></a>2.2. ExceptionTranslationFilter</h3> <div class="paragraph"> <p>The <code>ExceptionTranslationFilter</code> sits above the <code>FilterSecurityInterceptor</code> in the security filter stack. It doesn’t do any actual security enforcement itself, but handles exceptions thrown by the security interceptors and provides suitable and HTTP responses.</p> </div> <div class="listingblock"> <div class="content"> <pre style="" class="prettyprint xml language-xml prettyprinted"><code><span class="pln"> </span><span class="tag"><bean</span><span class="pln"> </span><span class="atn">id</span><span class="pun">=</span><span class="atv">"exceptionTranslationFilter"</span><span class="pln"> </span><span class="atn">class</span><span class="pun">=</span><span class="atv">"org.springframework.security.web.access.ExceptionTranslationFilter"</span><span class="tag">></span><span class="pln"> </span><span class="tag"><property</span><span class="pln"> </span><span class="atn">name</span><span class="pun">=</span><span class="atv">"authenticationEntryPoint"</span><span class="pln"> </span><span class="atn">ref</span><span class="pun">=</span><span class="atv">"authenticationEntryPoint"</span><span class="tag">/></span><span class="pln"> </span><span class="tag"><property</span><span class="pln"> </span><span class="atn">name</span><span class="pun">=</span><span class="atv">"accessDeniedHandler"</span><span class="pln"> </span><span class="atn">ref</span><span class="pun">=</span><span class="atv">"accessDeniedHandler"</span><span class="tag">/></span><span class="pln"> </span><span class="tag"></bean></span><span class="pln"> </span><span class="tag"><bean</span><span class="pln"> </span><span class="atn">id</span><span class="pun">=</span><span class="atv">"authenticationEntryPoint"</span><span class="pln"> </span><span class="atn">class</span><span class="pun">=</span><span class="atv">"org.springframework.security.web.authentication.LoginUrlAuthenticationEntryPoint"</span><span class="tag">></span><span class="pln"> </span><span class="tag"><property</span><span class="pln"> </span><span class="atn">name</span><span class="pun">=</span><span class="atv">"loginFormUrl"</span><span class="pln"> </span><span class="atn">value</span><span class="pun">=</span><span class="atv">"/login.jsp"</span><span class="tag">/></span><span class="pln"> </span><span class="tag"></bean></span><span class="pln"> </span><span class="tag"><bean</span><span class="pln"> </span><span class="atn">id</span><span class="pun">=</span><span class="atv">"accessDeniedHandler"</span><span class="pln"> </span><span class="atn">class</span><span class="pun">=</span><span class="atv">"org.springframework.security.web.access.AccessDeniedHandlerImpl"</span><span class="tag">></span><span class="pln"> </span><span class="tag"><property</span><span class="pln"> </span><span class="atn">name</span><span class="pun">=</span><span class="atv">"errorPage"</span><span class="pln"> </span><span class="atn">value</span><span class="pun">=</span><span class="atv">"/accessDenied.htm"</span><span class="tag">/></span><span class="pln"> </span><span class="tag"></bean></span></code></pre> </div> </div> <div class="sect3"> <h4 id="auth-entry-point"><a class="anchor" href="#auth-entry-point"></a>2.2.1. AuthenticationEntryPoint</h4> <div class="paragraph"> <p>The <code>AuthenticationEntryPoint</code> will be called if the user requests a secure HTTP resource but they are not authenticated. An appropriate <code>AuthenticationException</code> or <code>AccessDeniedException</code> will be thrown by a security interceptor further down the call stack, triggering the <code>commence</code> method on the entry point. This does the job of presenting the appropriate response to the user so that authentication can begin. The one we’ve used here is <code>LoginUrlAuthenticationEntryPoint</code>, which redirects the request to a different URL (typically a login page). The actual implementation used will depend on the authentication mechanism you want to be used in your application.</p> </div> </div> <div class="sect3"> <h4 id="access-denied-handler"><a class="anchor" href="#access-denied-handler"></a>2.2.2. AccessDeniedHandler</h4> <div class="paragraph"> <p>What happens if a user is already authenticated and they try to access a protected resource? In normal usage, this shouldn’t happen because the application workflow should be restricted to operations to which a user has access. For example, an HTML link to an administration page might be hidden from users who do not have an admin role. You can’t rely on hiding links for security though, as there’s always a possibility that a user will just enter the URL directly in an attempt to bypass the restrictions. Or they might modify a RESTful URL to change some of the argument values. Your application must be protected against these scenarios or it will definitely be insecure. You will typically use simple web layer security to apply constraints to basic URLs and use more specific method-based security on your service layer interfaces to really nail down what is permissible.</p> </div> <div class="paragraph"> <p>If an <code>AccessDeniedException</code> is thrown and a user has already been authenticated, then this means that an operation has been attempted for which they don’t have enough permissions. In this case, <code>ExceptionTranslationFilter</code> will invoke a second strategy, the <code>AccessDeniedHandler</code>. By default, an <code>AccessDeniedHandlerImpl</code> is used, which just sends a 403 (Forbidden) response to the client. Alternatively you can configure an instance explicitly (as in the above example) and set an error page URL which it will forwards the request to <span class="footnote">[<a id="_footnoteref_13" class="footnote" href="#_footnote_13" title="View footnote.">13</a>]</span>. This can be a simple "access denied" page, such as a JSP, or it could be a more complex handler such as an MVC controller. And of course, you can implement the interface yourself and use your own implementation.</p> </div> <div class="paragraph"> <p>It’s also possible to supply a custom <code>AccessDeniedHandler</code> when you’re using the namespace to configure your application. See <a href="#nsa-access-denied-handler">the namespace appendix</a> for more details.</p> </div> </div> <div class="sect3"> <h4 id="request-caching"><a class="anchor" href="#request-caching"></a>2.2.3. SavedRequest s and the RequestCache Interface</h4> <div class="paragraph"> <p>Another of <code>ExceptionTranslationFilter</code>'s responsibilities is to save the current request before invoking the <code>AuthenticationEntryPoint</code>. This allows the request to be restored after the use has authenticated (see previous overview of <a href="#tech-intro-web-authentication">web authentication</a>). A typical example would be where the user logs in with a form, and is then redirected to the original URL by the default <code>SavedRequestAwareAuthenticationSuccessHandler</code> (see <a href="#form-login-flow-handling">below</a>).</p> </div> <div class="paragraph"> <p>The <code>RequestCache</code> encapsulates the functionality required for storing and retrieving <code>HttpServletRequest</code> instances. By default the <code>HttpSessionRequestCache</code> is used, which stores the request in the <code>HttpSession</code>. The <code>RequestCacheFilter</code> has the job of actually restoring the saved request from the cache when the user is redirected to the original URL.</p> </div> <div class="paragraph"> <p>Under normal circumstances, you shouldn’t need to modify any of this functionality, but the saved-request handling is a "best-effort" approach and there may be situations which the default configuration isn’t able to handle. The use of these interfaces makes it fully pluggable from Spring Security 3.0 onwards.</p> </div> </div> </div> <div class="sect2"> <h3 id="security-context-persistence-filter"><a class="anchor" href="#security-context-persistence-filter"></a>2.3. SecurityContextPersistenceFilter</h3> <div class="paragraph"> <p>We covered the purpose of this all-important filter in the <a href="#tech-intro-sec-context-persistence">Technical Overview</a> chapter so you might want to re-read that section at this point. Let’s first take a look at how you would configure it for use with a <code>FilterChainProxy</code>. A basic configuration only requires the bean itself</p> </div> <div class="listingblock"> <div class="content"> <pre style="" class="prettyprint xml language-xml prettyprinted"><code><span class="tag"><bean</span><span class="pln"> </span><span class="atn">id</span><span class="pun">=</span><span class="atv">"securityContextPersistenceFilter"</span><span class="pln"> </span><span class="atn">class</span><span class="pun">=</span><span class="atv">"org.springframework.security.web.context.SecurityContextPersistenceFilter"</span><span class="tag">/></span></code></pre> </div> </div> <div class="paragraph"> <p>As we saw previously, this filter has two main tasks. It is responsible for storage of the <code>SecurityContext</code> contents between HTTP requests and for clearing the <code>SecurityContextHolder</code> when a request is completed. Clearing the <code>ThreadLocal</code> in which the context is stored is essential, as it might otherwise be possible for a thread to be replaced into the servlet container’s thread pool, with the security context for a particular user still attached. This thread might then be used at a later stage, performing operations with the wrong credentials.</p> </div> <div class="sect3"> <h4 id="security-context-repository"><a class="anchor" href="#security-context-repository"></a>2.3.1. SecurityContextRepository</h4> <div class="paragraph"> <p>From Spring Security 3.0, the job of loading and storing the security context is now delegated to a separate strategy interface:</p> </div> <div class="listingblock"> <div class="content"> <pre style="" class="prettyprint java language-java prettyprinted"><code><span class="kwd">public</span><span class="pln"> </span><span class="kwd">interface</span><span class="pln"> </span><span class="typ">SecurityContextRepository</span><span class="pln"> </span><span class="pun">{</span><span class="pln"> </span><span class="typ">SecurityContext</span><span class="pln"> loadContext</span><span class="pun">(</span><span class="typ">HttpRequestResponseHolder</span><span class="pln"> requestResponseHolder</span><span class="pun">);</span><span class="pln"> </span><span class="kwd">void</span><span class="pln"> saveContext</span><span class="pun">(</span><span class="typ">SecurityContext</span><span class="pln"> context</span><span class="pun">,</span><span class="pln"> </span><span class="typ">HttpServletRequest</span><span class="pln"> request</span><span class="pun">,</span><span class="pln"> </span><span class="typ">HttpServletResponse</span><span class="pln"> response</span><span class="pun">);</span><span class="pln"> </span><span class="pun">}</span></code></pre> </div> </div> <div class="paragraph"> <p>The <code>HttpRequestResponseHolder</code> is simply a container for the incoming request and response objects, allowing the implementation to replace these with wrapper classes. The returned contents will be passed to the filter chain.</p> </div> <div class="paragraph"> <p>The default implementation is <code>HttpSessionSecurityContextRepository</code>, which stores the security context as an <code>HttpSession</code> attribute <span class="footnote">[<a id="_footnoteref_14" class="footnote" href="#_footnote_14" title="View footnote.">14</a>]</span>. The most important configuration parameter for this implementation is the <code>allowSessionCreation</code> property, which defaults to <code>true</code>, thus allowing the class to create a session if it needs one to store the security context for an authenticated user (it won’t create one unless authentication has taken place and the contents of the security context have changed). If you don’t want a session to be created, then you can set this property to <code>false</code>:</p> </div> <div class="listingblock"> <div class="content"> <pre style="" class="prettyprint xml language-xml prettyprinted"><code><span class="tag"><bean</span><span class="pln"> </span><span class="atn">id</span><span class="pun">=</span><span class="atv">"securityContextPersistenceFilter"</span><span class="pln"> </span><span class="atn">class</span><span class="pun">=</span><span class="atv">"org.springframework.security.web.context.SecurityContextPersistenceFilter"</span><span class="tag">></span><span class="pln"> </span><span class="tag"><property</span><span class="pln"> </span><span class="atn">name</span><span class="pun">=</span><span class="atv">'securityContextRepository'</span><span class="tag">></span><span class="pln"> </span><span class="tag"><bean</span><span class="pln"> </span><span class="atn">class</span><span class="pun">=</span><span class="atv">'org.springframework.security.web.context.HttpSessionSecurityContextRepository'</span><span class="tag">></span><span class="pln"> </span><span class="tag"><property</span><span class="pln"> </span><span class="atn">name</span><span class="pun">=</span><span class="atv">'allowSessionCreation'</span><span class="pln"> </span><span class="atn">value</span><span class="pun">=</span><span class="atv">'false'</span><span class="pln"> </span><span class="tag">/></span><span class="pln"> </span><span class="tag"></bean></span><span class="pln"> </span><span class="tag"></property></span><span class="pln"> </span><span class="tag"></bean></span></code></pre> </div> </div> <div class="paragraph"> <p>Alternatively you could provide an instance of <code>NullSecurityContextRepository</code>, a "http://en.wikipedia.org/wiki/Null_Object_pattern[null object]" implementation, which will prevent the security context from being stored, even if a session has already been created during the request.</p> </div> </div> </div> <div class="sect2"> <h3 id="form-login-filter"><a class="anchor" href="#form-login-filter"></a>2.4. UsernamePasswordAuthenticationFilter</h3> <div class="paragraph"> <p>We’ve now seen the three main filters which are always present in a Spring Security web configuration. These are also the three which are automatically created by the namespace <code><http></code> element and cannot be substituted with alternatives. The only thing that’s missing now is an actual authentication mechanism, something that will allow a user to authenticate. This filter is the most commonly used authentication filter and the one that is most often customized <span class="footnote">[<a id="_footnoteref_15" class="footnote" href="#_footnote_15" title="View footnote.">15</a>]</span>. It also provides the implementation used by the <code><form-login></code> element from the namespace. There are three stages required to configure it.</p> </div> <div class="ulist"> <ul> <li> <p>Configure a <code>LoginUrlAuthenticationEntryPoint</code> with the URL of the login page, just as we did above, and set it on the <code>ExceptionTranslationFilter</code>.</p> </li> <li> <p>Implement the login page (using a JSP or MVC controller).</p> </li> <li> <p>Configure an instance of <code>UsernamePasswordAuthenticationFilter</code> in the application context</p> </li> <li> <p>Add the filter bean to your filter chain proxy (making sure you pay attention to the order).</p> </li> </ul> </div> <div class="paragraph"> <p>The login form simply contains <code>j_username</code> and <code>j_password</code> input fields, and posts to the URL that is monitored by the filter (by default this is <code>/j_spring_security_check</code>). The basic filter configuration looks something like this:</p> </div> <div class="listingblock"> <div class="content"> <pre style="" class="prettyprint xml language-xml prettyprinted"><code><span class="tag"><bean</span><span class="pln"> </span><span class="atn">id</span><span class="pun">=</span><span class="atv">"authenticationFilter"</span><span class="pln"> </span><span class="atn">class</span><span class="pun">=</span><span class="pln"> </span><span class="atv">"org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter"</span><span class="tag">></span><span class="pln"> </span><span class="tag"><property</span><span class="pln"> </span><span class="atn">name</span><span class="pun">=</span><span class="atv">"authenticationManager"</span><span class="pln"> </span><span class="atn">ref</span><span class="pun">=</span><span class="atv">"authenticationManager"</span><span class="tag">/></span><span class="pln"> </span><span class="tag"></bean></span></code></pre> </div> </div> <div class="sect3"> <h4 id="form-login-flow-handling"><a class="anchor" href="#form-login-flow-handling"></a>2.4.1. Application Flow on Authentication Success and Failure</h4> <div class="paragraph"> <p>The filter calls the configured <code>AuthenticationManager</code> to process each authentication request. The destination following a successful authentication or an authentication failure is controlled by the <code>AuthenticationSuccessHandler</code> and <code>AuthenticationFailureHandler</code> strategy interfaces, respectively. The filter has properties which allow you to set these so you can customize the behaviour completely <span class="footnote">[<a id="_footnoteref_16" class="footnote" href="#_footnote_16" title="View footnote.">16</a>]</span>. Some standard implementations are supplied such as <code>SimpleUrlAuthenticationSuccessHandler</code>, <code>SavedRequestAwareAuthenticationSuccessHandler</code>, <code>SimpleUrlAuthenticationFailureHandler</code> and <code>ExceptionMappingAuthenticationFailureHandler</code>. Have a look at the Javadoc for these classes and also for <code>AbstractAuthenticationProcessingFilter</code> to get an overview of how they work and the supported features.</p> </div> <div class="paragraph"> <p>If authentication is successful, the resulting <code>Authentication</code> object will be placed into the <code>SecurityContextHolder</code>. The configured <code>AuthenticationSuccessHandler</code> will then be called to either redirect or forward the user to the appropriate destination. By default a <code>SavedRequestAwareAuthenticationSuccessHandler</code> is used, which means that the user will be redirected to the original destination they requested before they were asked to login.</p> </div> <div class="admonitionblock note"> <table> <tbody><tr> <td class="icon"> <i class="icon-note" title="Note"></i> </td> <td class="content"> <div class="paragraph"> <p>The <code>ExceptionTranslationFilter</code> caches the original request a user makes. When the user authenticates, the request handler makes use of this cached request to obtain the original URL and redirect to it. The original request is then rebuilt and used as an alternative.</p> </div> </td> </tr> </tbody></table> </div> <div class="paragraph"> <p>If authentication fails, the configured <code>AuthenticationFailureHandler</code> will be invoked.</p> </div> </div> </div> </div> </div> <div class="sect1"> <h2 id="servletapi"><a class="anchor" href="#servletapi"></a>3. Servlet API integration</h2> <div class="sectionbody"> <div class="paragraph"> <p>This section describes how Spring Security is integrated with the Servlet API. The <a href="https://github.com/SpringSource/spring-security/blob/master/samples/servletapi-xml">servletapi-xml</a> sample application demonstrates the usage of each of these methods.</p> </div> <div class="sect2"> <h3 id="servletapi-25"><a class="anchor" href="#servletapi-25"></a>3.1. Servlet 2.5+ Integration</h3> <div class="sect3"> <h4 id="servletapi-remote-user"><a class="anchor" href="#servletapi-remote-user"></a>3.1.1. HttpServletRequest.getRemoteUser()</h4> <div class="paragraph"> <p>The <a href="http://docs.oracle.com/javaee/6/api/javax/servlet/http/HttpServletRequest.html#getRemoteUser%28%29">HttpServletRequest.getRemoteUser()</a> will return the result of <code>SecurityContextHolder.getContext().getAuthentication().getName()</code> which is typically the current username. This can be useful if you want to display the current username in your application. Additionally, checking if this is null can be used to indicate if a user has authenticated or is anonymous. Knowing if the user is authenticated or not can be useful for determining if certain UI elements should be shown or not (i.e. a log out link should only be displayed if the user is authenticated).</p> </div> </div> <div class="sect3"> <h4 id="servletapi-user-principal"><a class="anchor" href="#servletapi-user-principal"></a>3.1.2. HttpServletRequest.getUserPrincipal()</h4> <div class="paragraph"> <p>The <a href="http://docs.oracle.com/javaee/6/api/javax/servlet/http/HttpServletRequest.html#getUserPrincipal%28%29">HttpServletRequest.getUserPrincipal()</a> will return the result of <code>SecurityContextHolder.getContext().getAuthentication()</code>. This means it is an <code>Authentication</code> which is typically an instance of <code>UsernamePasswordAuthenticationToken</code> when using username and password based authentication. This can be useful if you need additional information about your user. For example, you might have created a custom <code>UserDetailsService</code> that returns a custom <code>UserDetails</code> containing a first and last name for your user. You could obtain this information with the following:</p> </div> <div class="listingblock"> <div class="content"> <pre style="" class="prettyprint java language-java prettyprinted"><code><span class="typ">Authentication</span><span class="pln"> auth </span><span class="pun">=</span><span class="pln"> httpServletRequest</span><span class="pun">.</span><span class="pln">getUserPrincipal</span><span class="pun">();</span><span class="pln"> </span><span class="com">// assume integrated custom UserDetails called MyCustomUserDetails</span><span class="pln"> </span><span class="com">// by default, typically instance of UserDetails</span><span class="pln"> </span><span class="typ">MyCustomUserDetails</span><span class="pln"> userDetails </span><span class="pun">=</span><span class="pln"> </span><span class="pun">(</span><span class="typ">MyCustomUserDetails</span><span class="pun">)</span><span class="pln"> auth</span><span class="pun">.</span><span class="pln">getPrincipal</span><span class="pun">();</span><span class="pln"> </span><span class="typ">String</span><span class="pln"> firstName </span><span class="pun">=</span><span class="pln"> userDetails</span><span class="pun">.</span><span class="pln">getFirstName</span><span class="pun">();</span><span class="pln"> </span><span class="typ">String</span><span class="pln"> lastName </span><span class="pun">=</span><span class="pln"> userDetails</span><span class="pun">.</span><span class="pln">getLastName</span><span class="pun">();</span></code></pre> </div> </div> <div class="admonitionblock note"> <table> <tbody><tr> <td class="icon"> <i class="icon-note" title="Note"></i> </td> <td class="content"> <div class="paragraph"> <p>It should be noted that it is typically bad practice to perform so much logic throughout your application. Instead, one should centralize it to reduce any coupling of Spring Security and the Servlet API’s.</p> </div> </td> </tr> </tbody></table> </div> </div> <div class="sect3"> <h4 id="servletapi-user-in-role"><a class="anchor" href="#servletapi-user-in-role"></a>3.1.3. HttpServletRequest.isUserInRole(String)</h4> <div class="paragraph"> <p>The <a href="http://docs.oracle.com/javaee/6/api/javax/servlet/http/HttpServletRequest.html#isUserInRole%28java.lang.String%29">HttpServletRequest.isUserInRole(String)</a> will determine if <code>SecurityContextHolder.getContext().getAuthentication().getAuthorities()</code> contains a <code>GrantedAuthority</code> with the role passed into <code>isUserInRole(String)</code>. Typically users should not pass in the "ROLE_" prefix into this method since it is added automatically. For example, if you want to determine if the current user has the authority "ROLE_ADMIN", you could use the the following:</p> </div> <div class="listingblock"> <div class="content"> <pre style="" class="prettyprint java language-java prettyprinted"><code><span class="kwd">boolean</span><span class="pln"> isAdmin </span><span class="pun">=</span><span class="pln"> httpServletRequest</span><span class="pun">.</span><span class="pln">isUserInRole</span><span class="pun">(</span><span class="str">"ADMIN"</span><span class="pun">);</span></code></pre> </div> </div> <div class="paragraph"> <p>This might be useful to determine if certain UI components should be displayed. For example, you might display admin links only if the current user is an admin.</p> </div> </div> </div> <div class="sect2"> <h3 id="servletapi-3"><a class="anchor" href="#servletapi-3"></a>3.2. Servlet 3+ Integration</h3> <div class="paragraph"> <p>The following section describes the Servlet 3 methods that Spring Security integrates with.</p> </div> <div class="sect3"> <h4 id="servletapi-authenticate"><a class="anchor" href="#servletapi-authenticate"></a>3.2.1. HttpServletRequest.authenticate(HttpServletRequest,HttpServletResponse)</h4> <div class="paragraph"> <p>The <a href="http://docs.oracle.com/javaee/6/api/javax/servlet/http/HttpServletRequest.html#authenticate%28javax.servlet.http.HttpServletResponse%29">HttpServletRequest.authenticate(HttpServletRequest,HttpServletResponse)</a> method can be used to ensure that a user is authenticated. If they are not authenticated, the configured AuthenticationEntryPoint will be used to request the user to authenticate (i.e. redirect to the login page).</p> </div> </div> <div class="sect3"> <h4 id="servletapi-login"><a class="anchor" href="#servletapi-login"></a>3.2.2. HttpServletRequest.login(String,String)</h4> <div class="paragraph"> <p>The <a href="http://docs.oracle.com/javaee/6/api/javax/servlet/http/HttpServletRequest.html#login%28java.lang.String,%20java.lang.String%29">HttpServletRequest.login(String,String)</a> method can be used to authenticate the user with the current <code>AuthenticationManager</code>. For example, the following would attempt to authenticate with the username "user" and password "password":</p> </div> <div class="listingblock"> <div class="content"> <pre style="" class="prettyprint java language-java prettyprinted"><code><span class="kwd">try</span><span class="pln"> </span><span class="pun">{</span><span class="pln"> httpServletRequest</span><span class="pun">.</span><span class="pln">login</span><span class="pun">(</span><span class="str">"user"</span><span class="pun">,</span><span class="str">"password"</span><span class="pun">);</span><span class="pln"> </span><span class="pun">}</span><span class="pln"> </span><span class="kwd">catch</span><span class="pun">(</span><span class="typ">ServletException</span><span class="pln"> e</span><span class="pun">)</span><span class="pln"> </span><span class="pun">{</span><span class="pln"> </span><span class="com">// fail to authenticate</span><span class="pln"> </span><span class="pun">}</span></code></pre> </div> </div> <div class="admonitionblock note"> <table> <tbody><tr> <td class="icon"> <i class="icon-note" title="Note"></i> </td> <td class="content"> <div class="paragraph"> <p>It is not necessary to catch the ServletException if you want Spring Security to process the failed authentication attempt.</p> </div> </td> </tr> </tbody></table> </div> </div> <div class="sect3"> <h4 id="servletapi-logout"><a class="anchor" href="#servletapi-logout"></a>3.2.3. HttpServletRequest.logout()</h4> <div class="paragraph"> <p>The <a href="http://docs.oracle.com/javaee/6/api/javax/servlet/http/HttpServletRequest.html#logout%28%29">HttpServletRequest.logout()</a> method can be used to log the current user out.</p> </div> <div class="paragraph"> <p>Typically this means that the SecurityContextHolder will be cleared out, the HttpSession will be invalidated, any "Remember Me" authentication will be cleaned up, etc. However, the configured LogoutHandler implementations will vary depending on your Spring Security configuration. It is important to note that after HttpServletRequest.logout() has been invoked, you are still in charge of writing a response out. Typically this would involve a redirect to the welcome page.</p> </div> </div> <div class="sect3"> <h4 id="servletapi-start-runnable"><a class="anchor" href="#servletapi-start-runnable"></a>3.2.4. AsyncContext.start(Runnable)</h4> <div class="paragraph"> <p>The <a href="http://docs.oracle.com/javaee/6/api/javax/servlet/AsyncContext.html#start%28java.lang.Runnable%29">AsynchContext.start(Runnable)</a> method that ensures your credentials will be propagated to the new Thread. Using Spring Security’s concurrency support, Spring Security overrides the AsyncContext.start(Runnable) to ensure that the current SecurityContext is used when processing the Runnable. For example, the following would output the current user’s Authentication:</p> </div> <div class="listingblock"> <div class="content"> <pre style="" class="prettyprint java language-java prettyprinted"><code><span class="kwd">final</span><span class="pln"> </span><span class="typ">AsyncContext</span><span class="pln"> async </span><span class="pun">=</span><span class="pln"> httpServletRequest</span><span class="pun">.</span><span class="pln">startAsync</span><span class="pun">();</span><span class="pln"> async</span><span class="pun">.</span><span class="pln">start</span><span class="pun">(</span><span class="kwd">new</span><span class="pln"> </span><span class="typ">Runnable</span><span class="pun">()</span><span class="pln"> </span><span class="pun">{</span><span class="pln"> </span><span class="kwd">public</span><span class="pln"> </span><span class="kwd">void</span><span class="pln"> run</span><span class="pun">()</span><span class="pln"> </span><span class="pun">{</span><span class="pln"> </span><span class="typ">Authentication</span><span class="pln"> authentication </span><span class="pun">=</span><span class="pln"> </span><span class="typ">SecurityContextHolder</span><span class="pun">.</span><span class="pln">getContext</span><span class="pun">().</span><span class="pln">getAuthentication</span><span class="pun">();</span><span class="pln"> </span><span class="kwd">try</span><span class="pln"> </span><span class="pun">{</span><span class="pln"> </span><span class="kwd">final</span><span class="pln"> </span><span class="typ">HttpServletResponse</span><span class="pln"> asyncResponse </span><span class="pun">=</span><span class="pln"> </span><span class="pun">(</span><span class="typ">HttpServletResponse</span><span class="pun">)</span><span class="pln"> async</span><span class="pun">.</span><span class="pln">getResponse</span><span class="pun">();</span><span class="pln"> asyncResponse</span><span class="pun">.</span><span class="pln">setStatus</span><span class="pun">(</span><span class="typ">HttpServletResponse</span><span class="pun">.</span><span class="pln">SC_OK</span><span class="pun">);</span><span class="pln"> asyncResponse</span><span class="pun">.</span><span class="pln">getWriter</span><span class="pun">().</span><span class="pln">write</span><span class="pun">(</span><span class="typ">String</span><span class="pun">.</span><span class="pln">valueOf</span><span class="pun">(</span><span class="pln">authentication</span><span class="pun">));</span><span class="pln"> async</span><span class="pun">.</span><span class="pln">complete</span><span class="pun">();</span><span class="pln"> </span><span class="pun">}</span><span class="pln"> </span><span class="kwd">catch</span><span class="pun">(</span><span class="typ">Exception</span><span class="pln"> e</span><span class="pun">)</span><span class="pln"> </span><span class="pun">{</span><span class="pln"> </span><span class="kwd">throw</span><span class="pln"> </span><span class="kwd">new</span><span class="pln"> </span><span class="typ">RuntimeException</span><span class="pun">(</span><span class="pln">e</span><span class="pun">);</span><span class="pln"> </span><span class="pun">}</span><span class="pln"> </span><span class="pun">}</span><span class="pln"> </span><span class="pun">});</span></code></pre> </div> </div> </div> <div class="sect3"> <h4 id="servletapi-async"><a class="anchor" href="#servletapi-async"></a>3.2.5. Async Servlet Support</h4> <div class="paragraph"> <p>If you are using Java Based configuration, you are ready to go. If you are using XML configuration, there are a few updates that are necessary. The first step is to ensure you have updated your web.xml to use at least the 3.0 schema as shown below:</p> </div> <div class="listingblock"> <div class="content"> <pre style="" class="prettyprint xml language-xml prettyprinted"><code><span class="tag"><web-app</span><span class="pln"> </span><span class="atn">xmlns</span><span class="pun">=</span><span class="atv">"http://java.sun.com/xml/ns/javaee"</span><span class="pln"> </span><span class="atn">xmlns:xsi</span><span class="pun">=</span><span class="atv">"http://www.w3.org/2001/XMLSchema-instance"</span><span class="pln"> </span><span class="atn">xsi:schemaLocation</span><span class="pun">=</span><span class="atv">"http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"</span><span class="pln"> </span><span class="atn">version</span><span class="pun">=</span><span class="atv">"3.0"</span><span class="tag">></span><span class="pln"> </span><span class="tag"></web-app></span></code></pre> </div> </div> <div class="paragraph"> <p>Next you need to ensure that your springSecurityFilterChain is setup for processing asynchronous requests.</p> </div> <div class="listingblock"> <div class="content"> <pre style="" class="prettyprint xml language-xml prettyprinted"><code><span class="tag"><filter></span><span class="pln"> </span><span class="tag"><filter-name></span><span class="pln">springSecurityFilterChain</span><span class="tag"></filter-name></span><span class="pln"> </span><span class="tag"><filter-class></span><span class="pln"> org.springframework.web.filter.DelegatingFilterProxy </span><span class="tag"></filter-class></span><span class="pln"> </span><span class="tag"><async-supported></span><span class="pln">true</span><span class="tag"></async-supported></span><span class="pln"> </span><span class="tag"></filter></span><span class="pln"> </span><span class="tag"><filter-mapping></span><span class="pln"> </span><span class="tag"><filter-name></span><span class="pln">springSecurityFilterChain</span><span class="tag"></filter-name></span><span class="pln"> </span><span class="tag"><url-pattern></span><span class="pln">/*</span><span class="tag"></url-pattern></span><span class="pln"> </span><span class="tag"><dispatcher></span><span class="pln">REQUEST</span><span class="tag"></dispatcher></span><span class="pln"> </span><span class="tag"><dispatcher></span><span class="pln">ASYNC</span><span class="tag"></dispatcher></span><span class="pln"> </span><span class="tag"></filter-mapping></span></code></pre> </div> </div> <div class="paragraph"> <p>That’s it! Now Spring Security will ensure that your SecurityContext is propagated on asynchronous requests too.</p> </div> <div class="paragraph"> <p>So how does it work? If you are not really interested, feel free to skip the remainder of this section, otherwise read on. Most of this is built into the Servlet specification, but there is a little bit of tweaking that Spring Security does to ensure things work with asynchronous requests properly. Prior to Spring Security 3.2, the SecurityContext from the SecurityContextHolder was automatically saved as soon as the HttpServletResponse was committed. This can cause issues in a Async environment. For example, consider the following:</p> </div> <div class="listingblock"> <div class="content"> <pre style="" class="prettyprint java language-java prettyprinted"><code><span class="pln">httpServletRequest</span><span class="pun">.</span><span class="pln">startAsync</span><span class="pun">();</span><span class="pln"> </span><span class="kwd">new</span><span class="pln"> </span><span class="typ">Thread</span><span class="pun">(</span><span class="str">"AsyncThread"</span><span class="pun">)</span><span class="pln"> </span><span class="pun">{</span><span class="pln"> </span><span class="lit">@Override</span><span class="pln"> </span><span class="kwd">public</span><span class="pln"> </span><span class="kwd">void</span><span class="pln"> run</span><span class="pun">()</span><span class="pln"> </span><span class="pun">{</span><span class="pln"> </span><span class="kwd">try</span><span class="pln"> </span><span class="pun">{</span><span class="pln"> </span><span class="com">// Do work</span><span class="pln"> </span><span class="typ">TimeUnit</span><span class="pun">.</span><span class="pln">SECONDS</span><span class="pun">.</span><span class="pln">sleep</span><span class="pun">(</span><span class="lit">1</span><span class="pun">);</span><span class="pln"> </span><span class="com">// Write to and commit the httpServletResponse</span><span class="pln"> httpServletResponse</span><span class="pun">.</span><span class="pln">getOutputStream</span><span class="pun">().</span><span class="pln">flush</span><span class="pun">();</span><span class="pln"> </span><span class="pun">}</span><span class="pln"> </span><span class="kwd">catch</span><span class="pln"> </span><span class="pun">(</span><span class="typ">Exception</span><span class="pln"> e</span><span class="pun">)</span><span class="pln"> </span><span class="pun">{</span><span class="pln"> e</span><span class="pun">.</span><span class="pln">printStackTrace</span><span class="pun">();</span><span class="pln"> </span><span class="pun">}</span><span class="pln"> </span><span class="pun">}</span><span class="pln"> </span><span class="pun">}.</span><span class="pln">start</span><span class="pun">();</span></code></pre> </div> </div> <div class="paragraph"> <p>The issue is that this Thread is not known to Spring Security, so the SecurityContext is not propagated to it. This means when we commit the HttpServletResponse there is no SecuriytContext. When Spring Security automatically saved the SecurityContext on committing the HttpServletResponse it would lose our logged in user.</p> </div> <div class="paragraph"> <p>Since version 3.2, Spring Security is smart enough to no longer automatically save the SecurityContext on commiting the HttpServletResponse as soon as HttpServletRequest.startAsync() is invoked.</p> </div> </div> </div> <div class="sect2"> <h3 id="servletapi-31"><a class="anchor" href="#servletapi-31"></a>3.3. Servlet 3.1+ Integration</h3> <div class="paragraph"> <p>The following section describes the Servlet 3.1 methods that Spring Security integrates with.</p> </div> <div class="sect3"> <h4 id="servletapi-change-session-id"><a class="anchor" href="#servletapi-change-session-id"></a>3.3.1. HttpServletRequest#changeSessionId()</h4> <div class="paragraph"> <p>The <a href="http://docs.oracle.com/javaee/7/api/javax/servlet/http/HttpServletRequest.html#changeSessionId%28%29">HttpServletRequest.changeSessionId()</a> is the default method for protecting against <a href="#ns-session-fixation">Session Fixation</a> attacks in Servlet 3.1 and higher.</p> </div> </div> </div> </div> </div> <div class="sect1"> <h2 id="basic"><a class="anchor" href="#basic"></a>4. Basic and Digest Authentication</h2> <div class="sectionbody"> <div class="paragraph"> <p>Basic and digest authentiation are alternative authentication mechanisms which are popular in web applications. Basic authentication is often used with stateless clients which pass their credentials on each request. It’s quite common to use it in combination with form-based authentication where an application is used through both a browser-based user interface and as a web-service. However, basic authentication transmits the password as plain text so it should only really be used over an encrypted transport layer such as HTTPS.</p> </div> <div class="sect2"> <h3 id="basic-processing-filter"><a class="anchor" href="#basic-processing-filter"></a>4.1. BasicAuthenticationFilter</h3> <div class="paragraph"> <p><code>BasicAuthenticationFilter</code> is responsible for processing basic authentication credentials presented in HTTP headers. This can be used for authenticating calls made by Spring remoting protocols (such as Hessian and Burlap), as well as normal browser user agents (such as Firefox and Internet Explorer). The standard governing HTTP Basic Authentication is defined by RFC 1945, Section 11, and <code>BasicAuthenticationFilter</code> conforms with this RFC. Basic Authentication is an attractive approach to authentication, because it is very widely deployed in user agents and implementation is extremely simple (it’s just a Base64 encoding of the username:password, specified in an HTTP header).</p> </div> <div class="sect3"> <h4 id="basic-config"><a class="anchor" href="#basic-config"></a>4.1.1. Configuration</h4> <div class="paragraph"> <p>To implement HTTP Basic Authentication, you need to add a <code>BasicAuthenticationFilter</code> to your filter chain. The application context should contain <code>BasicAuthenticationFilter</code> and its required collaborator:</p> </div> <div class="listingblock"> <div class="content"> <pre style="" class="prettyprint xml language-xml prettyprinted"><code><span class="tag"><bean</span><span class="pln"> </span><span class="atn">id</span><span class="pun">=</span><span class="atv">"basicAuthenticationFilter"</span><span class="pln"> </span><span class="atn">class</span><span class="pun">=</span><span class="atv">"org.springframework.security.web.authentication.www.BasicAuthenticationFilter"</span><span class="tag">></span><span class="pln"> </span><span class="tag"><property</span><span class="pln"> </span><span class="atn">name</span><span class="pun">=</span><span class="atv">"authenticationManager"</span><span class="pln"> </span><span class="atn">ref</span><span class="pun">=</span><span class="atv">"authenticationManager"</span><span class="tag">/></span><span class="pln"> </span><span class="tag"><property</span><span class="pln"> </span><span class="atn">name</span><span class="pun">=</span><span class="atv">"authenticationEntryPoint"</span><span class="pln"> </span><span class="atn">ref</span><span class="pun">=</span><span class="atv">"authenticationEntryPoint"</span><span class="tag">/></span><span class="pln"> </span><span class="tag"></bean></span><span class="pln"> </span><span class="tag"><bean</span><span class="pln"> </span><span class="atn">id</span><span class="pun">=</span><span class="atv">"authenticationEntryPoint"</span><span class="pln"> </span><span class="atn">class</span><span class="pun">=</span><span class="atv">"org.springframework.security.web.authentication.www.BasicAuthenticationEntryPoint"</span><span class="tag">></span><span class="pln"> </span><span class="tag"><property</span><span class="pln"> </span><span class="atn">name</span><span class="pun">=</span><span class="atv">"realmName"</span><span class="pln"> </span><span class="atn">value</span><span class="pun">=</span><span class="atv">"Name Of Your Realm"</span><span class="tag">/></span><span class="pln"> </span><span class="tag"></bean></span></code></pre> </div> </div> <div class="paragraph"> <p>The configured <code>AuthenticationManager</code> processes each authentication request. If authentication fails, the configured <code>AuthenticationEntryPoint</code> will be used to retry the authentication process. Usually you will use the filter in combination with a`BasicAuthenticationEntryPoint`, which returns a 401 response with a suitable header to retry HTTP Basic authentication. If authentication is successful, the resulting <code>Authentication</code> object will be placed into the <code>SecurityContextHolder</code> as usual.</p> </div> <div class="paragraph"> <p>If the authentication event was successful, or authentication was not attempted because the HTTP header did not contain a supported authentication request, the filter chain will continue as normal. The only time the filter chain will be interrupted is if authentication fails and the <code>AuthenticationEntryPoint</code> is called.</p> </div> </div> </div> <div class="sect2"> <h3 id="digest-processing-filter"><a class="anchor" href="#digest-processing-filter"></a>4.2. DigestAuthenticationFilter</h3> <div class="paragraph"> <p><code>DigestAuthenticationFilter</code> is capable of processing digest authentication credentials presented in HTTP headers. Digest Authentication attempts to solve many of the weaknesses of Basic authentication, specifically by ensuring credentials are never sent in clear text across the wire. Many user agents support Digest Authentication, including FireFox and Internet Explorer. The standard governing HTTP Digest Authentication is defined by RFC 2617, which updates an earlier version of the Digest Authentication standard prescribed by RFC 2069. Most user agents implement RFC 2617. Spring Security’s <code>DigestAuthenticationFilter</code> is compatible with the "<code>auth</code>" quality of protection (<code>qop</code>) prescribed by RFC 2617, which also provides backward compatibility with RFC 2069. Digest Authentication is a more attractive option if you need to use unencrypted HTTP (i.e. no TLS/HTTPS) and wish to maximise security of the authentication process. Indeed Digest Authentication is a mandatory requirement for the WebDAV protocol, as noted by RFC 2518 Section 17.1.</p> </div> <div class="paragraph"> <p>Digest Authentication is definitely the most secure choice between Form Authentication, Basic Authentication and Digest Authentication, although extra security also means more complex user agent implementations. Central to Digest Authentication is a "nonce". This is a value the server generates. Spring Security’s nonce adopts the following format:</p> </div> <div class="listingblock"> <div class="content"> <pre style="" class="prettyprint txt language-txt prettyprinted"><code><span class="pln">base64</span><span class="pun">(</span><span class="pln">expirationTime </span><span class="pun">+</span><span class="pln"> </span><span class="str">":"</span><span class="pln"> </span><span class="pun">+</span><span class="pln"> md5Hex</span><span class="pun">(</span><span class="pln">expirationTime </span><span class="pun">+</span><span class="pln"> </span><span class="str">":"</span><span class="pln"> </span><span class="pun">+</span><span class="pln"> key</span><span class="pun">))</span><span class="pln"> expirationTime</span><span class="pun">:</span><span class="pln"> </span><span class="typ">The</span><span class="pln"> date </span><span class="kwd">and</span><span class="pln"> time </span><span class="kwd">when</span><span class="pln"> the nonce expires</span><span class="pun">,</span><span class="pln"> expressed </span><span class="kwd">in</span><span class="pln"> milliseconds key</span><span class="pun">:</span><span class="pln"> A </span><span class="kwd">private</span><span class="pln"> key to prevent modification of the nonce token</span></code></pre> </div> </div> <div class="paragraph"> <p>The <code>DigestAuthenticatonEntryPoint</code> has a property specifying the <code>key</code> used for generating the nonce tokens, along with a <code>nonceValiditySeconds</code> property for determining the expiration time (default 300, which equals five minutes). Whist ever the nonce is valid, the digest is computed by concatenating various strings including the username, password, nonce, URI being requested, a client-generated nonce (merely a random value which the user agent generates each request), the realm name etc, then performing an MD5 hash. Both the server and user agent perform this digest computation, resulting in different hash codes if they disagree on an included value (eg password). In Spring Security implementation, if the server-generated nonce has merely expired (but the digest was otherwise valid), the <code>DigestAuthenticationEntryPoint</code> will send a <code>"stale=true"</code> header. This tells the user agent there is no need to disturb the user (as the password and username etc is correct), but simply to try again using a new nonce.</p> </div> <div class="paragraph"> <p>An appropriate value for <code>DigestAuthenticationEntryPoint</code>'s <code>nonceValiditySeconds</code> parameter will depend on your application. Extremely secure applications should note that an intercepted authentication header can be used to impersonate the principal until the <code>expirationTime</code> contained in the nonce is reached. This is the key principle when selecting an appropriate setting, but it would be unusual for immensely secure applications to not be running over TLS/HTTPS in the first instance.</p> </div> <div class="paragraph"> <p>Because of the more complex implementation of Digest Authentication, there are often user agent issues. For example, Internet Explorer fails to present an "<code>opaque</code>" token on subsequent requests in the same session. Spring Security filters therefore encapsulate all state information into the "<code>nonce</code>" token instead. In our testing, Spring Security’s implementation works reliably with FireFox and Internet Explorer, correctly handling nonce timeouts etc.</p> </div> <div class="sect3"> <h4 id="digest-config"><a class="anchor" href="#digest-config"></a>4.2.1. Configuration</h4> <div class="paragraph"> <p>Now that we’ve reviewed the theory, let’s see how to use it. To implement HTTP Digest Authentication, it is necessary to define <code>DigestAuthenticationFilter</code> in the filter chain. The application context will need to define the <code>DigestAuthenticationFilter</code> and its required collaborators:</p> </div> <div class="listingblock"> <div class="content"> <pre style="" class="prettyprint xml language-xml prettyprinted"><code><span class="tag"><bean</span><span class="pln"> </span><span class="atn">id</span><span class="pun">=</span><span class="atv">"digestFilter"</span><span class="pln"> </span><span class="atn">class</span><span class="pun">=</span><span class="pln"> </span><span class="atv">"org.springframework.security.web.authentication.www.DigestAuthenticationFilter"</span><span class="tag">></span><span class="pln"> </span><span class="tag"><property</span><span class="pln"> </span><span class="atn">name</span><span class="pun">=</span><span class="atv">"userDetailsService"</span><span class="pln"> </span><span class="atn">ref</span><span class="pun">=</span><span class="atv">"jdbcDaoImpl"</span><span class="tag">/></span><span class="pln"> </span><span class="tag"><property</span><span class="pln"> </span><span class="atn">name</span><span class="pun">=</span><span class="atv">"authenticationEntryPoint"</span><span class="pln"> </span><span class="atn">ref</span><span class="pun">=</span><span class="atv">"digestEntryPoint"</span><span class="tag">/></span><span class="pln"> </span><span class="tag"><property</span><span class="pln"> </span><span class="atn">name</span><span class="pun">=</span><span class="atv">"userCache"</span><span class="pln"> </span><span class="atn">ref</span><span class="pun">=</span><span class="atv">"userCache"</span><span class="tag">/></span><span class="pln"> </span><span class="tag"></bean></span><span class="pln"> </span><span class="tag"><bean</span><span class="pln"> </span><span class="atn">id</span><span class="pun">=</span><span class="atv">"digestEntryPoint"</span><span class="pln"> </span><span class="atn">class</span><span class="pun">=</span><span class="pln"> </span><span class="atv">"org.springframework.security.web.authentication.www.DigestAuthenticationEntryPoint"</span><span class="tag">></span><span class="pln"> </span><span class="tag"><property</span><span class="pln"> </span><span class="atn">name</span><span class="pun">=</span><span class="atv">"realmName"</span><span class="pln"> </span><span class="atn">value</span><span class="pun">=</span><span class="atv">"Contacts Realm via Digest Authentication"</span><span class="tag">/></span><span class="pln"> </span><span class="tag"><property</span><span class="pln"> </span><span class="atn">name</span><span class="pun">=</span><span class="atv">"key"</span><span class="pln"> </span><span class="atn">value</span><span class="pun">=</span><span class="atv">"acegi"</span><span class="tag">/></span><span class="pln"> </span><span class="tag"><property</span><span class="pln"> </span><span class="atn">name</span><span class="pun">=</span><span class="atv">"nonceValiditySeconds"</span><span class="pln"> </span><span class="atn">value</span><span class="pun">=</span><span class="atv">"10"</span><span class="tag">/></span><span class="pln"> </span><span class="tag"></bean></span></code></pre> </div> </div> <div class="paragraph"> <p>The configured <code>UserDetailsService</code> is needed because <code>DigestAuthenticationFilter</code> must have direct access to the clear text password of a user. Digest Authentication will NOT work if you are using encoded passwords in your DAO <span class="footnote">[<a id="_footnoteref_17" class="footnote" href="#_footnote_17" title="View footnote.">17</a>]</span>. The DAO collaborator, along with the <code>UserCache</code>, are typically shared directly with a <code>DaoAuthenticationProvider</code>. The <code>authenticationEntryPoint</code> property must be <code>DigestAuthenticationEntryPoint</code>, so that <code>DigestAuthenticationFilter</code> can obtain the correct <code>realmName</code> and <code>key</code> for digest calculations.</p> </div> <div class="paragraph"> <p>Like <code>BasicAuthenticationFilter</code>, if authentication is successful an <code>Authentication</code> request token will be placed into the <code>SecurityContextHolder</code>. If the authentication event was successful, or authentication was not attempted because the HTTP header did not contain a Digest Authentication request, the filter chain will continue as normal. The only time the filter chain will be interrupted is if authentication fails and the <code>AuthenticationEntryPoint</code> is called, as discussed in the previous paragraph.</p> </div> <div class="paragraph"> <p>Digest Authentication’s RFC offers a range of additional features to further increase security. For example, the nonce can be changed on every request. Despite this, Spring Security implementation was designed to minimise the complexity of the implementation (and the doubtless user agent incompatibilities that would emerge), and avoid needing to store server-side state. You are invited to review RFC 2617 if you wish to explore these features in more detail. As far as we are aware, Spring Security’s implementation does comply with the minimum standards of this RFC.</p> </div> </div> </div> </div> </div> <div class="sect1"> <h2 id="remember-me"><a class="anchor" href="#remember-me"></a>5. Remember-Me Authentication</h2> <div class="sectionbody"> <div class="sect2"> <h3 id="remember-me-overview"><a class="anchor" href="#remember-me-overview"></a>5.1. Overview</h3> <div class="paragraph"> <p>Remember-me or persistent-login authentication refers to web sites being able to remember the identity of a principal between sessions. This is typically accomplished by sending a cookie to the browser, with the cookie being detected during future sessions and causing automated login to take place. Spring Security provides the necessary hooks for these operations to take place, and has two concrete remember-me implementations. One uses hashing to preserve the security of cookie-based tokens and the other uses a database or other persistent storage mechanism to store the generated tokens.</p> </div> <div class="paragraph"> <p>Note that both implemementations require a <code>UserDetailsService</code>. If you are using an authentication provider which doesn’t use a <code>UserDetailsService</code> (for example, the LDAP provider) then it won’t work unless you also have a <code>UserDetailsService</code> bean in your application context.</p> </div> </div> <div class="sect2"> <h3 id="remember-me-hash-token"><a class="anchor" href="#remember-me-hash-token"></a>5.2. Simple Hash-Based Token Approach</h3> <div class="paragraph"> <p>This approach uses hashing to achieve a useful remember-me strategy. In essence a cookie is sent to the browser upon successful interactive authentication, with the cookie being composed as follows:</p> </div> <div class="listingblock"> <div class="content"> <pre style="" class="prettyprint txt language-txt prettyprinted"><code><span class="pln">base64</span><span class="pun">(</span><span class="pln">username </span><span class="pun">+</span><span class="pln"> </span><span class="str">":"</span><span class="pln"> </span><span class="pun">+</span><span class="pln"> expirationTime </span><span class="pun">+</span><span class="pln"> </span><span class="str">":"</span><span class="pln"> </span><span class="pun">+</span><span class="pln"> md5Hex</span><span class="pun">(</span><span class="pln">username </span><span class="pun">+</span><span class="pln"> </span><span class="str">":"</span><span class="pln"> </span><span class="pun">+</span><span class="pln"> expirationTime </span><span class="pun">+</span><span class="pln"> </span><span class="str">":"</span><span class="pln"> password </span><span class="pun">+</span><span class="pln"> </span><span class="str">":"</span><span class="pln"> </span><span class="pun">+</span><span class="pln"> key</span><span class="pun">))</span><span class="pln"> username</span><span class="pun">:</span><span class="pln"> </span><span class="typ">As</span><span class="pln"> identifiable to the </span><span class="str">`UserDetailsService`</span><span class="pln"> password</span><span class="pun">:</span><span class="pln"> </span><span class="typ">That</span><span class="pln"> matches the one </span><span class="kwd">in</span><span class="pln"> the retrieved </span><span class="typ">UserDetails</span><span class="pln"> expirationTime</span><span class="pun">:</span><span class="pln"> </span><span class="typ">The</span><span class="pln"> date </span><span class="kwd">and</span><span class="pln"> time </span><span class="kwd">when</span><span class="pln"> the remember</span><span class="pun">-</span><span class="pln">me token expires</span><span class="pun">,</span><span class="pln"> expressed </span><span class="kwd">in</span><span class="pln"> milliseconds key</span><span class="pun">:</span><span class="pln"> A </span><span class="kwd">private</span><span class="pln"> key to prevent modification of the remember</span><span class="pun">-</span><span class="pln">me token</span></code></pre> </div> </div> <div class="paragraph"> <p>As such the remember-me token is valid only for the period specified, and provided that the username, password and key does not change. Notably, this has a potential security issue in that a captured remember-me token will be usable from any user agent until such time as the token expires. This is the same issue as with digest authentication. If a principal is aware a token has been captured, they can easily change their password and immediately invalidate all remember-me tokens on issue. If more significant security is needed you should use the approach described in the next section. Alternatively remember-me services should simply not be used at all.</p> </div> <div class="paragraph"> <p>If you are familiar with the topics discussed in the chapter on <a href="#ns-config">namespace configuration</a>, you can enable remember-me authentication just by adding the <code><remember-me></code> element:</p> </div> <div class="listingblock"> <div class="content"> <pre style="" class="prettyprint xml language-xml prettyprinted"><code><span class="tag"><http></span><span class="pln"> ... </span><span class="tag"><remember-me</span><span class="pln"> </span><span class="atn">key</span><span class="pun">=</span><span class="atv">"myAppKey"</span><span class="tag">/></span><span class="pln"> </span><span class="tag"></http></span></code></pre> </div> </div> <div class="paragraph"> <p>The <code>UserDetailsService</code> will normally be selected automatically. If you have more than one in your application context, you need to specify which one should be used with the <code>user-service-ref</code> attribute, where the value is the name of your <code>UserDetailsService</code> bean.</p> </div> </div> <div class="sect2"> <h3 id="remember-me-persistent-token"><a class="anchor" href="#remember-me-persistent-token"></a>5.3. Persistent Token Approach</h3> <div class="paragraph"> <p>This approach is based on the article <a href="http://jaspan.com/improved_persistent_login_cookie_best_practice">http://jaspan.com/improved_persistent_login_cookie_best_practice</a> with some minor modifications <span class="footnote">[<a id="_footnoteref_18" class="footnote" href="#_footnote_18" title="View footnote.">18</a>]</span>. To use the this approach with namespace configuration, you would supply a datasource reference:</p> </div> <div class="listingblock"> <div class="content"> <pre style="" class="prettyprint xml language-xml prettyprinted"><code><span class="tag"><http></span><span class="pln"> ... </span><span class="tag"><remember-me</span><span class="pln"> </span><span class="atn">data-source-ref</span><span class="pun">=</span><span class="atv">"someDataSource"</span><span class="tag">/></span><span class="pln"> </span><span class="tag"></http></span></code></pre> </div> </div> <div class="paragraph"> <p>The database should contain a <code>persistent_logins</code> table, created using the following SQL (or equivalent):</p> </div> <div class="listingblock"> <div class="content"> <pre style="" class="prettyprint ddl language-ddl prettyprinted"><code><span class="pln">create table persistent_logins </span><span class="pun">(</span><span class="pln">username varchar</span><span class="pun">(</span><span class="lit">64</span><span class="pun">)</span><span class="pln"> </span><span class="kwd">not</span><span class="pln"> </span><span class="kwd">null</span><span class="pun">,</span><span class="pln"> series varchar</span><span class="pun">(</span><span class="lit">64</span><span class="pun">)</span><span class="pln"> primary key</span><span class="pun">,</span><span class="pln"> token varchar</span><span class="pun">(</span><span class="lit">64</span><span class="pun">)</span><span class="pln"> </span><span class="kwd">not</span><span class="pln"> </span><span class="kwd">null</span><span class="pun">,</span><span class="pln"> last_used timestamp </span><span class="kwd">not</span><span class="pln"> </span><span class="kwd">null</span><span class="pun">)</span></code></pre> </div> </div> </div> <div class="sect2"> <h3 id="remember-me-impls"><a class="anchor" href="#remember-me-impls"></a>5.4. Remember-Me Interfaces and Implementations</h3> <div class="paragraph"> <p>Remember-me authentication is not used with basic authentication, given it is often not used with <code>HttpSession</code> s. Remember-me is used with <code>UsernamePasswordAuthenticationFilter</code>, and is implemented via hooks in the <code>AbstractAuthenticationProcessingFilter</code> superclass. The hooks will invoke a concrete <code>RememberMeServices</code> at the appropriate times. The interface looks like this:</p> </div> <div class="listingblock"> <div class="content"> <pre style="" class="prettyprint java language-java prettyprinted"><code><span class="typ">Authentication</span><span class="pln"> autoLogin</span><span class="pun">(</span><span class="typ">HttpServletRequest</span><span class="pln"> request</span><span class="pun">,</span><span class="pln"> </span><span class="typ">HttpServletResponse</span><span class="pln"> response</span><span class="pun">);</span><span class="pln"> </span><span class="kwd">void</span><span class="pln"> loginFail</span><span class="pun">(</span><span class="typ">HttpServletRequest</span><span class="pln"> request</span><span class="pun">,</span><span class="pln"> </span><span class="typ">HttpServletResponse</span><span class="pln"> response</span><span class="pun">);</span><span class="pln"> </span><span class="kwd">void</span><span class="pln"> loginSuccess</span><span class="pun">(</span><span class="typ">HttpServletRequest</span><span class="pln"> request</span><span class="pun">,</span><span class="pln"> </span><span class="typ">HttpServletResponse</span><span class="pln"> response</span><span class="pun">,</span><span class="pln"> </span><span class="typ">Authentication</span><span class="pln"> successfulAuthentication</span><span class="pun">);</span></code></pre> </div> </div> <div class="paragraph"> <p>Please refer to the JavaDocs for a fuller discussion on what the methods do, although note at this stage that <code>AbstractAuthenticationProcessingFilter</code> only calls the <code>loginFail()</code> and <code>loginSuccess()</code> methods. The <code>autoLogin()</code> method is called by <code>RememberMeAuthenticationFilter</code> whenever the <code>SecurityContextHolder</code> does not contain an <code>Authentication</code>. This interface therefore provides the underlying remember-me implementation with sufficient notification of authentication-related events, and delegates to the implementation whenever a candidate web request might contain a cookie and wish to be remembered. This design allows any number of remember-me implementation strategies. We’ve seen above that Spring Security provides two implementations. We’ll look at these in turn.</p> </div> <div class="sect3"> <h4 id="tokenbasedremembermeservices"><a class="anchor" href="#tokenbasedremembermeservices"></a>5.4.1. TokenBasedRememberMeServices</h4> <div class="paragraph"> <p>This implementation supports the simpler approach described in <a href="#remember-me-hash-token">Simple Hash-Based Token Approach</a>. <code>TokenBasedRememberMeServices</code> generates a <code>RememberMeAuthenticationToken</code>, which is processed by <code>RememberMeAuthenticationProvider</code>. A <code>key</code> is shared between this authentication provider and the <code>TokenBasedRememberMeServices</code>. In addition, <code>TokenBasedRememberMeServices</code> requires A UserDetailsService from which it can retrieve the username and password for signature comparison purposes, and generate the <code>RememberMeAuthenticationToken</code> to contain the correct <code>GrantedAuthority</code> s. Some sort of logout command should be provided by the application that invalidates the cookie if the user requests this. <code>TokenBasedRememberMeServices</code> also implements Spring Security’s <code>LogoutHandler</code> interface so can be used with <code>LogoutFilter</code> to have the cookie cleared automatically.</p> </div> <div class="paragraph"> <p>The beans required in an application context to enable remember-me services are as follows:</p> </div> <div class="listingblock"> <div class="content"> <pre style="" class="prettyprint xml language-xml prettyprinted"><code><span class="tag"><bean</span><span class="pln"> </span><span class="atn">id</span><span class="pun">=</span><span class="atv">"rememberMeFilter"</span><span class="pln"> </span><span class="atn">class</span><span class="pun">=</span><span class="pln"> </span><span class="atv">"org.springframework.security.web.authentication.rememberme.RememberMeAuthenticationFilter"</span><span class="tag">></span><span class="pln"> </span><span class="tag"><property</span><span class="pln"> </span><span class="atn">name</span><span class="pun">=</span><span class="atv">"rememberMeServices"</span><span class="pln"> </span><span class="atn">ref</span><span class="pun">=</span><span class="atv">"rememberMeServices"</span><span class="tag">/></span><span class="pln"> </span><span class="tag"><property</span><span class="pln"> </span><span class="atn">name</span><span class="pun">=</span><span class="atv">"authenticationManager"</span><span class="pln"> </span><span class="atn">ref</span><span class="pun">=</span><span class="atv">"theAuthenticationManager"</span><span class="pln"> </span><span class="tag">/></span><span class="pln"> </span><span class="tag"></bean></span><span class="pln"> </span><span class="tag"><bean</span><span class="pln"> </span><span class="atn">id</span><span class="pun">=</span><span class="atv">"rememberMeServices"</span><span class="pln"> </span><span class="atn">class</span><span class="pun">=</span><span class="pln"> </span><span class="atv">"org.springframework.security.web.authentication.rememberme.TokenBasedRememberMeServices"</span><span class="tag">></span><span class="pln"> </span><span class="tag"><property</span><span class="pln"> </span><span class="atn">name</span><span class="pun">=</span><span class="atv">"userDetailsService"</span><span class="pln"> </span><span class="atn">ref</span><span class="pun">=</span><span class="atv">"myUserDetailsService"</span><span class="tag">/></span><span class="pln"> </span><span class="tag"><property</span><span class="pln"> </span><span class="atn">name</span><span class="pun">=</span><span class="atv">"key"</span><span class="pln"> </span><span class="atn">value</span><span class="pun">=</span><span class="atv">"springRocks"</span><span class="tag">/></span><span class="pln"> </span><span class="tag"></bean></span><span class="pln"> </span><span class="tag"><bean</span><span class="pln"> </span><span class="atn">id</span><span class="pun">=</span><span class="atv">"rememberMeAuthenticationProvider"</span><span class="pln"> </span><span class="atn">class</span><span class="pun">=</span><span class="pln"> </span><span class="atv">"org.springframework.security.authentication.rememberme.RememberMeAuthenticationProvider"</span><span class="tag">></span><span class="pln"> </span><span class="tag"><property</span><span class="pln"> </span><span class="atn">name</span><span class="pun">=</span><span class="atv">"key"</span><span class="pln"> </span><span class="atn">value</span><span class="pun">=</span><span class="atv">"springRocks"</span><span class="tag">/></span><span class="pln"> </span><span class="tag"></bean></span></code></pre> </div> </div> <div class="paragraph"> <p>Don’t forget to add your <code>RememberMeServices</code> implementation to your <code>UsernamePasswordAuthenticationFilter.setRememberMeServices()</code> property, include the <code>RememberMeAuthenticationProvider</code> in your <code>AuthenticationManager.setProviders()</code> list, and add <code>RememberMeAuthenticationFilter</code> into your <code>FilterChainProxy</code> (typically immediately after your <code>UsernamePasswordAuthenticationFilter</code>).</p> </div> </div> <div class="sect3"> <h4 id="persistenttokenbasedremembermeservices"><a class="anchor" href="#persistenttokenbasedremembermeservices"></a>5.4.2. PersistentTokenBasedRememberMeServices</h4> <div class="paragraph"> <p>This class can be used in the same way as <code>TokenBasedRememberMeServices</code>, but it additionally needs to be configured with a <code>PersistentTokenRepository</code> to store the tokens. There are two standard implementations.</p> </div> <div class="ulist"> <ul> <li> <p><code>InMemoryTokenRepositoryImpl</code> which is intended for testing only.</p> </li> <li> <p><code>JdbcTokenRepositoryImpl</code> which stores the tokens in a database.</p> </li> </ul> </div> <div class="paragraph"> <p>The database schema is described above in <a href="#remember-me-persistent-token">Persistent Token Approach</a>.</p> </div> </div> </div> </div> </div> <div class="sect1"> <h2 id="csrf"><a class="anchor" href="#csrf"></a>6. Cross Site Request Forgery (CSRF)</h2> <div class="sectionbody"> <div class="paragraph"> <p>This section discusses Spring Security’s <a href="http://en.wikipedia.org/wiki/Cross-site_request_forgery"> Cross Site Request Forgery (CSRF)</a> support.</p> </div> <div class="sect2"> <h3 id="csrf-attacks"><a class="anchor" href="#csrf-attacks"></a>6.1. CSRF Attacks</h3> <div class="paragraph"> <p>Before we discuss how Spring Security can protect applications from CSRF attacks, we will explain what a CSRF attack is. Let’s take a look at a concrete example to get a better understanding.</p> </div> <div class="paragraph"> <p>Assume that your bank’s website provides a form that allows transferring money from the currently logged in user to another bank account. For example, the HTTP request might look like:</p> </div> <div class="listingblock"> <div class="content"> <pre style="" class="prettyprint prettyprinted"><code><span class="pln">POST </span><span class="pun">/</span><span class="pln">transfer HTTP</span><span class="pun">/</span><span class="lit">1.1</span><span class="pln"> </span><span class="typ">Host</span><span class="pun">:</span><span class="pln"> bank</span><span class="pun">.</span><span class="pln">example</span><span class="pun">.</span><span class="pln">com </span><span class="typ">Cookie</span><span class="pun">:</span><span class="pln"> JSESSIONID</span><span class="pun">=</span><span class="pln">randomid</span><span class="pun">;</span><span class="pln"> </span><span class="typ">Domain</span><span class="pun">=</span><span class="pln">bank</span><span class="pun">.</span><span class="pln">example</span><span class="pun">.</span><span class="pln">com</span><span class="pun">;</span><span class="pln"> </span><span class="typ">Secure</span><span class="pun">;</span><span class="pln"> </span><span class="typ">HttpOnly</span><span class="pln"> </span><span class="typ">Content</span><span class="pun">-</span><span class="typ">Type</span><span class="pun">:</span><span class="pln"> application</span><span class="pun">/</span><span class="pln">x</span><span class="pun">-</span><span class="pln">www</span><span class="pun">-</span><span class="pln">form</span><span class="pun">-</span><span class="pln">urlencoded amount</span><span class="pun">=</span><span class="lit">100.00</span><span class="pun">&</span><span class="pln">routingNumber</span><span class="pun">=</span><span class="lit">1234</span><span class="pun">&</span><span class="pln">account</span><span class="pun">=</span><span class="lit">9876</span></code></pre> </div> </div> <div class="paragraph"> <p>Now pretend you authenticate to your bank’s website and then, without logging out, visit an evil website. The evil website contains an HTML page with the following form:</p> </div> <div class="listingblock"> <div class="content"> <pre style="" class="prettyprint xml language-xml prettyprinted"><code><span class="tag"><form</span><span class="pln"> </span><span class="atn">action</span><span class="pun">=</span><span class="atv">"https://bank.example.com/transfer"</span><span class="pln"> </span><span class="atn">method</span><span class="pun">=</span><span class="atv">"post"</span><span class="tag">></span><span class="pln"> </span><span class="tag"><input</span><span class="pln"> </span><span class="atn">type</span><span class="pun">=</span><span class="atv">"hidden"</span><span class="pln"> </span><span class="atn">name</span><span class="pun">=</span><span class="atv">"amount"</span><span class="pln"> </span><span class="atn">value</span><span class="pun">=</span><span class="atv">"100.00"</span><span class="tag">/></span><span class="pln"> </span><span class="tag"><input</span><span class="pln"> </span><span class="atn">type</span><span class="pun">=</span><span class="atv">"hidden"</span><span class="pln"> </span><span class="atn">name</span><span class="pun">=</span><span class="atv">"routingNumber"</span><span class="pln"> </span><span class="atn">value</span><span class="pun">=</span><span class="atv">"evilsRoutingNumber"</span><span class="tag">/></span><span class="pln"> </span><span class="tag"><input</span><span class="pln"> </span><span class="atn">type</span><span class="pun">=</span><span class="atv">"hidden"</span><span class="pln"> </span><span class="atn">name</span><span class="pun">=</span><span class="atv">"account"</span><span class="pln"> </span><span class="atn">value</span><span class="pun">=</span><span class="atv">"evilsAccountNumber"</span><span class="tag">/></span><span class="pln"> </span><span class="tag"><input</span><span class="pln"> </span><span class="atn">type</span><span class="pun">=</span><span class="atv">"submit"</span><span class="pln"> </span><span class="atn">value</span><span class="pun">=</span><span class="atv">"Win Money!"</span><span class="tag">/></span><span class="pln"> </span><span class="tag"></form></span></code></pre> </div> </div> <div class="paragraph"> <p>You like to win money, so you click on the submit button. In the process, you have unintentionally transferred $100 to a malicious user. This happens because, while the evil website cannot see your cookies, the cookies associated with your bank are still sent along with the request.</p> </div> <div class="paragraph"> <p>Worst yet, this whole process could have been automated using JavaScript. This means you didn’t even need to click on the button. So how do we protect ourselves from such attacks?</p> </div> </div> <div class="sect2"> <h3 id="synchronizer-token-pattern"><a class="anchor" href="#synchronizer-token-pattern"></a>6.2. Synchronizer Token Pattern</h3> <div class="paragraph"> <p>The issue is that the HTTP request from the bank’s website and the request from the evil website are exactly the same. This means there is no way to reject requests coming from the evil website and allow requests coming from the bank’s website. To protect against CSRF attacks we need to ensure there is something in the request that the evil site is unable to provide.</p> </div> <div class="paragraph"> <p>One solution is to use the <a href="https://www.owasp.org/index.php/Cross-Site_Request_Forgery_%28CSRF%29_Prevention_Cheat_Sheet#General_Recommendation:_Synchronizer_Token_Pattern">Synchronizer Token Pattern</a>. This solution is to ensure that each request requires, in addition to our session cookie, a randomly generated token as an HTTP parameter. When a request is submitted, the server must look up the expected value for the parameter and compare it against the actual value in the request. If the values do not match, the request should fail.</p> </div> <div class="paragraph"> <p>We can relax the expectations to only require the token for each HTTP request that updates state. This can be safely done since the same origin policy ensures the evil site cannot read the response. Additionally, we do not want to include the random token in HTTP GET as this can cause the tokens to be leaked.</p> </div> <div class="paragraph"> <p>Let’s take a look at how our example would change. Assume the randomly generated token is present in an HTTP parameter named _csrf. For example, the request to transfer money would look like this:</p> </div> <div class="listingblock"> <div class="content"> <pre style="" class="prettyprint prettyprinted"><code><span class="pln">POST </span><span class="pun">/</span><span class="pln">transfer HTTP</span><span class="pun">/</span><span class="lit">1.1</span><span class="pln"> </span><span class="typ">Host</span><span class="pun">:</span><span class="pln"> bank</span><span class="pun">.</span><span class="pln">example</span><span class="pun">.</span><span class="pln">com </span><span class="typ">Cookie</span><span class="pun">:</span><span class="pln"> JSESSIONID</span><span class="pun">=</span><span class="pln">randomid</span><span class="pun">;</span><span class="pln"> </span><span class="typ">Domain</span><span class="pun">=</span><span class="pln">bank</span><span class="pun">.</span><span class="pln">example</span><span class="pun">.</span><span class="pln">com</span><span class="pun">;</span><span class="pln"> </span><span class="typ">Secure</span><span class="pun">;</span><span class="pln"> </span><span class="typ">HttpOnly</span><span class="pln"> </span><span class="typ">Content</span><span class="pun">-</span><span class="typ">Type</span><span class="pun">:</span><span class="pln"> application</span><span class="pun">/</span><span class="pln">x</span><span class="pun">-</span><span class="pln">www</span><span class="pun">-</span><span class="pln">form</span><span class="pun">-</span><span class="pln">urlencoded amount</span><span class="pun">=</span><span class="lit">100.00</span><span class="pun">&</span><span class="pln">routingNumber</span><span class="pun">=</span><span class="lit">1234</span><span class="pun">&</span><span class="pln">account</span><span class="pun">=</span><span class="lit">9876</span><span class="pun">&</span><span class="pln">_csrf</span><span class="pun">=<</span><span class="pln">secure</span><span class="pun">-</span><span class="pln">random</span><span class="pun">></span></code></pre> </div> </div> <div class="paragraph"> <p>You will notice that we added the _csrf parameter with a random value. Now the evil website will not be able to guess the correct value for the _csrf parameter (which must be explicitly provided on the evil website) and the transfer will fail when the server compares the actual token to the expected token.</p> </div> </div> <div class="sect2"> <h3 id="when-to-use-csrf-protection"><a class="anchor" href="#when-to-use-csrf-protection"></a>6.3. When to use CSRF protection</h3> <div class="paragraph"> <p>When you use CSRF protection? Our recommendation is to use CSRF protection for any request that could be processed by a browser by normal users. If you are only creating a service that is used by non-browser clients, you will likely want to disable CSRF protection.</p> </div> <div class="sect3"> <h4 id="csrf-protection-and-json"><a class="anchor" href="#csrf-protection-and-json"></a>6.3.1. CSRF protection and JSON</h4> <div class="paragraph"> <p>A common question is, but do I need to protect JSON requests made by javascript? The short answer is, it depends. However, you must be very careful as there are CSRF exploits that can impact JSON requests. For example, a malicious user can create a <a href="http://blog.opensecurityresearch.com/2012/02/json-csrf-with-parameter-padding.html">CSRF with JSON using the following form</a>:</p> </div> <div class="listingblock"> <div class="content"> <pre style="" class="prettyprint xml language-xml prettyprinted"><code><span class="tag"><form</span><span class="pln"> </span><span class="atn">action</span><span class="pun">=</span><span class="atv">"https://bank.example.com/transfer"</span><span class="pln"> </span><span class="atn">method</span><span class="pun">=</span><span class="atv">"post"</span><span class="pln"> </span><span class="atn">enctype</span><span class="pun">=</span><span class="atv">"text/plain"</span><span class="tag">></span><span class="pln"> </span><span class="tag"><input</span><span class="pln"> </span><span class="atn">name</span><span class="pun">=</span><span class="atv">'{"amount":100,"routingNumber":"evilsRoutingNumber","account":"evilsAccountNumber", "ignore_me":"'</span><span class="pln"> </span><span class="atn">value</span><span class="pun">=</span><span class="atv">'test"}'</span><span class="pln"> </span><span class="atn">type</span><span class="pun">=</span><span class="atv">'hidden'</span><span class="tag">></span><span class="pln"> </span><span class="tag"><input</span><span class="pln"> </span><span class="atn">type</span><span class="pun">=</span><span class="atv">"submit"</span><span class="pln"> </span><span class="atn">value</span><span class="pun">=</span><span class="atv">"Win Money!"</span><span class="tag">/></span><span class="pln"> </span><span class="tag"></form></span></code></pre> </div> </div> <div class="paragraph"> <p>This will produce the following JSON structure</p> </div> <div class="listingblock"> <div class="content"> <pre style="" class="prettyprint javascript language-javascript prettyprinted"><code><span class="pun">{</span><span class="pln"> </span><span class="str">"amount"</span><span class="pun">:</span><span class="pln"> </span><span class="lit">100</span><span class="pun">,</span><span class="pln"> </span><span class="str">"routingNumber"</span><span class="pun">:</span><span class="pln"> </span><span class="str">"evilsRoutingNumber"</span><span class="pun">,</span><span class="pln"> </span><span class="str">"account"</span><span class="pun">:</span><span class="pln"> </span><span class="str">"evilsAccountNumber"</span><span class="pun">,</span><span class="pln"> </span><span class="str">"ignore_me"</span><span class="pun">:</span><span class="pln"> </span><span class="str">"=test"</span><span class="pln"> </span><span class="pun">}</span></code></pre> </div> </div> <div class="paragraph"> <p>If an application were not validating the Content-Type, then it would be exposed to this exploit. Depending on the setup, a Spring MVC application that validates the Content-Type could still be exploited by updating the URL suffix to end with ".json" as shown below:</p> </div> <div class="listingblock"> <div class="content"> <pre style="" class="prettyprint xml language-xml prettyprinted"><code><span class="tag"><form</span><span class="pln"> </span><span class="atn">action</span><span class="pun">=</span><span class="atv">"https://bank.example.com/transfer.json"</span><span class="pln"> </span><span class="atn">method</span><span class="pun">=</span><span class="atv">"post"</span><span class="pln"> </span><span class="atn">enctype</span><span class="pun">=</span><span class="atv">"text/plain"</span><span class="tag">></span><span class="pln"> </span><span class="tag"><input</span><span class="pln"> </span><span class="atn">name</span><span class="pun">=</span><span class="atv">'{"amount":100,"routingNumber":"evilsRoutingNumber","account":"evilsAccountNumber", "ignore_me":"'</span><span class="pln"> </span><span class="atn">value</span><span class="pun">=</span><span class="atv">'test"}'</span><span class="pln"> </span><span class="atn">type</span><span class="pun">=</span><span class="atv">'hidden'</span><span class="tag">></span><span class="pln"> </span><span class="tag"><input</span><span class="pln"> </span><span class="atn">type</span><span class="pun">=</span><span class="atv">"submit"</span><span class="pln"> </span><span class="atn">value</span><span class="pun">=</span><span class="atv">"Win Money!"</span><span class="tag">/></span><span class="pln"> </span><span class="tag"></form></span></code></pre> </div> </div> </div> <div class="sect3"> <h4 id="csrf-and-stateless-browser-applications"><a class="anchor" href="#csrf-and-stateless-browser-applications"></a>6.3.2. CSRF and Stateless Browser Applications</h4> <div class="paragraph"> <p>What if my application is stateless? That doesn’t necessarily mean you are protected. In fact, if a user does not need to perform any actions in the web browser for a given request, they are likely still vulnerable to CSRF attacks.</p> </div> <div class="paragraph"> <p>For example, consider an application uses a custom cookie that contains all the state within it for authentication instead of the JSESSIONID. When the CSRF attack is made the custom cookie will be sent with the request in the same manner that the JSESSIONID cookie was sent in our previous example.</p> </div> <div class="paragraph"> <p>User’s using basic authentication are also vulnerable to CSRF attacks since the browser will automatically include the username password in any requests in the same manner that the JSESSIONID cookie was sent in our previous example.</p> </div> </div> </div> <div class="sect2"> <h3 id="csrf-using"><a class="anchor" href="#csrf-using"></a>6.4. Using Spring Security CSRF Protection</h3> <div class="paragraph"> <p>So what are the steps necessary to use Spring Security’s to protect our site against CSRF attacks? The steps to using Spring Security’s CSRF protection are outlined below:</p> </div> <div class="ulist"> <ul> <li> <p><a href="#csrf-use-proper-verbs">Use proper HTTP verbs</a></p> </li> <li> <p><a href="#csrf-configure">Configure CSRF Protection</a></p> </li> <li> <p><a href="#csrf-include-csrf-token">Include the CSRF Token</a></p> </li> </ul> </div> <div class="sect3"> <h4 id="csrf-use-proper-verbs"><a class="anchor" href="#csrf-use-proper-verbs"></a>6.4.1. Use proper HTTP verbs</h4> <div class="paragraph"> <p>The first step to protecting against CSRF attacks is to ensure your website uses proper HTTP verbs. Specifically, before Spring Security’s CSRF support can be of use, you need to be certain that your application is using PATCH, POST, PUT, and/or DELETE for anything that modifies state.</p> </div> <div class="paragraph"> <p>This is not a limitation of Spring Security’s support, but instead a general requirement for proper CSRF prevention. The reason is that including private information in an HTTP GET can cause the information to be leaked. See <a href="http://www.w3.org/Protocols/rfc2616/rfc2616-sec15.html#sec15.1.3">RFC 2616 Section 15.1.3 Encoding Sensitive Information in URI’s</a> for general guidance on using POST instead of GET for sensitive information.</p> </div> </div> <div class="sect3"> <h4 id="csrf-configure"><a class="anchor" href="#csrf-configure"></a>6.4.2. Configure CSRF Protection</h4> <div class="paragraph"> <p>The next step is to include Spring Security’s CSRF protection within your application. Some frameworks handle invalid CSRF tokens by invaliding the user’s session, but this causes <a href="#csrf-logout">its own problems</a>. Instead by default Spring Security’s CSRF protection will produce an HTTP 403 access denied. This can be customized by configuring the <a href="#access-denied-handler">AccessDeniedHandler</a> to process <code>InvalidCsrfTokenException</code> differently.</p> </div> <div class="paragraph"> <p>For passivity reasons, if you are using the XML configuration, CSRF protection must be explicitly enabled using the <a href="#nsa-csrf"><csrf</a>> element. Refer to the <a href="#nsa-csrf"><csrf</a>> element’s documentation for additional customizations.</p> </div> <div class="admonitionblock note"> <table> <tbody><tr> <td class="icon"> <i class="icon-note" title="Note"></i> </td> <td class="content"> <div class="paragraph"> <p><a href="https://jira.springsource.org/browse/SEC-2347">SEC-2347</a> is logged to ensure Spring Security 4.x’s XML namespace configuration will enable CSRF protection by default.</p> </div> </td> </tr> </tbody></table> </div> <div class="listingblock"> <div class="content"> <pre style="" class="prettyprint xml language-xml prettyprinted"><code><span class="tag"><http></span><span class="pln"> </span><span class="com"><!-- ... --></span><span class="pln"> </span><span class="tag"><csrf</span><span class="pln"> </span><span class="tag">/></span><span class="pln"> </span><span class="tag"></http></span></code></pre> </div> </div> <div class="paragraph"> <p>CSRF protection is enabled by default with Java configuration. If you would like to disable CSRF, the corresponding Java configuration can be seen below. Refer to the Javadoc of csrf() for additional customizations in how CSRF protection is configured.</p> </div> <div class="listingblock"> <div class="content"> <pre style="" class="prettyprint java language-java prettyprinted"><code><span class="lit">@EnableWebSecurity</span><span class="pln"> </span><span class="lit">@Configuration</span><span class="pln"> </span><span class="kwd">public</span><span class="pln"> </span><span class="kwd">class</span><span class="pln"> </span><span class="typ">WebSecurityConfig</span><span class="pln"> </span><span class="kwd">extends</span><span class="pln"> </span><span class="typ">WebSecurityConfigurerAdapter</span><span class="pln"> </span><span class="pun">{</span><span class="pln"> </span><span class="lit">@Override</span><span class="pln"> </span><span class="kwd">protected</span><span class="pln"> </span><span class="kwd">void</span><span class="pln"> configure</span><span class="pun">(</span><span class="typ">HttpSecurity</span><span class="pln"> http</span><span class="pun">)</span><span class="pln"> </span><span class="kwd">throws</span><span class="pln"> </span><span class="typ">Exception</span><span class="pln"> </span><span class="pun">{</span><span class="pln"> http </span><span class="pun">.</span><span class="pln">csrf</span><span class="pun">().</span><span class="pln">disable</span><span class="pun">();</span><span class="pln"> </span><span class="pun">}</span><span class="pln"> </span><span class="pun">}</span></code></pre> </div> </div> </div> <div class="sect3"> <h4 id="csrf-include-csrf-token"><a class="anchor" href="#csrf-include-csrf-token"></a>6.4.3. Include the CSRF Token</h4> <div class="sect4"> <h5 id="csrf-include-csrf-token-form"><a class="anchor" href="#csrf-include-csrf-token-form"></a>Form Submissions</h5> <div class="paragraph"> <p>The last step is to ensure that you include the CSRF token in all PATCH, POST, PUT, and DELETE methods. One way to approach this is to use the <code>_csrf</code> request attribute to obtain the current <code>CsrfToken</code>. An example of doing this with a JSP is shown below:</p> </div> <div class="listingblock"> <div class="content"> <pre style="" class="prettyprint xml language-xml prettyprinted"><code><span class="tag"><c:url</span><span class="pln"> </span><span class="atn">var</span><span class="pun">=</span><span class="atv">"logoutUrl"</span><span class="pln"> </span><span class="atn">value</span><span class="pun">=</span><span class="atv">"/logout"</span><span class="tag">/></span><span class="pln"> </span><span class="tag"><form</span><span class="pln"> </span><span class="atn">action</span><span class="pun">=</span><span class="atv">"${logoutUrl}"</span><span class="pln"> </span><span class="atn">method</span><span class="pun">=</span><span class="atv">"post"</span><span class="tag">></span><span class="pln"> </span><span class="tag"><input</span><span class="pln"> </span><span class="atn">type</span><span class="pun">=</span><span class="atv">"submit"</span><span class="pln"> </span><span class="atn">value</span><span class="pun">=</span><span class="atv">"Log out"</span><span class="pln"> </span><span class="tag">/></span><span class="pln"> </span><span class="tag"><input</span><span class="pln"> </span><span class="atn">type</span><span class="pun">=</span><span class="atv">"hidden"</span><span class="pln"> </span><span class="atn">name</span><span class="pun">=</span><span class="atv">"${_csrf.parameterName}"</span><span class="pln"> </span><span class="atn">value</span><span class="pun">=</span><span class="atv">"${_csrf.token}"</span><span class="tag">/></span><span class="pln"> </span><span class="tag"></form></span></code></pre> </div> </div> <div class="paragraph"> <p>An easier approach is to use <a href="#the-csrfInput-tag">the csrfInput tag</a> from the Spring Security JSP tag library.</p> </div> <div class="admonitionblock note"> <table> <tbody><tr> <td class="icon"> <i class="icon-note" title="Note"></i> </td> <td class="content"> <div class="paragraph"> <p>If you are using Spring MVC <code><form:form></code> tag or <a href="http://www.thymeleaf.org/whatsnew21.html#reqdata">Thymeleaf 2.1+</a>, and you replace <code>@EnableWebSecurity</code> with <code>@EnableWebMvcSecurity</code>, the <code>CsrfToken</code> is automatically included for you (using the <code>CsrfRequestDataValueProcessor</code>).</p> </div> </td> </tr> </tbody></table> </div> </div> <div class="sect4"> <h5 id="csrf-include-csrf-token-ajax"><a class="anchor" href="#csrf-include-csrf-token-ajax"></a>Ajax and JSON Requests</h5> <div class="paragraph"> <p>If you using JSON, then it is not possible to submit the CSRF token within an HTTP parameter. Instead you can submit the token within a HTTP header. A typical pattern would be to include the CSRF token within your meta tags. An example with a JSP is shown below:</p> </div> <div class="listingblock"> <div class="content"> <pre style="" class="prettyprint xml language-xml prettyprinted"><code><span class="tag"><html></span><span class="pln"> </span><span class="tag"><head></span><span class="pln"> </span><span class="tag"><meta</span><span class="pln"> </span><span class="atn">name</span><span class="pun">=</span><span class="atv">"_csrf"</span><span class="pln"> </span><span class="atn">content</span><span class="pun">=</span><span class="atv">"${_csrf.token}"</span><span class="tag">/></span><span class="pln"> </span><span class="com"><!-- default header name is X-CSRF-TOKEN --></span><span class="pln"> </span><span class="tag"><meta</span><span class="pln"> </span><span class="atn">name</span><span class="pun">=</span><span class="atv">"_csrf_header"</span><span class="pln"> </span><span class="atn">content</span><span class="pun">=</span><span class="atv">"${_csrf.headerName}"</span><span class="tag">/></span><span class="pln"> </span><span class="com"><!-- ... --></span><span class="pln"> </span><span class="tag"></head></span><span class="pln"> </span><span class="com"><!-- ... --></span></code></pre> </div> </div> <div class="paragraph"> <p>Instead of manually creating the meta tags, you can use the simpler <a href="#the-csrfmetatags-tag">csrfMetaTags tag</a> from the Spring Security JSP tag library.</p> </div> <div class="paragraph"> <p>You can then include the token within all your Ajax requests. If you were using jQuery, this could be done with the following:</p> </div> <div class="listingblock"> <div class="content"> <pre style="" class="prettyprint javascript language-javascript prettyprinted"><code><span class="pln">$</span><span class="pun">(</span><span class="kwd">function</span><span class="pln"> </span><span class="pun">()</span><span class="pln"> </span><span class="pun">{</span><span class="pln"> </span><span class="kwd">var</span><span class="pln"> token </span><span class="pun">=</span><span class="pln"> $</span><span class="pun">(</span><span class="str">"meta[name='_csrf']"</span><span class="pun">).</span><span class="pln">attr</span><span class="pun">(</span><span class="str">"content"</span><span class="pun">);</span><span class="pln"> </span><span class="kwd">var</span><span class="pln"> header </span><span class="pun">=</span><span class="pln"> $</span><span class="pun">(</span><span class="str">"meta[name='_csrf_header']"</span><span class="pun">).</span><span class="pln">attr</span><span class="pun">(</span><span class="str">"content"</span><span class="pun">);</span><span class="pln"> $</span><span class="pun">(</span><span class="pln">document</span><span class="pun">).</span><span class="pln">ajaxSend</span><span class="pun">(</span><span class="kwd">function</span><span class="pun">(</span><span class="pln">e</span><span class="pun">,</span><span class="pln"> xhr</span><span class="pun">,</span><span class="pln"> options</span><span class="pun">)</span><span class="pln"> </span><span class="pun">{</span><span class="pln"> xhr</span><span class="pun">.</span><span class="pln">setRequestHeader</span><span class="pun">(</span><span class="pln">header</span><span class="pun">,</span><span class="pln"> token</span><span class="pun">);</span><span class="pln"> </span><span class="pun">});</span><span class="pln"> </span><span class="pun">});</span></code></pre> </div> </div> <div class="paragraph"> <p>As a alternative to jQuery, we recommend using <a href="http://cujojs.com/">cujoJS’s</a> rest.js. The <a href="https://github.com/cujojs/rest">rest.js</a> module provides advanced support for working with HTTP request and responses in RESTful ways. A core capability is the ability to contextualize the HTTP client adding behavior as needed by chaining interceptors on to the client.</p> </div> <div class="listingblock"> <div class="content"> <pre style="" class="prettyprint javascript language-javascript prettyprinted"><code><span class="kwd">var</span><span class="pln"> client </span><span class="pun">=</span><span class="pln"> rest</span><span class="pun">.</span><span class="pln">chain</span><span class="pun">(</span><span class="pln">csrf</span><span class="pun">,</span><span class="pln"> </span><span class="pun">{</span><span class="pln"> token</span><span class="pun">:</span><span class="pln"> $</span><span class="pun">(</span><span class="str">"meta[name='_csrf']"</span><span class="pun">).</span><span class="pln">attr</span><span class="pun">(</span><span class="str">"content"</span><span class="pun">),</span><span class="pln"> name</span><span class="pun">:</span><span class="pln"> $</span><span class="pun">(</span><span class="str">"meta[name='_csrf_header']"</span><span class="pun">).</span><span class="pln">attr</span><span class="pun">(</span><span class="str">"content"</span><span class="pun">)</span><span class="pln"> </span><span class="pun">});</span></code></pre> </div> </div> <div class="paragraph"> <p>The configured client can be shared with any component of the application that needs to make a request to the CSRF protected resource. One significant different between rest.js and jQuery is that only requests made with the configured client will contain the CSRF token, vs jQuery where <em>all</em> requests will include the token. The ability to scope which requests receive the token helps guard against leaking the CSRF token to a third party. Please refer to the <a href="https://github.com/cujojs/rest/tree/master/docs">rest.js reference documentation</a> for more information on rest.js.</p> </div> </div> </div> </div> <div class="sect2"> <h3 id="csrf-caveats"><a class="anchor" href="#csrf-caveats"></a>6.5. CSRF Caveats</h3> <div class="paragraph"> <p>There are a few caveats when implementing CSRF.</p> </div> <div class="sect3"> <h4 id="csrf-timeouts"><a class="anchor" href="#csrf-timeouts"></a>6.5.1. Timeouts</h4> <div class="paragraph"> <p>One issue is that the expected CSRF token is stored in the HttpSession, so as soon as the HttpSession expires your configured <code>AccessDeniedHandler</code> will receive a InvalidCsrfTokenException. If you are using the default <code>AccessDeniedHandler</code>, the browser will get an HTTP 403 and display a poor error message.</p> </div> <div class="admonitionblock note"> <table> <tbody><tr> <td class="icon"> <i class="icon-note" title="Note"></i> </td> <td class="content"> <div class="paragraph"> <p>One might ask why the expected <code>CsrfToken</code> isn’t stored in a cookie. This is because there are known exploits in which headers (i.e. specify the cookies) can be set by another domain. This is the same reason Ruby on Rails <a href="http://weblog.rubyonrails.org/2011/2/8/csrf-protection-bypass-in-ruby-on-rails/">no longer skips CSRF checks when the header X-Requested-With is present</a>. See <a href="http://lists.webappsec.org/pipermail/websecurity_lists.webappsec.org/2011-February/007533.html">this webappsec.org thread</a> for details on how to perform the exploit. Another disadvantage is that by removing the state (i.e. the timeout) you lose the ability to forcibly terminate the token if something got compromised.</p> </div> </td> </tr> </tbody></table> </div> <div class="paragraph"> <p>A simple way to mitigate an active user experiencing a timeout is to have some JavaScript that lets the user know their session is about to expire. The user can click a button to continue and refresh the session.</p> </div> <div class="paragraph"> <p>Alternatively, specifying a custom <code>AccessDeniedHandler</code> allows you to process the <code>InvalidCsrfTokenException</code> anyway you like. For an example of how to customize the <code>AccessDeniedHandler</code> refer to the provided links for both <a href="#nsa-access-denied-handler">xml</a> and <a href="https://github.com/spring-projects/spring-security/blob/3.2.0.RC1/config/src/test/groovy/org/springframework/security/config/annotation/web/configurers/NamespaceHttpAccessDeniedHandlerTests.groovy#L64">Java configuration</a>.</p> </div> </div> <div class="sect3"> <h4 id="csrf-login"><a class="anchor" href="#csrf-login"></a>6.5.2. Logging In</h4> <div class="paragraph"> <p>In order to protect against <a href="http://en.wikipedia.org/wiki/Cross-site_request_forgery#Forging_login_requests">forging log in requests</a> the log in form should be protected against CSRF attacks too. Since the <code>CsrfToken</code> is stored in HttpSession, this means an HttpSession will be created as soon as <code>CsrfToken</code> token attribute is accessed. While this sounds bad in a RESTful / stateless architecture the reality is that state is necessary to implement practical security. Without state, we have nothing we can do if a token is compromised. Practically speaking, the CSRF token is quite small in size and should have a negligible impact on our architecture.</p> </div> </div> <div class="sect3"> <h4 id="csrf-logout"><a class="anchor" href="#csrf-logout"></a>6.5.3. Logging Out</h4> <div class="paragraph"> <p>Adding CSRF will update the LogoutFilter to only use HTTP POST. This ensures that log out requires a CSRF token and that a malicious user cannot forcibly log out your users.</p> </div> <div class="paragraph"> <p>One approach is to use a form for log out. If you really want a link, you can use JavaScript to have the link perform a POST (i.e. maybe on a hidden form). For browsers with JavaScript that is disabled, you can optionally have the link take the user to a log out confirmation page that will perform the POST.</p> </div> <div class="paragraph"> <p>If you really want to use HTTP GET with logout you can do so, but remember this is generally not recommended. For example, the following Java Configuration will perform logout with the URL /logout is requested with any HTTP method:</p> </div> <div class="listingblock"> <div class="content"> <pre style="" class="prettyprint java language-java prettyprinted"><code><span class="lit">@EnableWebSecurity</span><span class="pln"> </span><span class="lit">@Configuration</span><span class="pln"> </span><span class="kwd">public</span><span class="pln"> </span><span class="kwd">class</span><span class="pln"> </span><span class="typ">WebSecurityConfig</span><span class="pln"> </span><span class="kwd">extends</span><span class="pln"> </span><span class="typ">WebSecurityConfigurerAdapter</span><span class="pln"> </span><span class="pun">{</span><span class="pln"> </span><span class="lit">@Override</span><span class="pln"> </span><span class="kwd">protected</span><span class="pln"> </span><span class="kwd">void</span><span class="pln"> configure</span><span class="pun">(</span><span class="typ">HttpSecurity</span><span class="pln"> http</span><span class="pun">)</span><span class="pln"> </span><span class="kwd">throws</span><span class="pln"> </span><span class="typ">Exception</span><span class="pln"> </span><span class="pun">{</span><span class="pln"> http </span><span class="pun">.</span><span class="pln">logout</span><span class="pun">()</span><span class="pln"> </span><span class="pun">.</span><span class="pln">logoutRequestMatcher</span><span class="pun">(</span><span class="kwd">new</span><span class="pln"> </span><span class="typ">AntPathRequestMatcher</span><span class="pun">(</span><span class="str">"/logout"</span><span class="pun">));</span><span class="pln"> </span><span class="pun">}</span><span class="pln"> </span><span class="pun">}</span></code></pre> </div> </div> </div> <div class="sect3"> <h4 id="csrf-multipart"><a class="anchor" href="#csrf-multipart"></a>6.5.4. Multipart (file upload)</h4> <div class="paragraph"> <p>There are two options to using CSRF protection with multipart/form-data. Each option has its tradeoffs.</p> </div> <div class="ulist"> <ul> <li> <p><a href="#csrf-multipartfilter">Placing MultipartFilter before Spring Security</a></p> </li> <li> <p><a href="#csrf-include-csrf-token-in-action">Include CSRF token in action</a></p> </li> </ul> </div> <div class="admonitionblock note"> <table> <tbody><tr> <td class="icon"> <i class="icon-note" title="Note"></i> </td> <td class="content"> <div class="paragraph"> <p>Before you integrate Spring Security’s CSRF protection with multipart file upload, ensure that you can upload without the CSRF protection first. More information about using multipart forms with Spring can be found within the <a href="http://docs.spring.io/spring/docs/3.2.x/spring-framework-reference/html/mvc.html#mvc-multipart">17.10 Spring’s multipart (file upload) support</a> section of the Spring reference and the <a href="http://docs.spring.io/spring/docs/3.2.x/javadoc-api/org/springframework/web/multipart/support/MultipartFilter.html">MultipartFilter javadoc</a>.</p> </div> </td> </tr> </tbody></table> </div> <div class="sect4"> <h5 id="csrf-multipartfilter"><a class="anchor" href="#csrf-multipartfilter"></a>Placing MultipartFilter before Spring Security</h5> <div class="paragraph"> <p>The first option is to ensure that the <code>MultipartFilter</code> is specified before the Spring Security filter. Specifying the <code>MultipartFilter</code> before the Spring Security filter means that there is no authorization for invoking the <code>MultipartFilter</code> which means anyone can place temporary files on your server. However, only authorized users will be able to submit a File that is processed by your application. In general, this is the recommended approach because the temporary file upload should have a negligble impact on most servers.</p> </div> <div class="paragraph"> <p>To ensure <code>MultipartFilter</code> is specified before the Spring Security filter with java configuration, users can override beforeSpringSecurityFilterChain as shown below:</p> </div> <div class="listingblock"> <div class="content"> <pre style="" class="prettyprint java language-java prettyprinted"><code><span class="kwd">public</span><span class="pln"> </span><span class="kwd">class</span><span class="pln"> </span><span class="typ">SecurityApplicationInitializer</span><span class="pln"> </span><span class="kwd">extends</span><span class="pln"> </span><span class="typ">AbstractSecurityWebApplicationInitializer</span><span class="pln"> </span><span class="pun">{</span><span class="pln"> </span><span class="lit">@Override</span><span class="pln"> </span><span class="kwd">protected</span><span class="pln"> </span><span class="kwd">void</span><span class="pln"> beforeSpringSecurityFilterChain</span><span class="pun">(</span><span class="typ">ServletContext</span><span class="pln"> servletContext</span><span class="pun">)</span><span class="pln"> </span><span class="pun">{</span><span class="pln"> insertFilters</span><span class="pun">(</span><span class="pln">servletContext</span><span class="pun">,</span><span class="pln"> </span><span class="kwd">new</span><span class="pln"> </span><span class="typ">MultipartFilter</span><span class="pun">());</span><span class="pln"> </span><span class="pun">}</span><span class="pln"> </span><span class="pun">}</span></code></pre> </div> </div> <div class="paragraph"> <p>To ensure <code>MultipartFilter</code> is specified before the Spring Security filter with XML configuration, users can ensure the <filter-mapping> element of the <code>MultipartFilter</code> is placed before the springSecurityFilterChain within the web.xml as shown below:</p> </div> <div class="listingblock"> <div class="content"> <pre style="" class="prettyprint xml language-xml prettyprinted"><code><span class="tag"><filter></span><span class="pln"> </span><span class="tag"><filter-name></span><span class="pln">MultipartFilter</span><span class="tag"></filter-name></span><span class="pln"> </span><span class="tag"><filter-class></span><span class="pln">org.springframework.web.multipart.support.MultipartFilter</span><span class="tag"></filter-class></span><span class="pln"> </span><span class="tag"></filter></span><span class="pln"> </span><span class="tag"><filter></span><span class="pln"> </span><span class="tag"><filter-name></span><span class="pln">springSecurityFilterChain</span><span class="tag"></filter-name></span><span class="pln"> </span><span class="tag"><filter-class></span><span class="pln">org.springframework.web.filter.DelegatingFilterProxy</span><span class="tag"></filter-class></span><span class="pln"> </span><span class="tag"></filter></span><span class="pln"> </span><span class="tag"><filter-mapping></span><span class="pln"> </span><span class="tag"><filter-name></span><span class="pln">MultipartFilter</span><span class="tag"></filter-name></span><span class="pln"> </span><span class="tag"><url-pattern></span><span class="pln">/*</span><span class="tag"></url-pattern></span><span class="pln"> </span><span class="tag"></filter-mapping></span><span class="pln"> </span><span class="tag"><filter-mapping></span><span class="pln"> </span><span class="tag"><filter-name></span><span class="pln">springSecurityFilterChain</span><span class="tag"></filter-name></span><span class="pln"> </span><span class="tag"><url-pattern></span><span class="pln">/*</span><span class="tag"></url-pattern></span><span class="pln"> </span><span class="tag"></filter-mapping></span></code></pre> </div> </div> </div> <div class="sect4"> <h5 id="csrf-include-csrf-token-in-action"><a class="anchor" href="#csrf-include-csrf-token-in-action"></a>Include CSRF token in action</h5> <div class="paragraph"> <p>If allowing unauthorized users to upload temporariy files is not acceptable, an alternative is to place the <code>MultipartFilter</code> after the Spring Security filter and include the CSRF as a query parameter in the action attribute of the form. An example with a jsp is shown below</p> </div> <div class="listingblock"> <div class="content"> <pre style="" class="prettyprint xml language-xml prettyprinted"><code><span class="tag"><form</span><span class="pln"> </span><span class="atn">action</span><span class="pun">=</span><span class="atv">"./upload?${_csrf.parameterName}=${_csrf.token}"</span><span class="pln"> </span><span class="atn">method</span><span class="pun">=</span><span class="atv">"post"</span><span class="pln"> </span><span class="atn">enctype</span><span class="pun">=</span><span class="atv">"multipart/form-data"</span><span class="tag">></span></code></pre> </div> </div> <div class="paragraph"> <p>The disadvantage to this approach is that query parameters can be leaked. More genearlly, it is considered best practice to place sensitive data within the body or headers to ensure it is not leaked. Additional information can be found in <a href="http://www.w3.org/Protocols/rfc2616/rfc2616-sec15.html#sec15.1.3">RFC 2616 Section 15.1.3 Encoding Sensitive Information in URI’s</a>.</p> </div> </div> </div> <div class="sect3"> <h4 id="hiddenhttpmethodfilter"><a class="anchor" href="#hiddenhttpmethodfilter"></a>6.5.5. HiddenHttpMethodFilter</h4> <div class="paragraph"> <p>The HiddenHttpMethodFilter should be placed before the Spring Security filter. In general this is true, but it could have additional implications when protecting against CSRF attacks.</p> </div> <div class="paragraph"> <p>Note that the HiddenHttpMethodFilter only overrides the HTTP method on a POST, so this is actually unlikely to cause any real problems. However, it is still best practice to ensure it is placed before Spring Security’s filters.</p> </div> </div> </div> <div class="sect2"> <h3 id="overriding-defaults"><a class="anchor" href="#overriding-defaults"></a>6.6. Overriding Defaults</h3> <div class="paragraph"> <p>Spring Security’s goal is to provide defaults that protect your users from exploits. This does not mean that you are forced to accept all of its defaults.</p> </div> <div class="paragraph"> <p>For example, you can provide a custom CsrfTokenRepository to override the way in which the <code>CsrfToken</code> is stored.</p> </div> <div class="paragraph"> <p>You can also specify a custom RequestMatcher to determine which requests are protected by CSRF (i.e. perhaps you don’t care if log out is exploited). In short, if Spring Security’s CSRF protection doesn’t behave exactly as you want it, you are able to customize the behavior. Refer to the <a href="#nsa-csrf"><csrf></a> documentation for details on how to make these customizations with XML and the <code>CsrfConfigurer</code> javadoc for details on how to make these customizations when using Java configuration.</p> </div> </div> </div> </div> <div class="sect1"> <h2 id="headers"><a class="anchor" href="#headers"></a>7. Security HTTP Response Headers</h2> <div class="sectionbody"> <div class="paragraph"> <p>This section discusses Spring Security’s support for adding various security headers to the response.</p> </div> <div class="sect2"> <h3 id="default-security-headers"><a class="anchor" href="#default-security-headers"></a>7.1. Default Security Headers</h3> <div class="paragraph"> <p>Spring Security allows users to easily inject the default security headers to assist in protecting their application. The following is a list of the current <em>Default Security Headers</em> provided by Spring Security:</p> </div> <div class="ulist"> <ul> <li> <p><a href="#headers-cache-control">Cache Control</a></p> </li> <li> <p><a href="#headers-content-type-options">Content Type Options</a></p> </li> <li> <p><a href="#headers-hsts">HTTP Strict Transport Security</a></p> </li> <li> <p><a href="#headers-frame-options">X-Frame-Options</a></p> </li> <li> <p><a href="#headers-xss-protection">X-XSS-Protection</a></p> </li> </ul> </div> <div class="paragraph"> <p>While each of these headers are considered best practice, it should be noted that not all clients utilize the headers, so additional testing is encouraged. For passivity reasons, if you are using Spring Security’s XML namespace support, you must explicitly enable the security headers. All of the default headers can be easily added using the <a href="#nsa-headers"><headers</a>> element with no child elements:</p> </div> <div class="admonitionblock note"> <table> <tbody><tr> <td class="icon"> <i class="icon-note" title="Note"></i> </td> <td class="content"> <div class="paragraph"> <p><a href="https://jira.springsource.org/browse/SEC-2348">SEC-2348</a> is logged to ensure Spring Security 4.x’s XML namespace configuration will enable Security headers by default.</p> </div> </td> </tr> </tbody></table> </div> <div class="listingblock"> <div class="content"> <pre style="" class="prettyprint xml language-xml prettyprinted"><code><span class="tag"><http></span><span class="pln"> </span><span class="com"><!-- ... --></span><span class="pln"> </span><span class="tag"><headers</span><span class="pln"> </span><span class="tag">/></span><span class="pln"> </span><span class="tag"></http></span></code></pre> </div> </div> <div class="paragraph"> <p>Alternatively, you can choose to explicitly list the headers you wish to include. For example, the following is the same the previous configuration. Removing any of the elements will remove that header from the responses.</p> </div> <div class="listingblock"> <div class="content"> <pre style="" class="prettyprint xml language-xml prettyprinted"><code><span class="tag"><http></span><span class="pln"> </span><span class="com"><!-- ... --></span><span class="pln"> </span><span class="tag"><headers></span><span class="pln"> </span><span class="tag"><cache-control</span><span class="pln"> </span><span class="tag">/></span><span class="pln"> </span><span class="tag"><content-type-options</span><span class="pln"> </span><span class="tag">/></span><span class="pln"> </span><span class="tag"><hsts</span><span class="pln"> </span><span class="tag">/></span><span class="pln"> </span><span class="tag"><frame-options</span><span class="pln"> </span><span class="tag">/></span><span class="pln"> </span><span class="tag"><xss-protection</span><span class="pln"> </span><span class="tag">/></span><span class="pln"> </span><span class="tag"></headers></span><span class="pln"> </span><span class="tag"></http></span></code></pre> </div> </div> <div class="paragraph"> <p>If you are using Spring Security’s Java configuration, all of the default security headers are added by default. They can be disabled using the Java configuration below:</p> </div> <div class="listingblock"> <div class="content"> <pre style="" class="prettyprint java language-java prettyprinted"><code><span class="lit">@EnableWebSecurity</span><span class="pln"> </span><span class="lit">@Configuration</span><span class="pln"> </span><span class="kwd">public</span><span class="pln"> </span><span class="kwd">class</span><span class="pln"> </span><span class="typ">WebSecurityConfig</span><span class="pln"> </span><span class="kwd">extends</span><span class="pln"> </span><span class="typ">WebSecurityConfigurerAdapter</span><span class="pln"> </span><span class="pun">{</span><span class="pln"> </span><span class="lit">@Override</span><span class="pln"> </span><span class="kwd">protected</span><span class="pln"> </span><span class="kwd">void</span><span class="pln"> configure</span><span class="pun">(</span><span class="typ">HttpSecurity</span><span class="pln"> http</span><span class="pun">)</span><span class="pln"> </span><span class="kwd">throws</span><span class="pln"> </span><span class="typ">Exception</span><span class="pln"> </span><span class="pun">{</span><span class="pln"> http </span><span class="com">// ...</span><span class="pln"> </span><span class="pun">.</span><span class="pln">headers</span><span class="pun">().</span><span class="pln">disable</span><span class="pun">();</span><span class="pln"> </span><span class="pun">}</span><span class="pln"> </span><span class="pun">}</span></code></pre> </div> </div> <div class="paragraph"> <p>As soon as you specify any headers that should be included, then only those headers will be include. For example, the following configuration will include support for <a href="#headers-cache-control">Cache Control</a> and <a href="#headers-frame-options">X-Frame-Options</a> only.</p> </div> <div class="listingblock"> <div class="content"> <pre style="" class="prettyprint java language-java prettyprinted"><code><span class="lit">@EnableWebSecurity</span><span class="pln"> </span><span class="lit">@Configuration</span><span class="pln"> </span><span class="kwd">public</span><span class="pln"> </span><span class="kwd">class</span><span class="pln"> </span><span class="typ">WebSecurityConfig</span><span class="pln"> </span><span class="kwd">extends</span><span class="pln"> </span><span class="typ">WebSecurityConfigurerAdapter</span><span class="pln"> </span><span class="pun">{</span><span class="pln"> </span><span class="lit">@Override</span><span class="pln"> </span><span class="kwd">protected</span><span class="pln"> </span><span class="kwd">void</span><span class="pln"> configure</span><span class="pun">(</span><span class="typ">HttpSecurity</span><span class="pln"> http</span><span class="pun">)</span><span class="pln"> </span><span class="kwd">throws</span><span class="pln"> </span><span class="typ">Exception</span><span class="pln"> </span><span class="pun">{</span><span class="pln"> http </span><span class="com">// ...</span><span class="pln"> </span><span class="pun">.</span><span class="pln">headers</span><span class="pun">()</span><span class="pln"> </span><span class="pun">.</span><span class="pln">cacheControl</span><span class="pun">()</span><span class="pln"> </span><span class="pun">.</span><span class="pln">frameOptions</span><span class="pun">();</span><span class="pln"> </span><span class="pun">}</span><span class="pln"> </span><span class="pun">}</span></code></pre> </div> </div> <div class="sect3"> <h4 id="headers-cache-control"><a class="anchor" href="#headers-cache-control"></a>7.1.1. Cache Control</h4> <div class="paragraph"> <p>In the past Spring Security required you to provide your own cache control for your web application. This seemed reasonable at the time, but browser caches have evolved to include caches for secure connections as well. This means that a user may view an authenticated page, log out, and then a malicious user can use the browser history to view the cached page. To help mitigate this Spring Security has added cache control support which will insert the following headers into you response.</p> </div> <div class="listingblock"> <div class="content"> <pre style="" class="prettyprint prettyprinted"><code><span class="typ">Cache</span><span class="pun">-</span><span class="typ">Control</span><span class="pun">:</span><span class="pln"> </span><span class="kwd">no</span><span class="pun">-</span><span class="pln">cache</span><span class="pun">,</span><span class="pln"> </span><span class="kwd">no</span><span class="pun">-</span><span class="pln">store</span><span class="pun">,</span><span class="pln"> max</span><span class="pun">-</span><span class="pln">age</span><span class="pun">=</span><span class="lit">0</span><span class="pun">,</span><span class="pln"> must</span><span class="pun">-</span><span class="pln">revalidate </span><span class="typ">Pragma</span><span class="pun">:</span><span class="pln"> </span><span class="kwd">no</span><span class="pun">-</span><span class="pln">cache </span><span class="typ">Expires</span><span class="pun">:</span><span class="pln"> </span><span class="lit">0</span></code></pre> </div> </div> <div class="paragraph"> <p>Simply adding the <a href="#nsa-headers"><headers</a>> element with no child elements will automatically add Cache Control and quite a few other protections. However, if you only want cache control, you can enable this feature using Spring Security’s XML namespace with the <a href="#nsa-cache-control"><cache-control</a>> element.</p> </div> <div class="listingblock"> <div class="content"> <pre style="" class="prettyprint xml language-xml prettyprinted"><code><span class="tag"><http></span><span class="pln"> </span><span class="com"><!-- ... --></span><span class="pln"> </span><span class="tag"><headers></span><span class="pln"> </span><span class="tag"><cache-control</span><span class="pln"> </span><span class="tag">/></span><span class="pln"> </span><span class="tag"></headers></span><span class="pln"> </span><span class="tag"></http></span></code></pre> </div> </div> <div class="paragraph"> <p>Similarly, you can enable only cache control within Java Configuration with the following:</p> </div> <div class="listingblock"> <div class="content"> <pre style="" class="prettyprint java language-java prettyprinted"><code><span class="lit">@EnableWebSecurity</span><span class="pln"> </span><span class="lit">@Configuration</span><span class="pln"> </span><span class="kwd">public</span><span class="pln"> </span><span class="kwd">class</span><span class="pln"> </span><span class="typ">WebSecurityConfig</span><span class="pln"> </span><span class="kwd">extends</span><span class="pln"> </span><span class="typ">WebSecurityConfigurerAdapter</span><span class="pln"> </span><span class="pun">{</span><span class="pln"> </span><span class="lit">@Override</span><span class="pln"> </span><span class="kwd">protected</span><span class="pln"> </span><span class="kwd">void</span><span class="pln"> configure</span><span class="pun">(</span><span class="typ">HttpSecurity</span><span class="pln"> http</span><span class="pun">)</span><span class="pln"> </span><span class="kwd">throws</span><span class="pln"> </span><span class="typ">Exception</span><span class="pln"> </span><span class="pun">{</span><span class="pln"> http </span><span class="com">// ...</span><span class="pln"> </span><span class="pun">.</span><span class="pln">headers</span><span class="pun">()</span><span class="pln"> </span><span class="pun">.</span><span class="pln">cacheControl</span><span class="pun">();</span><span class="pln"> </span><span class="pun">}</span><span class="pln"> </span><span class="pun">}</span></code></pre> </div> </div> <div class="paragraph"> <p>If you actually want to cache specific responses, your application can selectively invoke <a href="http://docs.oracle.com/javaee/6/api/javax/servlet/http/HttpServletResponse.html#setHeader%28java.lang.String,java.lang.String%29">HttpServletResponse.setHeader(String,String)</a> to override the header set by Spring Security. This is useful to ensure things like CSS, JavaScript, and images are properly cached.</p> </div> <div class="paragraph"> <p>When using Spring Web MVC, this is typically done within your configuration. For example, the following configuration will ensure that the cache headers are set for all of your resources:</p> </div> <div class="listingblock"> <div class="content"> <pre style="" class="prettyprint java language-java prettyprinted"><code><span class="lit">@EnableWebMvc</span><span class="pln"> </span><span class="kwd">public</span><span class="pln"> </span><span class="kwd">class</span><span class="pln"> </span><span class="typ">WebMvcConfiguration</span><span class="pln"> </span><span class="kwd">extends</span><span class="pln"> </span><span class="typ">WebMvcConfigurerAdapter</span><span class="pln"> </span><span class="pun">{</span><span class="pln"> </span><span class="lit">@Override</span><span class="pln"> </span><span class="kwd">public</span><span class="pln"> </span><span class="kwd">void</span><span class="pln"> addResourceHandlers</span><span class="pun">(</span><span class="typ">ResourceHandlerRegistry</span><span class="pln"> registry</span><span class="pun">)</span><span class="pln"> </span><span class="pun">{</span><span class="pln"> registry </span><span class="pun">.</span><span class="pln">addResourceHandler</span><span class="pun">(</span><span class="str">"/resources/**"</span><span class="pun">)</span><span class="pln"> </span><span class="pun">.</span><span class="pln">addResourceLocations</span><span class="pun">(</span><span class="str">"/resources/"</span><span class="pun">)</span><span class="pln"> </span><span class="pun">.</span><span class="pln">setCachePeriod</span><span class="pun">(</span><span class="lit">31556926</span><span class="pun">);</span><span class="pln"> </span><span class="pun">}</span><span class="pln"> </span><span class="com">// ...</span><span class="pln"> </span><span class="pun">}</span></code></pre> </div> </div> </div> <div class="sect3"> <h4 id="headers-content-type-options"><a class="anchor" href="#headers-content-type-options"></a>7.1.2. Content Type Options</h4> <div class="paragraph"> <p>Historically browsers, including Internet Explorer, would try to guess the content type of a request using <a href="http://en.wikipedia.org/wiki/Content_sniffing">content sniffing</a>. This allowed browsers to improve the user experience by guessing the content type on resources that had not specified the content type. For example, if a browser encountered a JavaScript file that did not have the content type specified, it would be able to guess the content type and then execute it.</p> </div> <div class="admonitionblock note"> <table> <tbody><tr> <td class="icon"> <i class="icon-note" title="Note"></i> </td> <td class="content"> <div class="paragraph"> <p>There are many additional things one should do (i.e. only display the document in a distinct domain, ensure Content-Type header is set, sanitize the document, etc) when allowing content to be uploaded. However, these measures are out of the scope of what Spring Security provides. It is also important to point out when disabling content sniffing, you must specify the content type in order for things to work properly.</p> </div> </td> </tr> </tbody></table> </div> <div class="paragraph"> <p>The problem with content sniffing is that this allowed malicious users to use polyglots (i.e. a file that is valid as multiple content types) to execute XSS attacks. For example, some sites may allow users to submit a valid postscript document to a website and view it. A malicious user might create a <a href="http://webblaze.cs.berkeley.edu/papers/barth-caballero-song.pdf">postscript document that is also a valid JavaScript file</a> and execute a XSS attack with it.</p> </div> <div class="paragraph"> <p>Content sniffing can be disabled by adding the following header to our response:</p> </div> <div class="listingblock"> <div class="content"> <pre style="" class="prettyprint prettyprinted"><code><span class="pln">X</span><span class="pun">-</span><span class="typ">Content</span><span class="pun">-</span><span class="typ">Type</span><span class="pun">-</span><span class="typ">Options</span><span class="pun">:</span><span class="pln"> nosniff</span></code></pre> </div> </div> <div class="paragraph"> <p>Just as with the cache control element, the nosniff directive is added by default when using the <headers> element with no child elements. However, if you want more control over which headers are added you can use the <a href="#nsa-content-type-options"><content-type-options</a>> element as shown below:</p> </div> <div class="listingblock"> <div class="content"> <pre style="" class="prettyprint xml language-xml prettyprinted"><code><span class="tag"><http></span><span class="pln"> </span><span class="com"><!-- ... --></span><span class="pln"> </span><span class="tag"><headers></span><span class="pln"> </span><span class="tag"><content-type-options</span><span class="pln"> </span><span class="tag">/></span><span class="pln"> </span><span class="tag"></headers></span><span class="pln"> </span><span class="tag"></http></span></code></pre> </div> </div> <div class="paragraph"> <p>The X-Content-Type-Options header is added by default with Spring Security Java configuration. If you want more control over the headers, you can explicitly specify the content type options with the following:</p> </div> <div class="listingblock"> <div class="content"> <pre style="" class="prettyprint java language-java prettyprinted"><code><span class="lit">@EnableWebSecurity</span><span class="pln"> </span><span class="lit">@Configuration</span><span class="pln"> </span><span class="kwd">public</span><span class="pln"> </span><span class="kwd">class</span><span class="pln"> </span><span class="typ">WebSecurityConfig</span><span class="pln"> </span><span class="kwd">extends</span><span class="pln"> </span><span class="typ">WebSecurityConfigurerAdapter</span><span class="pln"> </span><span class="pun">{</span><span class="pln"> </span><span class="lit">@Override</span><span class="pln"> </span><span class="kwd">protected</span><span class="pln"> </span><span class="kwd">void</span><span class="pln"> configure</span><span class="pun">(</span><span class="typ">HttpSecurity</span><span class="pln"> http</span><span class="pun">)</span><span class="pln"> </span><span class="kwd">throws</span><span class="pln"> </span><span class="typ">Exception</span><span class="pln"> </span><span class="pun">{</span><span class="pln"> http </span><span class="com">// ...</span><span class="pln"> </span><span class="pun">.</span><span class="pln">headers</span><span class="pun">()</span><span class="pln"> </span><span class="pun">.</span><span class="pln">contentTypeOptions</span><span class="pun">();</span><span class="pln"> </span><span class="pun">}</span><span class="pln"> </span><span class="pun">}</span></code></pre> </div> </div> </div> <div class="sect3"> <h4 id="headers-hsts"><a class="anchor" href="#headers-hsts"></a>7.1.3. HTTP Strict Transport Security (HSTS)</h4> <div class="paragraph"> <p>When you type in your bank’s website, do you enter mybank.example.com or do you enter <a href="https://mybank.example.com/">https://mybank.example.com</a>? If you omit the https protocol, you are potentially vulnerable to <a href="http://en.wikipedia.org/wiki/Man-in-the-middle_attack">Man in the Middle attacks</a>. Even if the website performs a redirect to <a href="https://mybank.example.com/">https://mybank.example.com</a> a malicious user could intercept the initial HTTP request and manipulate the response (i.e. redirect to <a href="https://mibank.example.com/">https://mibank.example.com</a> and steal their credentials).</p> </div> <div class="paragraph"> <p>Many users omit the https protocol and this is why <a href="http://tools.ietf.org/html/rfc6797">HTTP Strict Transport Security (HSTS)</a> was created. Once mybank.example.com is added as a <a href="http://tools.ietf.org/html/rfc6797#section-5.1">HSTS host</a>, a browser can know ahead of time that any request to mybank.example.com should be interpreted as <a href="https://mybank.example.com/">https://mybank.example.com</a>. This greatly reduces the possibility of a Man in the Middle attack occurring.</p> </div> <div class="admonitionblock note"> <table> <tbody><tr> <td class="icon"> <i class="icon-note" title="Note"></i> </td> <td class="content"> <div class="paragraph"> <p>In accordance with <a href="http://tools.ietf.org/html/rfc6797#section-7.2">RFC6797</a>, the HSTS header is only injected into HTTPS responses. In order for the browser to acknowledge the header, the browser must first trust the CA that signed the SSL certificate used to make the connection (not just the SSL certificate).</p> </div> </td> </tr> </tbody></table> </div> <div class="paragraph"> <p>One way for a site to be marked as a HSTS host is to have the host preloaded into the browser. Another is to add the "Strict-Transport-Security" header to the response. For example the following would instruct the browser to treat the domain as an HSTS host for a year (there are approximately 31536000 seconds in a year):</p> </div> <div class="listingblock"> <div class="content"> <pre style="" class="prettyprint prettyprinted"><code><span class="typ">Strict</span><span class="pun">-</span><span class="typ">Transport</span><span class="pun">-</span><span class="typ">Security</span><span class="pun">:</span><span class="pln"> max</span><span class="pun">-</span><span class="pln">age</span><span class="pun">=</span><span class="lit">31536000</span><span class="pln"> </span><span class="pun">;</span><span class="pln"> includeSubDomains</span></code></pre> </div> </div> <div class="paragraph"> <p>The optional includeSubDomains directive instructs Spring Security that subdomains (i.e. secure.mybank.example.com) should also be treated as an HSTS domain.</p> </div> <div class="paragraph"> <p>As with the other headers, Spring Security adds the previous header to the response when the <headers> element is specified with no child elements. It is also automatically added when you are using Java Configuration. You can also only use HSTS headers with the <a href="#nsa-hsts"><hsts</a>> element as shown below:</p> </div> <div class="listingblock"> <div class="content"> <pre style="" class="prettyprint xml language-xml prettyprinted"><code><span class="tag"><http></span><span class="pln"> </span><span class="com"><!-- ... --></span><span class="pln"> </span><span class="tag"><headers></span><span class="pln"> </span><span class="tag"><hsts</span><span class="pln"> </span><span class="tag">/></span><span class="pln"> </span><span class="tag"></headers></span><span class="pln"> </span><span class="tag"></http></span></code></pre> </div> </div> <div class="paragraph"> <p>Similarly, you can enable only HSTS headers with Java Configuration:</p> </div> <div class="listingblock"> <div class="content"> <pre style="" class="prettyprint java language-java prettyprinted"><code><span class="lit">@EnableWebSecurity</span><span class="pln"> </span><span class="lit">@Configuration</span><span class="pln"> </span><span class="kwd">public</span><span class="pln"> </span><span class="kwd">class</span><span class="pln"> </span><span class="typ">WebSecurityConfig</span><span class="pln"> </span><span class="kwd">extends</span><span class="pln"> </span><span class="typ">WebSecurityConfigurerAdapter</span><span class="pln"> </span><span class="pun">{</span><span class="pln"> </span><span class="lit">@Override</span><span class="pln"> </span><span class="kwd">protected</span><span class="pln"> </span><span class="kwd">void</span><span class="pln"> configure</span><span class="pun">(</span><span class="typ">HttpSecurity</span><span class="pln"> http</span><span class="pun">)</span><span class="pln"> </span><span class="kwd">throws</span><span class="pln"> </span><span class="typ">Exception</span><span class="pln"> </span><span class="pun">{</span><span class="pln"> http </span><span class="com">// ...</span><span class="pln"> </span><span class="pun">.</span><span class="pln">headers</span><span class="pun">()</span><span class="pln"> </span><span class="pun">.</span><span class="pln">httpStrictTransportSecurity</span><span class="pun">();</span><span class="pln"> </span><span class="pun">}</span><span class="pln"> </span><span class="pun">}</span></code></pre> </div> </div> </div> <div class="sect3"> <h4 id="headers-frame-options"><a class="anchor" href="#headers-frame-options"></a>7.1.4. X-Frame-Options</h4> <div class="paragraph"> <p>Allowing your website to be added to a frame can be a security issue. For example, using clever CSS styling users could be tricked into clicking on something that they were not intending (<a href="http://www.youtube.com/watch?v=3mk0RySeNsU">video demo</a>). For example, a user that is logged into their bank might click a button that grants access to other users. This sort of attack is known ashttp://en.wikipedia.org/wiki/Clickjacking[Clickjacking].</p> </div> <div class="admonitionblock note"> <table> <tbody><tr> <td class="icon"> <i class="icon-note" title="Note"></i> </td> <td class="content"> <div class="paragraph"> <p>Another modern approach to dealing with clickjacking is using a <a href="http://www.w3.org/TR/CSP/">Content Security Policy</a>. Spring Security does not provide support for this as the specification is not released and it is quite a bit more complicated. However, you could use the <a href="#headers-static">static headers</a> feature to implement this. To stay up to date with this issue and to see how you can implement it with Spring Security refer to <a href="https://jira.springsource.org/browse/SEC-2117">SEC-2117</a></p> </div> </td> </tr> </tbody></table> </div> <div class="paragraph"> <p>There are a number ways to mitigate clickjacking attacks. For example, to protect legacy browsers from clickjacking attacks you can use <a href="https://www.owasp.org/index.php/Clickjacking_Defense_Cheat_Sheet#Best-for-now_Legacy_Browser_Frame_Breaking_Script">frame breaking code</a>. While not perfect, the frame breaking code is the best you can do for the legacy browsers.</p> </div> <div class="paragraph"> <p>A more modern approach to address clickjacking is to use <a href="https://developer.mozilla.org/en-US/docs/HTTP/X-Frame-Options">X-Frame-Options</a> header:</p> </div> <div class="listingblock"> <div class="content"> <pre style="" class="prettyprint prettyprinted"><code><span class="pln">X</span><span class="pun">-</span><span class="typ">Frame</span><span class="pun">-</span><span class="typ">Options</span><span class="pun">:</span><span class="pln"> DENY</span></code></pre> </div> </div> <div class="paragraph"> <p>The X-Frame-Options response header instructs the browser to prevent any site with this header in the response from being rendered within a frame. As with the other response headers, this is automatically included when the <headers> element is specified with no child elements. You can also explicitly specify the <a href="#nsa-frame-options">frame-options</a> element to control which headers are added to the response.</p> </div> <div class="listingblock"> <div class="content"> <pre style="" class="prettyprint xml language-xml prettyprinted"><code><span class="tag"><http></span><span class="pln"> </span><span class="com"><!-- ... --></span><span class="pln"> </span><span class="tag"><headers></span><span class="pln"> </span><span class="tag"><frame-options</span><span class="pln"> </span><span class="tag">/></span><span class="pln"> </span><span class="tag"></headers></span><span class="pln"> </span><span class="tag"></http></span></code></pre> </div> </div> <div class="paragraph"> <p>Similarly, you can enable only frame options within Java Configuration with the following:</p> </div> <div class="listingblock"> <div class="content"> <pre style="" class="prettyprint java language-java prettyprinted"><code><span class="lit">@EnableWebSecurity</span><span class="pln"> </span><span class="lit">@Configuration</span><span class="pln"> </span><span class="kwd">public</span><span class="pln"> </span><span class="kwd">class</span><span class="pln"> </span><span class="typ">WebSecurityConfig</span><span class="pln"> </span><span class="kwd">extends</span><span class="pln"> </span><span class="typ">WebSecurityConfigurerAdapter</span><span class="pln"> </span><span class="pun">{</span><span class="pln"> </span><span class="lit">@Override</span><span class="pln"> </span><span class="kwd">protected</span><span class="pln"> </span><span class="kwd">void</span><span class="pln"> configure</span><span class="pun">(</span><span class="typ">HttpSecurity</span><span class="pln"> http</span><span class="pun">)</span><span class="pln"> </span><span class="kwd">throws</span><span class="pln"> </span><span class="typ">Exception</span><span class="pln"> </span><span class="pun">{</span><span class="pln"> http </span><span class="com">// ...</span><span class="pln"> </span><span class="pun">.</span><span class="pln">headers</span><span class="pun">()</span><span class="pln"> </span><span class="pun">.</span><span class="pln">frameOptions</span><span class="pun">();</span><span class="pln"> </span><span class="pun">}</span><span class="pln"> </span><span class="pun">}</span></code></pre> </div> </div> <div class="paragraph"> <p>If you want to change the value for the X-Frame-Options header, then you can use a <a href="#headers-headers-writer">XFrameOptionsHeaderWriter instance</a>.</p> </div> </div> <div class="sect3"> <h4 id="headers-xss-protection"><a class="anchor" href="#headers-xss-protection"></a>7.1.5. X-XSS-Protection</h4> <div class="paragraph"> <p>Some browsers have built in support for filtering out <a href="https://www.owasp.org/index.php/Testing_for_Reflected_Cross_site_scripting_%28OWASP-DV-001%29">reflected XSS attacks</a>. This is by no means full proof, but does assist in XSS protection.</p> </div> <div class="paragraph"> <p>The filtering is typically enabled by default, so adding the header typically just ensures it is enabled and instructs the browser what to do when a XSS attack is detected. For example, the filter might try to change the content in the least invasive way to still render everything. At times, this type of replacement can become a <a href="http://hackademix.net/2009/11/21/ies-xss-filter-creates-xss-vulnerabilities/">XSS vulnerability in itself</a>. Instead, it is best to block the content rather than attempt to fix it. To do this we can add the following header:</p> </div> <div class="listingblock"> <div class="content"> <pre style="" class="prettyprint prettyprinted"><code><span class="pln">X</span><span class="pun">-</span><span class="pln">XSS</span><span class="pun">-</span><span class="typ">Protection</span><span class="pun">:</span><span class="pln"> </span><span class="lit">1</span><span class="pun">;</span><span class="pln"> mode</span><span class="pun">=</span><span class="pln">block</span></code></pre> </div> </div> <div class="paragraph"> <p>This header is included by default when the <headers> element is specified with no child elements. We can explicitly state it using the <a href="#nsa-xss-protection">xss-protection</a> element as shown below:</p> </div> <div class="listingblock"> <div class="content"> <pre style="" class="prettyprint xml language-xml prettyprinted"><code><span class="tag"><http></span><span class="pln"> </span><span class="com"><!-- ... --></span><span class="pln"> </span><span class="tag"><headers></span><span class="pln"> </span><span class="tag"><xss-protection</span><span class="pln"> </span><span class="tag">/></span><span class="pln"> </span><span class="tag"></headers></span><span class="pln"> </span><span class="tag"></http></span></code></pre> </div> </div> <div class="paragraph"> <p>Similarly, you can enable only xss protection within Java Configuration with the following:</p> </div> <div class="listingblock"> <div class="content"> <pre style="" class="prettyprint java language-java prettyprinted"><code><span class="lit">@EnableWebSecurity</span><span class="pln"> </span><span class="lit">@Configuration</span><span class="pln"> </span><span class="kwd">public</span><span class="pln"> </span><span class="kwd">class</span><span class="pln"> </span><span class="typ">WebSecurityConfig</span><span class="pln"> </span><span class="kwd">extends</span><span class="pln"> </span><span class="typ">WebSecurityConfigurerAdapter</span><span class="pln"> </span><span class="pun">{</span><span class="pln"> </span><span class="lit">@Override</span><span class="pln"> </span><span class="kwd">protected</span><span class="pln"> </span><span class="kwd">void</span><span class="pln"> configure</span><span class="pun">(</span><span class="typ">HttpSecurity</span><span class="pln"> http</span><span class="pun">)</span><span class="pln"> </span><span class="kwd">throws</span><span class="pln"> </span><span class="typ">Exception</span><span class="pln"> </span><span class="pun">{</span><span class="pln"> http </span><span class="com">// ...</span><span class="pln"> </span><span class="pun">.</span><span class="pln">headers</span><span class="pun">()</span><span class="pln"> </span><span class="pun">.</span><span class="pln">xssProtection</span><span class="pun">();</span><span class="pln"> </span><span class="pun">}</span><span class="pln"> </span><span class="pun">}</span></code></pre> </div> </div> </div> </div> <div class="sect2"> <h3 id="headers-custom"><a class="anchor" href="#headers-custom"></a>7.2. Custom Headers</h3> <div class="paragraph"> <p>Spring Security has mechanisms to make it convenient to add the more common security headers to your application. However, it also provides hooks to enable adding custom headers.</p> </div> <div class="sect3"> <h4 id="headers-static"><a class="anchor" href="#headers-static"></a>7.2.1. Static Headers</h4> <div class="paragraph"> <p>There may be times you wish to inject custom security headers into your application that are not supported out of the box. For example, perhaps you wish to have early support for <a href="http://www.w3.org/TR/CSP/">Content Security Policy</a> in order to ensure that resources are only loaded from the same origin. Since support for Content Security Policy has not been finalized, browsers use one of two common extension headers to implement the feature. This means we will need to inject the policy twice. An example of the headers can be seen below:</p> </div> <div class="listingblock"> <div class="content"> <pre style="" class="prettyprint prettyprinted"><code><span class="pln">X</span><span class="pun">-</span><span class="typ">Content</span><span class="pun">-</span><span class="typ">Security</span><span class="pun">-</span><span class="typ">Policy</span><span class="pun">:</span><span class="pln"> </span><span class="kwd">default</span><span class="pun">-</span><span class="pln">src </span><span class="str">'self'</span><span class="pln"> X</span><span class="pun">-</span><span class="typ">WebKit</span><span class="pun">-</span><span class="pln">CSP</span><span class="pun">:</span><span class="pln"> </span><span class="kwd">default</span><span class="pun">-</span><span class="pln">src </span><span class="str">'self'</span></code></pre> </div> </div> <div class="paragraph"> <p>When using the XML namespace, these headers can be added to the response using the <a href="#nsa-header"><header</a>> element as shown below:</p> </div> <div class="listingblock"> <div class="content"> <pre style="" class="prettyprint xml language-xml prettyprinted"><code><span class="tag"><http></span><span class="pln"> </span><span class="com"><!-- ... --></span><span class="pln"> </span><span class="tag"><headers></span><span class="pln"> </span><span class="tag"><header</span><span class="pln"> </span><span class="atn">name</span><span class="pun">=</span><span class="atv">"X-Content-Security-Policy"</span><span class="pln"> </span><span class="atn">value</span><span class="pun">=</span><span class="atv">"default-src 'self'"</span><span class="tag">/></span><span class="pln"> </span><span class="tag"><header</span><span class="pln"> </span><span class="atn">name</span><span class="pun">=</span><span class="atv">"X-WebKit-CSP"</span><span class="pln"> </span><span class="atn">value</span><span class="pun">=</span><span class="atv">"default-src 'self'"</span><span class="tag">/></span><span class="pln"> </span><span class="tag"></headers></span><span class="pln"> </span><span class="tag"></http></span></code></pre> </div> </div> <div class="paragraph"> <p>Similarly, the headers could be added to the response using Java Configuration as shown in the following:</p> </div> <div class="listingblock"> <div class="content"> <pre style="" class="prettyprint java language-java prettyprinted"><code><span class="lit">@EnableWebSecurity</span><span class="pln"> </span><span class="lit">@Configuration</span><span class="pln"> </span><span class="kwd">public</span><span class="pln"> </span><span class="kwd">class</span><span class="pln"> </span><span class="typ">WebSecurityConfig</span><span class="pln"> </span><span class="kwd">extends</span><span class="pln"> </span><span class="typ">WebSecurityConfigurerAdapter</span><span class="pln"> </span><span class="pun">{</span><span class="pln"> </span><span class="lit">@Override</span><span class="pln"> </span><span class="kwd">protected</span><span class="pln"> </span><span class="kwd">void</span><span class="pln"> configure</span><span class="pun">(</span><span class="typ">HttpSecurity</span><span class="pln"> http</span><span class="pun">)</span><span class="pln"> </span><span class="kwd">throws</span><span class="pln"> </span><span class="typ">Exception</span><span class="pln"> </span><span class="pun">{</span><span class="pln"> http </span><span class="com">// ...</span><span class="pln"> </span><span class="pun">.</span><span class="pln">headers</span><span class="pun">()</span><span class="pln"> </span><span class="pun">.</span><span class="pln">addHeaderWriter</span><span class="pun">(</span><span class="kwd">new</span><span class="pln"> </span><span class="typ">StaticHeadersWriter</span><span class="pun">(</span><span class="str">"X-Content-Security-Policy"</span><span class="pun">,</span><span class="str">"default-src 'self'"</span><span class="pun">))</span><span class="pln"> </span><span class="pun">.</span><span class="pln">addHeaderWriter</span><span class="pun">(</span><span class="kwd">new</span><span class="pln"> </span><span class="typ">StaticHeadersWriter</span><span class="pun">(</span><span class="str">"X-WebKit-CSP"</span><span class="pun">,</span><span class="str">"default-src 'self'"</span><span class="pun">));</span><span class="pln"> </span><span class="pun">}</span><span class="pln"> </span><span class="pun">}</span></code></pre> </div> </div> </div> <div class="sect3"> <h4 id="headers-writer"><a class="anchor" href="#headers-writer"></a>7.2.2. Headers Writer</h4> <div class="paragraph"> <p>When the namespace or Java configuration does not support the headers you want, you can create a custom <code>HeadersWriter</code> instance or even provide a custom implementation of the <code>HeadersWriter</code>.</p> </div> <div class="paragraph"> <p>Let’s take a look at an example of using an custom instance of <code>XFrameOptionsHeaderWriter</code>. Perhaps you want to allow framing of content for the same origin. This is easily supported by setting the <a href="#nsa-frame-options-policy">policy</a> attribute to "SAMEORIGIN", but let’s take a look at a more explicit example using the <a href="#nsa-header-ref">ref</a> attribute.</p> </div> <div class="listingblock"> <div class="content"> <pre style="" class="prettyprint xml language-xml prettyprinted"><code><span class="tag"><http></span><span class="pln"> </span><span class="com"><!-- ... --></span><span class="pln"> </span><span class="tag"><headers></span><span class="pln"> </span><span class="tag"><header</span><span class="pln"> </span><span class="atn">ref</span><span class="pun">=</span><span class="atv">"frameOptionsWriter"</span><span class="tag">/></span><span class="pln"> </span><span class="tag"></headers></span><span class="pln"> </span><span class="tag"></http></span><span class="pln"> </span><span class="com"><!-- Requires the c-namespace. See http://static.springsource.org/spring/docs/3.2.x/spring-framework-reference/html/beans.html#beans-c-namespace --></span><span class="pln"> </span><span class="tag"><beans:bean</span><span class="pln"> </span><span class="atn">id</span><span class="pun">=</span><span class="atv">"frameOptionsWriter"</span><span class="pln"> </span><span class="atn">class</span><span class="pun">=</span><span class="atv">"org.springframework.security.web.header.writers.frameoptions.XFrameOptionsHeaderWriter"</span><span class="pln"> </span><span class="atn">c:frameOptionsMode</span><span class="pun">=</span><span class="atv">"SAMEORIGIN"</span><span class="tag">/></span></code></pre> </div> </div> <div class="paragraph"> <p>We could also restrict framing of content to the same origin with Java configuration:</p> </div> <div class="listingblock"> <div class="content"> <pre style="" class="prettyprint java language-java prettyprinted"><code><span class="lit">@EnableWebSecurity</span><span class="pln"> </span><span class="lit">@Configuration</span><span class="pln"> </span><span class="kwd">public</span><span class="pln"> </span><span class="kwd">class</span><span class="pln"> </span><span class="typ">WebSecurityConfig</span><span class="pln"> </span><span class="kwd">extends</span><span class="pln"> </span><span class="typ">WebSecurityConfigurerAdapter</span><span class="pln"> </span><span class="pun">{</span><span class="pln"> </span><span class="lit">@Override</span><span class="pln"> </span><span class="kwd">protected</span><span class="pln"> </span><span class="kwd">void</span><span class="pln"> configure</span><span class="pun">(</span><span class="typ">HttpSecurity</span><span class="pln"> http</span><span class="pun">)</span><span class="pln"> </span><span class="kwd">throws</span><span class="pln"> </span><span class="typ">Exception</span><span class="pln"> </span><span class="pun">{</span><span class="pln"> http </span><span class="com">// ...</span><span class="pln"> </span><span class="pun">.</span><span class="pln">headers</span><span class="pun">()</span><span class="pln"> </span><span class="pun">.</span><span class="pln">addHeaderWriter</span><span class="pun">(</span><span class="kwd">new</span><span class="pln"> </span><span class="typ">XFrameOptionsHeaderWriter</span><span class="pun">(</span><span class="typ">XFrameOptionsMode</span><span class="pun">.</span><span class="pln">SAMEORIGIN</span><span class="pun">));</span><span class="pln"> </span><span class="pun">}</span><span class="pln"> </span><span class="pun">}</span></code></pre> </div> </div> </div> <div class="sect3"> <h4 id="headers-delegatingrequestmatcherheaderwriter"><a class="anchor" href="#headers-delegatingrequestmatcherheaderwriter"></a>7.2.3. DelegatingRequestMatcherHeaderWriter</h4> <div class="paragraph"> <p>At times you may want to only write a header for certain requests. For example, perhaps you want to only protect your log in page from being framed. You could use the <code>DelegatingRequestMatcherHeaderWriter</code> to do so. When using the XML namespace configuration, this can be done with the following:</p> </div> <div class="listingblock"> <div class="content"> <pre style="" class="prettyprint xml language-xml prettyprinted"><code><span class="tag"><http></span><span class="pln"> </span><span class="com"><!-- ... --></span><span class="pln"> </span><span class="tag"><headers></span><span class="pln"> </span><span class="tag"><header</span><span class="pln"> </span><span class="atn">ref</span><span class="pun">=</span><span class="atv">"headerWriter"</span><span class="tag">/></span><span class="pln"> </span><span class="tag"></headers></span><span class="pln"> </span><span class="tag"></http></span><span class="pln"> </span><span class="tag"><beans:bean</span><span class="pln"> </span><span class="atn">id</span><span class="pun">=</span><span class="atv">"headerWriter"</span><span class="pln"> </span><span class="atn">class</span><span class="pun">=</span><span class="atv">"org.springframework.security.web.header.writers.DelegatingRequestMatcherHeaderWriter"</span><span class="tag">></span><span class="pln"> </span><span class="tag"><beans:constructor-arg></span><span class="pln"> </span><span class="tag"><bean</span><span class="pln"> </span><span class="atn">class</span><span class="pun">=</span><span class="atv">"org.springframework.security.web.util.matcher.AntPathRequestMatcher"</span><span class="pln"> </span><span class="atn">c:pattern</span><span class="pun">=</span><span class="atv">"/login"</span><span class="tag">/></span><span class="pln"> </span><span class="tag"></beans:constructor-arg></span><span class="pln"> </span><span class="tag"><beans:constructor-arg></span><span class="pln"> </span><span class="tag"><beans:bean</span><span class="pln"> </span><span class="atn">class</span><span class="pun">=</span><span class="atv">"org.springframework.security.web.header.writers.frameoptions.XFrameOptionsHeaderWriter"</span><span class="tag">/></span><span class="pln"> </span><span class="tag"></beans:constructor-arg></span><span class="pln"> </span><span class="tag"></beans:bean></span></code></pre> </div> </div> <div class="paragraph"> <p>We could also prevent framing of content to the log in page using java configuration:</p> </div> <div class="listingblock"> <div class="content"> <pre style="" class="prettyprint java language-java prettyprinted"><code><span class="lit">@EnableWebSecurity</span><span class="pln"> </span><span class="lit">@Configuration</span><span class="pln"> </span><span class="kwd">public</span><span class="pln"> </span><span class="kwd">class</span><span class="pln"> </span><span class="typ">WebSecurityConfig</span><span class="pln"> </span><span class="kwd">extends</span><span class="pln"> </span><span class="typ">WebSecurityConfigurerAdapter</span><span class="pln"> </span><span class="pun">{</span><span class="pln"> </span><span class="lit">@Override</span><span class="pln"> </span><span class="kwd">protected</span><span class="pln"> </span><span class="kwd">void</span><span class="pln"> configure</span><span class="pun">(</span><span class="typ">HttpSecurity</span><span class="pln"> http</span><span class="pun">)</span><span class="pln"> </span><span class="kwd">throws</span><span class="pln"> </span><span class="typ">Exception</span><span class="pln"> </span><span class="pun">{</span><span class="pln"> </span><span class="typ">RequestMatcher</span><span class="pln"> matcher </span><span class="pun">=</span><span class="pln"> </span><span class="kwd">new</span><span class="pln"> </span><span class="typ">AntPathRequestMatcher</span><span class="pun">(</span><span class="str">"/login"</span><span class="pun">);</span><span class="pln"> </span><span class="typ">DelegatingRequestMatcherHeaderWriter</span><span class="pln"> headerWriter </span><span class="pun">=</span><span class="pln"> </span><span class="kwd">new</span><span class="pln"> </span><span class="typ">DelegatingRequestMatcherHeaderWriter</span><span class="pun">(</span><span class="pln">matcher</span><span class="pun">,</span><span class="kwd">new</span><span class="pln"> </span><span class="typ">XFrameOptionsHeaderWriter</span><span class="pun">());</span><span class="pln"> http </span><span class="com">// ...</span><span class="pln"> </span><span class="pun">.</span><span class="pln">headers</span><span class="pun">()</span><span class="pln"> </span><span class="pun">.</span><span class="pln">addHeaderWriter</span><span class="pun">(</span><span class="pln">headerWriter</span><span class="pun">);</span><span class="pln"> </span><span class="pun">}</span><span class="pln"> </span><span class="pun">}</span></code></pre> </div> </div> </div> </div> </div> </div> <div class="sect1"> <h2 id="session-mgmt"><a class="anchor" href="#session-mgmt"></a>8. Session Management</h2> <div class="sectionbody"> <div class="paragraph"> <p>HTTP session related functonality is handled by a combination of the <code>SessionManagementFilter</code> and the <code>SessionAuthenticationStrategy</code> interface, which the filter delegates to. Typical usage includes session-fixation protection attack prevention, detection of session timeouts and restrictions on how many sessions an authenticated user may have open concurrently.</p> </div> <div class="sect2"> <h3 id="sessionmanagementfilter"><a class="anchor" href="#sessionmanagementfilter"></a>8.1. SessionManagementFilter</h3> <div class="paragraph"> <p>The <code>SessionManagementFilter</code> checks the contents of the <code>SecurityContextRepository</code> against the current contents of the <code>SecurityContextHolder</code> to determine whether a user has been authenticated during the current request, typically by a non-interactive authentication mechanism, such as pre-authentication or remember-me <span class="footnote">[<a id="_footnoteref_19" class="footnote" href="#_footnote_19" title="View footnote.">19</a>]</span>. If the repository contains a security context, the filter does nothing. If it doesn’t, and the thread-local <code>SecurityContext</code> contains a (non-anonymous) <code>Authentication</code> object, the filter assumes they have been authenticated by a previous filter in the stack. It will then invoke the configured <code>SessionAuthenticationStrategy</code>.</p> </div> <div class="paragraph"> <p>If the user is not currently authenticated, the filter will check whether an invalid session ID has been requested (because of a timeout, for example) and will invoke the configured`InvalidSessionStrategy`, if one is set. The most common behaviour is just to redirect to a fixed URL and this is encapsulated in the standard implementation`SimpleRedirectInvalidSessionStrategy`. The latter is also used when configuring an invalid session URL through the namespace,<a href="#ns-session-mgmt">as described earlier</a>.</p> </div> </div> <div class="sect2"> <h3 id="sessionauthenticationstrategy"><a class="anchor" href="#sessionauthenticationstrategy"></a>8.2. SessionAuthenticationStrategy</h3> <div class="paragraph"> <p><code>SessionAuthenticationStrategy</code> is used by both <code>SessionManagementFilter</code> and <code>AbstractAuthenticationProcessingFilter</code>, so if you are using a customized form-login class, for example, you will need to inject it into both of these. In this case, a typical configuration, combining the namespace and custom beans might look like this:</p> </div> <div class="listingblock"> <div class="content"> <pre style="" class="prettyprint xml language-xml prettyprinted"><code><span class="pln"> </span><span class="tag"><http></span><span class="pln"> </span><span class="tag"><custom-filter</span><span class="pln"> </span><span class="atn">position</span><span class="pun">=</span><span class="atv">"FORM_LOGIN_FILTER"</span><span class="pln"> </span><span class="atn">ref</span><span class="pun">=</span><span class="atv">"myAuthFilter"</span><span class="pln"> </span><span class="tag">/></span><span class="pln"> </span><span class="tag"><session-management</span><span class="pln"> </span><span class="atn">session-authentication-strategy-ref</span><span class="pun">=</span><span class="atv">"sas"</span><span class="tag">/></span><span class="pln"> </span><span class="tag"></http></span><span class="pln"> </span><span class="tag"><beans:bean</span><span class="pln"> </span><span class="atn">id</span><span class="pun">=</span><span class="atv">"myAuthFilter"</span><span class="pln"> </span><span class="atn">class</span><span class="pun">=</span><span class="pln"> </span><span class="atv">"org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter"</span><span class="tag">></span><span class="pln"> </span><span class="tag"><beans:property</span><span class="pln"> </span><span class="atn">name</span><span class="pun">=</span><span class="atv">"sessionAuthenticationStrategy"</span><span class="pln"> </span><span class="atn">ref</span><span class="pun">=</span><span class="atv">"sas"</span><span class="pln"> </span><span class="tag">/></span><span class="pln"> ... </span><span class="tag"></beans:bean></span><span class="pln"> </span><span class="tag"><beans:bean</span><span class="pln"> </span><span class="atn">id</span><span class="pun">=</span><span class="atv">"sas"</span><span class="pln"> </span><span class="atn">class</span><span class="pun">=</span><span class="pln"> </span><span class="atv">"org.springframework.security.web.authentication.session.SessionFixationProtectionStrategy"</span><span class="pln"> </span><span class="tag">/></span></code></pre> </div> </div> <div class="paragraph"> <p>Note that the use of the default, <code>SessionFixationProtectionStrategy</code> may cause issues if you are storing beans in the session which implement <code>HttpSessionBindingListener</code>, including Spring session-scoped beans. See the Javadoc for this class for more information.</p> </div> </div> <div class="sect2"> <h3 id="concurrent-sessions"><a class="anchor" href="#concurrent-sessions"></a>8.3. Concurrency Control</h3> <div class="paragraph"> <p>Spring Security is able to prevent a principal from concurrently authenticating to the same application more than a specified number of times. Many ISVs take advantage of this to enforce licensing, whilst network administrators like this feature because it helps prevent people from sharing login names. You can, for example, stop user"Batman" from logging onto the web application from two different sessions. You can either expire their previous login or you can report an error when they try to log in again, preventing the second login. Note that if you are using the second approach, a user who has not explicitly logged out (but who has just closed their browser, for example) will not be able to log in again until their original session expires.</p> </div> <div class="paragraph"> <p>Concurrency control is supported by the namespace, so please check the earlier namespace chapter for the simplest configuration. Sometimes you need to customize things though.</p> </div> <div class="paragraph"> <p>The implementation uses a specialized version of <code>SessionAuthenticationStrategy</code>, called <code>ConcurrentSessionControlAuthenticationStrategy</code>.</p> </div> <div class="admonitionblock note"> <table> <tbody><tr> <td class="icon"> <i class="icon-note" title="Note"></i> </td> <td class="content"> <div class="paragraph"> <p>Previously the concurrent authentication check was made by the <code>ProviderManager</code>, which could be injected with a <code>ConcurrentSessionController</code>. The latter would check if the user was attempting to exceed the number of permitted sessions. However, this approach required that an HTTP session be created in advance, which is undesirable. In Spring Security 3, the user is first authenticated by the <code>AuthenticationManager</code> and once they are successfully authenticated, a session is created and the check is made whether they are allowed to have another session open.</p> </div> </td> </tr> </tbody></table> </div> <div class="paragraph"> <p>To use concurrent session support, you’ll need to add the following to <code>web.xml</code>:</p> </div> <div class="listingblock"> <div class="content"> <pre style="" class="prettyprint xml language-xml prettyprinted"><code><span class="pln"> </span><span class="tag"><listener></span><span class="pln"> </span><span class="tag"><listener-class></span><span class="pln"> org.springframework.security.web.session.HttpSessionEventPublisher </span><span class="tag"></listener-class></span><span class="pln"> </span><span class="tag"></listener></span></code></pre> </div> </div> <div class="paragraph"> <p>In addition, you will need to add the <code>ConcurrentSessionFilter</code> to your <code>FilterChainProxy</code>. The <code>ConcurrentSessionFilter</code> requires two properties, <code>sessionRegistry</code>, which generally points to an instance of <code>SessionRegistryImpl</code>, and <code>expiredUrl</code>, which points to the page to display when a session has expired. A configuration using the namespace to create the <code>FilterChainProxy</code> and other default beans might look like this:</p> </div> <div class="listingblock"> <div class="content"> <pre style="" class="prettyprint xml language-xml prettyprinted"><code><span class="pln"> </span><span class="tag"><http></span><span class="pln"> </span><span class="tag"><custom-filter</span><span class="pln"> </span><span class="atn">position</span><span class="pun">=</span><span class="atv">"CONCURRENT_SESSION_FILTER"</span><span class="pln"> </span><span class="atn">ref</span><span class="pun">=</span><span class="atv">"concurrencyFilter"</span><span class="pln"> </span><span class="tag">/></span><span class="pln"> </span><span class="tag"><custom-filter</span><span class="pln"> </span><span class="atn">position</span><span class="pun">=</span><span class="atv">"FORM_LOGIN_FILTER"</span><span class="pln"> </span><span class="atn">ref</span><span class="pun">=</span><span class="atv">"myAuthFilter"</span><span class="pln"> </span><span class="tag">/></span><span class="pln"> </span><span class="tag"><session-management</span><span class="pln"> </span><span class="atn">session-authentication-strategy-ref</span><span class="pun">=</span><span class="atv">"sas"</span><span class="tag">/></span><span class="pln"> </span><span class="tag"></http></span><span class="pln"> </span><span class="tag"><beans:bean</span><span class="pln"> </span><span class="atn">id</span><span class="pun">=</span><span class="atv">"concurrencyFilter"</span><span class="pln"> </span><span class="atn">class</span><span class="pun">=</span><span class="atv">"org.springframework.security.web.session.ConcurrentSessionFilter"</span><span class="tag">></span><span class="pln"> </span><span class="tag"><beans:property</span><span class="pln"> </span><span class="atn">name</span><span class="pun">=</span><span class="atv">"sessionRegistry"</span><span class="pln"> </span><span class="atn">ref</span><span class="pun">=</span><span class="atv">"sessionRegistry"</span><span class="pln"> </span><span class="tag">/></span><span class="pln"> </span><span class="tag"><beans:property</span><span class="pln"> </span><span class="atn">name</span><span class="pun">=</span><span class="atv">"expiredUrl"</span><span class="pln"> </span><span class="atn">value</span><span class="pun">=</span><span class="atv">"/session-expired.htm"</span><span class="pln"> </span><span class="tag">/></span><span class="pln"> </span><span class="tag"></beans:bean></span><span class="pln"> </span><span class="tag"><beans:bean</span><span class="pln"> </span><span class="atn">id</span><span class="pun">=</span><span class="atv">"myAuthFilter"</span><span class="pln"> </span><span class="atn">class</span><span class="pun">=</span><span class="pln"> </span><span class="atv">"org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter"</span><span class="tag">></span><span class="pln"> </span><span class="tag"><beans:property</span><span class="pln"> </span><span class="atn">name</span><span class="pun">=</span><span class="atv">"sessionAuthenticationStrategy"</span><span class="pln"> </span><span class="atn">ref</span><span class="pun">=</span><span class="atv">"sas"</span><span class="pln"> </span><span class="tag">/></span><span class="pln"> </span><span class="tag"><beans:property</span><span class="pln"> </span><span class="atn">name</span><span class="pun">=</span><span class="atv">"authenticationManager"</span><span class="pln"> </span><span class="atn">ref</span><span class="pun">=</span><span class="atv">"authenticationManager"</span><span class="pln"> </span><span class="tag">/></span><span class="pln"> </span><span class="tag"></beans:bean></span><span class="pln"> </span><span class="tag"><beans:bean</span><span class="pln"> </span><span class="atn">id</span><span class="pun">=</span><span class="atv">"sas"</span><span class="pln"> </span><span class="atn">class</span><span class="pun">=</span><span class="atv">"org.springframework.security.web.authentication.session.CompositeSessionAuthenticationStrategy"</span><span class="tag">></span><span class="pln"> </span><span class="tag"><beans:constructor-arg></span><span class="pln"> </span><span class="tag"><beans:list></span><span class="pln"> </span><span class="tag"><beans:bean</span><span class="pln"> </span><span class="atn">class</span><span class="pun">=</span><span class="atv">"org.springframework.security.web.authentication.session.ConcurrentSessionControlAuthenticationStrategy"</span><span class="tag">></span><span class="pln"> </span><span class="tag"><beans:constructor-arg</span><span class="pln"> </span><span class="atn">ref</span><span class="pun">=</span><span class="atv">"sessionRegistry"</span><span class="tag">/></span><span class="pln"> </span><span class="tag"><beans:property</span><span class="pln"> </span><span class="atn">name</span><span class="pun">=</span><span class="atv">"maximumSessions"</span><span class="pln"> </span><span class="atn">value</span><span class="pun">=</span><span class="atv">"1"</span><span class="pln"> </span><span class="tag">/></span><span class="pln"> </span><span class="tag"><beans:property</span><span class="pln"> </span><span class="atn">name</span><span class="pun">=</span><span class="atv">"exceptionIfMaximumExceeded"</span><span class="pln"> </span><span class="atn">value</span><span class="pun">=</span><span class="atv">"true"</span><span class="pln"> </span><span class="tag">/></span><span class="pln"> </span><span class="tag"></beans:bean></span><span class="pln"> </span><span class="tag"><beans:bean</span><span class="pln"> </span><span class="atn">class</span><span class="pun">=</span><span class="atv">"org.springframework.security.web.authentication.session.SessionFixationProtectionStrategy"</span><span class="tag">></span><span class="pln"> </span><span class="tag"></beans:bean></span><span class="pln"> </span><span class="tag"><beans:bean</span><span class="pln"> </span><span class="atn">class</span><span class="pun">=</span><span class="atv">"org.springframework.security.web.authentication.session.RegisterSessionAuthenticationStrategy"</span><span class="tag">></span><span class="pln"> </span><span class="tag"><beans:constructor-arg</span><span class="pln"> </span><span class="atn">ref</span><span class="pun">=</span><span class="atv">"sessionRegistry"</span><span class="tag">/></span><span class="pln"> </span><span class="tag"></beans:bean></span><span class="pln"> </span><span class="tag"></beans:list></span><span class="pln"> </span><span class="tag"></beans:constructor-arg></span><span class="pln"> </span><span class="tag"></beans:bean></span><span class="pln"> </span><span class="tag"><beans:bean</span><span class="pln"> </span><span class="atn">id</span><span class="pun">=</span><span class="atv">"sessionRegistry"</span><span class="pln"> </span><span class="atn">class</span><span class="pun">=</span><span class="atv">"org.springframework.security.core.session.SessionRegistryImpl"</span><span class="pln"> </span><span class="tag">/></span></code></pre> </div> </div> <div class="paragraph"> <p>Adding the listener to <code>web.xml</code> causes an <code>ApplicationEvent</code> to be published to the Spring <code>ApplicationContext</code> every time a <code>HttpSession</code> commences or terminates. This is critical, as it allows the <code>SessionRegistryImpl</code> to be notified when a session ends. Without it, a user will never be able to log back in again once they have exceeded their session allowance, even if they log out of another session or it times out.</p> </div> <div class="sect3"> <h4 id="list-authenticated-principals"><a class="anchor" href="#list-authenticated-principals"></a>8.3.1. Querying the SessionRegistry for currently authenticated users and their sessions</h4> <div class="paragraph"> <p>Setting up concurrency-control, either through the namespace or using plain beans has the useful side effect of providing you with a reference to the <code>SessionRegistry</code> which you can use directly within your application, so even if you don’t want to restrict the number of sessions a user may have, it may be worth setting up the infrastructure anyway. You can set the <code>maximumSession</code> property to -1 to allow unlimited sessions. If you’re using the namespace, you can set an alias for the internally-created <code>SessionRegistry</code> using the <code>session-registry-alias</code> attribute, providing a reference which you can inject into your own beans.</p> </div> <div class="paragraph"> <p>The <code>getAllPrincipals()</code> method supplies you with a list of the currently authenticated users. You can list a user’s sessions by calling the <code>getAllSessions(Object principal, boolean includeExpiredSessions)</code> method, which returns a list of <code>SessionInformation</code> objects. You can also expire a user’s session by calling <code>expireNow()</code> on a <code>SessionInformation</code> instance. When the user returns to the application, they will be prevented from proceeding. You may find these methods useful in an administration application, for example. Have a look at the Javadoc for more information.</p> </div> </div> </div> </div> </div> <div class="sect1"> <h2 id="anonymous"><a class="anchor" href="#anonymous"></a>9. Anonymous Authentication</h2> <div class="sectionbody"> <div class="sect2"> <h3 id="anonymous-overview"><a class="anchor" href="#anonymous-overview"></a>9.1. Overview</h3> <div class="paragraph"> <p>It’s generally considered good security practice to adopt a "deny-by-default" where you explicitly specify what is allowed and disallow everything else. Defining what is accessible to unauthenticated users is a similar situation, particularly for web applications. Many sites require that users must be authenticated for anything other than a few URLs (for example the home and login pages). In this case it is easiest to define access configuration attributes for these specific URLs rather than have for every secured resource. Put differently, sometimes it is nice to say <code>ROLE_SOMETHING</code> is required by default and only allow certain exceptions to this rule, such as for login, logout and home pages of an application. You could also omit these pages from the filter chain entirely, thus bypassing the access control checks, but this may be undesirable for other reasons, particularly if the pages behave differently for authenticated users.</p> </div> <div class="paragraph"> <p>This is what we mean by anonymous authentication. Note that there is no real conceptual difference between a user who is "anonymously authenticated" and an unauthenticated user. Spring Security’s anonymous authentication just gives you a more convenient way to configure your access-control attributes. Calls to servlet API calls such as <code>getCallerPrincipal</code>, for example, will still return null even though there is actually an anonymous authentication object in the <code>SecurityContextHolder</code>.</p> </div> <div class="paragraph"> <p>There are other situations where anonymous authentication is useful, such as when an auditing interceptor queries the <code>SecurityContextHolder</code> to identify which principal was responsible for a given operation. Classes can be authored more robustly if they know the <code>SecurityContextHolder</code> always contains an <code>Authentication</code> object, and never <code>null</code>.</p> </div> </div> <div class="sect2"> <h3 id="anonymous-config"><a class="anchor" href="#anonymous-config"></a>9.2. Configuration</h3> <div class="paragraph"> <p>Anonymous authentication support is provided automatically when using the HTTP configuration Spring Security 3.0 and can be customized (or disabled) using the <code><anonymous></code> element. You don’t need to configure the beans described here unless you are using traditional bean configuration.</p> </div> <div class="paragraph"> <p>Three classes that together provide the anonymous authentication feature. <code>AnonymousAuthenticationToken</code> is an implementation of <code>Authentication</code>, and stores the <code>GrantedAuthority</code> s which apply to the anonymous principal. There is a corresponding <code>AnonymousAuthenticationProvider</code>, which is chained into the <code>ProviderManager</code> so that <code>AnonymousAuthenticationToken</code> s are accepted. Finally, there is an <code>AnonymousAuthenticationFilter</code>, which is chained after the normal authentication mechanisms and automatically adds an <code>AnonymousAuthenticationToken</code> to the <code>SecurityContextHolder</code> if there is no existing <code>Authentication</code> held there. The definition of the filter and authentication provider appears as follows:</p> </div> <div class="listingblock"> <div class="content"> <pre style="" class="prettyprint xml language-xml prettyprinted"><code><span class="pln"> </span><span class="tag"><bean</span><span class="pln"> </span><span class="atn">id</span><span class="pun">=</span><span class="atv">"anonymousAuthFilter"</span><span class="pln"> </span><span class="atn">class</span><span class="pun">=</span><span class="atv">"org.springframework.security.web.authentication.AnonymousAuthenticationFilter"</span><span class="tag">></span><span class="pln"> </span><span class="tag"><property</span><span class="pln"> </span><span class="atn">name</span><span class="pun">=</span><span class="atv">"key"</span><span class="pln"> </span><span class="atn">value</span><span class="pun">=</span><span class="atv">"foobar"</span><span class="tag">/></span><span class="pln"> </span><span class="tag"><property</span><span class="pln"> </span><span class="atn">name</span><span class="pun">=</span><span class="atv">"userAttribute"</span><span class="pln"> </span><span class="atn">value</span><span class="pun">=</span><span class="atv">"anonymousUser,ROLE_ANONYMOUS"</span><span class="tag">/></span><span class="pln"> </span><span class="tag"></bean></span><span class="pln"> </span><span class="tag"><bean</span><span class="pln"> </span><span class="atn">id</span><span class="pun">=</span><span class="atv">"anonymousAuthenticationProvider"</span><span class="pln"> </span><span class="atn">class</span><span class="pun">=</span><span class="atv">"org.springframework.security.authentication.AnonymousAuthenticationProvider"</span><span class="tag">></span><span class="pln"> </span><span class="tag"><property</span><span class="pln"> </span><span class="atn">name</span><span class="pun">=</span><span class="atv">"key"</span><span class="pln"> </span><span class="atn">value</span><span class="pun">=</span><span class="atv">"foobar"</span><span class="tag">/></span><span class="pln"> </span><span class="tag"></bean></span></code></pre> </div> </div> <div class="paragraph"> <p>The <code>key</code> is shared between the filter and authentication provider, so that tokens created by the former are accepted by the latter <span class="footnote">[<a id="_footnoteref_20" class="footnote" href="#_footnote_20" title="View footnote.">20</a>]</span>. The <code>userAttribute</code> is expressed in the form of <code>usernameInTheAuthenticationToken,grantedAuthority[,grantedAuthority]</code>. This is the same syntax as used after the equals sign for`InMemoryDaoImpl`'s <code>userMap</code> property.</p> </div> <div class="paragraph"> <p>As explained earlier, the benefit of anonymous authentication is that all URI patterns can have security applied to them. For example:</p> </div> <div class="listingblock"> <div class="content"> <pre style="" class="prettyprint xml language-xml prettyprinted"><code><span class="pln"> </span><span class="tag"><bean</span><span class="pln"> </span><span class="atn">id</span><span class="pun">=</span><span class="atv">"filterSecurityInterceptor"</span><span class="pln"> </span><span class="atn">class</span><span class="pun">=</span><span class="atv">"org.springframework.security.web.access.intercept.FilterSecurityInterceptor"</span><span class="tag">></span><span class="pln"> </span><span class="tag"><property</span><span class="pln"> </span><span class="atn">name</span><span class="pun">=</span><span class="atv">"authenticationManager"</span><span class="pln"> </span><span class="atn">ref</span><span class="pun">=</span><span class="atv">"authenticationManager"</span><span class="tag">/></span><span class="pln"> </span><span class="tag"><property</span><span class="pln"> </span><span class="atn">name</span><span class="pun">=</span><span class="atv">"accessDecisionManager"</span><span class="pln"> </span><span class="atn">ref</span><span class="pun">=</span><span class="atv">"httpRequestAccessDecisionManager"</span><span class="tag">/></span><span class="pln"> </span><span class="tag"><property</span><span class="pln"> </span><span class="atn">name</span><span class="pun">=</span><span class="atv">"securityMetadata"</span><span class="tag">></span><span class="pln"> </span><span class="tag"><security:filter-security-metadata-source></span><span class="pln"> </span><span class="tag"><security:intercept-url</span><span class="pln"> </span><span class="atn">pattern</span><span class="pun">=</span><span class="atv">'/index.jsp'</span><span class="pln"> </span><span class="atn">access</span><span class="pun">=</span><span class="atv">'ROLE_ANONYMOUS,ROLE_USER'</span><span class="tag">/></span><span class="pln"> </span><span class="tag"><security:intercept-url</span><span class="pln"> </span><span class="atn">pattern</span><span class="pun">=</span><span class="atv">'/hello.htm'</span><span class="pln"> </span><span class="atn">access</span><span class="pun">=</span><span class="atv">'ROLE_ANONYMOUS,ROLE_USER'</span><span class="tag">/></span><span class="pln"> </span><span class="tag"><security:intercept-url</span><span class="pln"> </span><span class="atn">pattern</span><span class="pun">=</span><span class="atv">'/logoff.jsp'</span><span class="pln"> </span><span class="atn">access</span><span class="pun">=</span><span class="atv">'ROLE_ANONYMOUS,ROLE_USER'</span><span class="tag">/></span><span class="pln"> </span><span class="tag"><security:intercept-url</span><span class="pln"> </span><span class="atn">pattern</span><span class="pun">=</span><span class="atv">'/login.jsp'</span><span class="pln"> </span><span class="atn">access</span><span class="pun">=</span><span class="atv">'ROLE_ANONYMOUS,ROLE_USER'</span><span class="tag">/></span><span class="pln"> </span><span class="tag"><security:intercept-url</span><span class="pln"> </span><span class="atn">pattern</span><span class="pun">=</span><span class="atv">'/**'</span><span class="pln"> </span><span class="atn">access</span><span class="pun">=</span><span class="atv">'ROLE_USER'</span><span class="tag">/></span><span class="pln"> </span><span class="tag"></security:filter-security-metadata-source></span><span class="pln">" + </span><span class="tag"></property></span><span class="pln"> </span><span class="tag"></bean></span></code></pre> </div> </div> </div> <div class="sect2"> <h3 id="anonymous-auth-trust-resolver"><a class="anchor" href="#anonymous-auth-trust-resolver"></a>9.3. AuthenticationTrustResolver</h3> <div class="paragraph"> <p>Rounding out the anonymous authentication discussion is the <code>AuthenticationTrustResolver</code> interface, with its corresponding <code>AuthenticationTrustResolverImpl</code> implementation. This interface provides an <code>isAnonymous(Authentication)</code> method, which allows interested classes to take into account this special type of authentication status. The <code>ExceptionTranslationFilter</code> uses this interface in processing <code>AccessDeniedException</code> s. If an <code>AccessDeniedException</code> is thrown, and the authentication is of an anonymous type, instead of throwing a 403 (forbidden) response, the filter will instead commence the <code>AuthenticationEntryPoint</code> so the principal can authenticate properly. This is a necessary distinction, otherwise principals would always be deemed "authenticated" and never be given an opportunity to login via form, basic, digest or some other normal authentication mechanism.</p> </div> <div class="paragraph"> <p>You will often see the <code>ROLE_ANONYMOUS</code> attribute in the above interceptor configuration replaced with <code>IS_AUTHENTICATED_ANONYMOUSLY</code>, which is effectively the same thing when defining access controls. This is an example of the use of the <code>AuthenticatedVoter</code> which we will see in the <a href="#authz-authenticated-voter">authorization chapter</a>. It uses an <code>AuthenticationTrustResolver</code> to process this particular configuration attribute and grant access to anonymous users. the <code>AuthenticatedVoter</code> approach is more powerful, since it allows you to differentiate between anonymous, remember-me and fully-authenticated users. If you don’t need this functionality though, then you can stick with <code>ROLE_ANONYMOUS</code>, which will be processed by Spring Security’s standard <code>RoleVoter</code>.</p> </div> </div> </div> </div> <h1 id="authorization" class="sect0"><a class="anchor" href="#authorization"></a>Authorization</h1> <div class="paragraph"> <p>The advanced authorization capabilities within Spring Security represent one of the most compelling reasons for its popularity. Irrespective of how you choose to authenticate - whether using a Spring Security-provided mechanism and provider, or integrating with a container or other non-Spring Security authentication authority - you will find the authorization services can be used within your application in a consistent and simple way.</p> </div> <div class="paragraph"> <p>In this part we’ll explore the different <code>AbstractSecurityInterceptor</code> implementations, which were introduced in Part I. We then move on to explore how to fine-tune authorization through use of domain access control lists.</p> </div> <div class="sect1"> <h2 id="authz-arch"><a class="anchor" href="#authz-arch"></a>1. Authorization Architecture</h2> <div class="sectionbody"> <div class="sect2"> <h3 id="authz-authorities"><a class="anchor" href="#authz-authorities"></a>1.1. Authorities</h3> <div class="paragraph"> <p>As we saw in the <a href="#tech-granted-authority">technical overview</a>, all <code>Authentication</code> implementations store a list of <code>GrantedAuthority</code> objects. These represent the authorities that have been granted to the principal. the <code>GrantedAuthority</code> objects are inserted into the <code>Authentication</code> object by the <code>AuthenticationManager</code> and are later read by <code>AccessDecisionManager</code> s when making authorization decisions.</p> </div> <div class="paragraph"> <p><code>GrantedAuthority</code> is an interface with only one method:</p> </div> <div class="listingblock"> <div class="content"> <pre style="" class="prettyprint java language-java prettyprinted"><code><span class="pln"> </span><span class="typ">String</span><span class="pln"> getAuthority</span><span class="pun">();</span></code></pre> </div> </div> <div class="paragraph"> <p>This method allows <code>AccessDecisionManager</code> s to obtain a precise <code>String</code> representation of the <code>GrantedAuthority</code>. By returning a representation as a <code>String</code>, a <code>GrantedAuthority</code> can be easily "read" by most <code>AccessDecisionManager</code> s. If a <code>GrantedAuthority</code> cannot be precisely represented as a <code>String</code>, the <code>GrantedAuthority</code> is considered "complex" and <code>getAuthority()</code> must return <code>null</code>.</p> </div> <div class="paragraph"> <p>An example of a "complex" <code>GrantedAuthority</code> would be an implementation that stores a list of operations and authority thresholds that apply to different customer account numbers. Representing this complex <code>GrantedAuthority</code> as a <code>String</code> would be quite difficult, and as a result the <code>getAuthority()</code> method should return <code>null</code>. This will indicate to any <code>AccessDecisionManager</code> that it will need to specifically support the <code>GrantedAuthority</code> implementation in order to understand its contents.</p> </div> <div class="paragraph"> <p>Spring Security includes one concrete <code>GrantedAuthority</code> implementation, <code>GrantedAuthorityImpl</code>. This allows any user-specified <code>String</code> to be converted into a <code>GrantedAuthority</code>. All <code>AuthenticationProvider</code> s included with the security architecture use <code>GrantedAuthorityImpl</code> to populate the <code>Authentication</code> object.</p> </div> </div> <div class="sect2"> <h3 id="authz-pre-invocation"><a class="anchor" href="#authz-pre-invocation"></a>1.2. Pre-Invocation Handling</h3> <div class="paragraph"> <p>As we’ve also seen in the <a href="#secure-objects">Technical Overview</a> chapter, Spring Security provides interceptors which control access to secure objects such as method invocations or web requests. A pre-invocation decision on whether the invocation is allowed to proceed is made by the <code>AccessDecisionManager</code>.</p> </div> <div class="sect3"> <h4 id="authz-access-decision-manager"><a class="anchor" href="#authz-access-decision-manager"></a>1.2.1. The AccessDecisionManager</h4> <div class="paragraph"> <p>The <code>AccessDecisionManager</code> is called by the <code>AbstractSecurityInterceptor</code> and is responsible for making final access control decisions. the <code>AccessDecisionManager</code> interface contains three methods:</p> </div> <div class="listingblock"> <div class="content"> <pre style="" class="prettyprint java language-java prettyprinted"><code><span class="kwd">void</span><span class="pln"> decide</span><span class="pun">(</span><span class="typ">Authentication</span><span class="pln"> authentication</span><span class="pun">,</span><span class="pln"> </span><span class="typ">Object</span><span class="pln"> secureObject</span><span class="pun">,</span><span class="pln"> </span><span class="typ">Collection</span><span class="pun"><</span><span class="typ">ConfigAttribute</span><span class="pun">></span><span class="pln"> attrs</span><span class="pun">)</span><span class="pln"> </span><span class="kwd">throws</span><span class="pln"> </span><span class="typ">AccessDeniedException</span><span class="pun">;</span><span class="pln"> </span><span class="kwd">boolean</span><span class="pln"> supports</span><span class="pun">(</span><span class="typ">ConfigAttribute</span><span class="pln"> attribute</span><span class="pun">);</span><span class="pln"> </span><span class="kwd">boolean</span><span class="pln"> supports</span><span class="pun">(</span><span class="typ">Class</span><span class="pln"> clazz</span><span class="pun">);</span></code></pre> </div> </div> <div class="paragraph"> <p>The <code>AccessDecisionManager</code>'s <code>decide</code> method is passed all the relevant information it needs in order to make an authorization decision. In particular, passing the secure <code>Object</code> enables those arguments contained in the actual secure object invocation to be inspected. For example, let’s assume the secure object was a`MethodInvocation`. It would be easy to query the <code>MethodInvocation</code> for any <code>Customer</code> argument, and then implement some sort of security logic in the <code>AccessDecisionManager</code> to ensure the principal is permitted to operate on that customer. Implementations are expected to throw an <code>AccessDeniedException</code> if access is denied.</p> </div> <div class="paragraph"> <p>The <code>supports(ConfigAttribute)</code> method is called by the <code>AbstractSecurityInterceptor</code> at startup time to determine if the <code>AccessDecisionManager</code> can process the passed <code>ConfigAttribute</code>. The <code>supports(Class)</code> method is called by a security interceptor implementation to ensure the configured <code>AccessDecisionManager</code> supports the type of secure object that the security interceptor will present.</p> </div> </div> <div class="sect3"> <h4 id="authz-voting-based"><a class="anchor" href="#authz-voting-based"></a>1.2.2. Voting-Based AccessDecisionManager Implementations</h4> <div class="paragraph"> <p>Whilst users can implement their own <code>AccessDecisionManager</code> to control all aspects of authorization, Spring Security includes several <code>AccessDecisionManager</code> implementations that are based on voting. <a href="#authz-access-voting">Voting Decision Manager</a> illustrates the relevant classes.</p> </div> <div id="authz-access-voting" class="imageblock"> <div class="content"> <img src="Spring%20Security%20Reference_files/access-decision-voting.png" alt="access decision voting"> </div> <div class="title">Figure 2. Voting Decision Manager</div> </div> <div class="paragraph"> <p>Using this approach, a series of <code>AccessDecisionVoter</code> implementations are polled on an authorization decision. The <code>AccessDecisionManager</code> then decides whether or not to throw an <code>AccessDeniedException</code> based on its assessment of the votes.</p> </div> <div class="paragraph"> <p>The <code>AccessDecisionVoter</code> interface has three methods:</p> </div> <div class="listingblock"> <div class="content"> <pre style="" class="prettyprint java language-java prettyprinted"><code><span class="kwd">int</span><span class="pln"> vote</span><span class="pun">(</span><span class="typ">Authentication</span><span class="pln"> authentication</span><span class="pun">,</span><span class="pln"> </span><span class="typ">Object</span><span class="pln"> object</span><span class="pun">,</span><span class="pln"> </span><span class="typ">Collection</span><span class="pun"><</span><span class="typ">ConfigAttribute</span><span class="pun">></span><span class="pln"> attrs</span><span class="pun">);</span><span class="pln"> </span><span class="kwd">boolean</span><span class="pln"> supports</span><span class="pun">(</span><span class="typ">ConfigAttribute</span><span class="pln"> attribute</span><span class="pun">);</span><span class="pln"> </span><span class="kwd">boolean</span><span class="pln"> supports</span><span class="pun">(</span><span class="typ">Class</span><span class="pln"> clazz</span><span class="pun">);</span></code></pre> </div> </div> <div class="paragraph"> <p>Concrete implementations return an <code>int</code>, with possible values being reflected in the <code>AccessDecisionVoter</code> static fields <code>ACCESS_ABSTAIN</code>, <code>ACCESS_DENIED</code> and <code>ACCESS_GRANTED</code>. A voting implementation will return <code>ACCESS_ABSTAIN</code> if it has no opinion on an authorization decision. If it does have an opinion, it must return either <code>ACCESS_DENIED</code> or <code>ACCESS_GRANTED</code>.</p> </div> <div class="paragraph"> <p>There are three concrete <code>AccessDecisionManager</code> s provided with Spring Security that tally the votes. the <code>ConsensusBased</code> implementation will grant or deny access based on the consensus of non-abstain votes. Properties are provided to control behavior in the event of an equality of votes or if all votes are abstain. The <code>AffirmativeBased</code> implementation will grant access if one or more <code>ACCESS_GRANTED</code> votes were received (i.e. a deny vote will be ignored, provided there was at least one grant vote). Like the <code>ConsensusBased</code> implementation, there is a parameter that controls the behavior if all voters abstain. The <code>UnanimousBased</code> provider expects unanimous <code>ACCESS_GRANTED</code> votes in order to grant access, ignoring abstains. It will deny access if there is any <code>ACCESS_DENIED</code> vote. Like the other implementations, there is a parameter that controls the behaviour if all voters abstain.</p> </div> <div class="paragraph"> <p>It is possible to implement a custom <code>AccessDecisionManager</code> that tallies votes differently. For example, votes from a particular <code>AccessDecisionVoter</code> might receive additional weighting, whilst a deny vote from a particular voter may have a veto effect.</p> </div> <div class="sect4"> <h5 id="authz-role-voter"><a class="anchor" href="#authz-role-voter"></a>RoleVoter</h5> <div class="paragraph"> <p>The most commonly used <code>AccessDecisionVoter</code> provided with Spring Security is the simple <code>RoleVoter</code>, which treats configuration attributes as simple role names and votes to grant access if the user has been assigned that role.</p> </div> <div class="paragraph"> <p>It will vote if any <code>ConfigAttribute</code> begins with the prefix <code>ROLE_</code>. It will vote to grant access if there is a <code>GrantedAuthority</code> which returns a <code>String</code> representation (via the <code>getAuthority()</code> method) exactly equal to one or more <code>ConfigAttributes</code> starting with the prefix <code>ROLE_</code>. If there is no exact match of any <code>ConfigAttribute</code> starting with <code>ROLE_</code>, the <code>RoleVoter</code> will vote to deny access. If no <code>ConfigAttribute</code> begins with <code>ROLE_</code>, the voter will abstain.</p> </div> </div> <div class="sect4"> <h5 id="authz-authenticated-voter"><a class="anchor" href="#authz-authenticated-voter"></a>AuthenticatedVoter</h5> <div class="paragraph"> <p>Another voter which we’ve implicitly seen is the <code>AuthenticatedVoter</code>, which can be used to differentiate between anonymous, fully-authenticated and remember-me authenticated users. Many sites allow certain limited access under remember-me authentication, but require a user to confirm their identity by logging in for full access.</p> </div> <div class="paragraph"> <p>When we’ve used the attribute <code>IS_AUTHENTICATED_ANONYMOUSLY</code> to grant anonymous access, this attribute was being processed by the <code>AuthenticatedVoter</code>. See the Javadoc for this class for more information.</p> </div> </div> <div class="sect4"> <h5 id="authz-custom-voter"><a class="anchor" href="#authz-custom-voter"></a>Custom Voters</h5> <div class="paragraph"> <p>Obviously, you can also implement a custom <code>AccessDecisionVoter</code> and you can put just about any access-control logic you want in it. It might be specific to your application (business-logic related) or it might implement some security administration logic. For example, you’ll find a <a href="http://blog.springsource.com/2009/01/02/spring-security-customization-part-2-adjusting-secured-session-in-real-time/"> blog article</a> on the SpringSource web site which describes how to use a voter to deny access in real-time to users whose accounts have been suspended.</p> </div> </div> </div> </div> <div class="sect2"> <h3 id="authz-after-invocation-handling"><a class="anchor" href="#authz-after-invocation-handling"></a>1.3. After Invocation Handling</h3> <div class="paragraph"> <p>Whilst the <code>AccessDecisionManager</code> is called by the <code>AbstractSecurityInterceptor</code> before proceeding with the secure object invocation, some applications need a way of modifying the object actually returned by the secure object invocation. Whilst you could easily implement your own AOP concern to achieve this, Spring Security provides a convenient hook that has several concrete implementations that integrate with its ACL capabilities.</p> </div> <div class="paragraph"> <p><a href="#authz-after-invocation">After Invocation Implementation</a> illustrates Spring Security’s <code>AfterInvocationManager</code> and its concrete implementations.</p> </div> <div id="authz-after-invocation" class="imageblock"> <div class="content"> <img src="Spring%20Security%20Reference_files/after-invocation.png" alt="after invocation"> </div> <div class="title">Figure 3. After Invocation Implementation</div> </div> <div class="paragraph"> <p>Like many other parts of Spring Security, <code>AfterInvocationManager</code> has a single concrete implementation, <code>AfterInvocationProviderManager</code>, which polls a list of <code>AfterInvocationProvider</code> s. Each <code>AfterInvocationProvider</code> is allowed to modify the return object or throw an <code>AccessDeniedException</code>. Indeed multiple providers can modify the object, as the result of the previous provider is passed to the next in the list.</p> </div> <div class="paragraph"> <p>Please be aware that if you’re using <code>AfterInvocationManager</code>, you will still need configuration attributes that allow the <code>MethodSecurityInterceptor</code>'s <code>AccessDecisionManager</code> to allow an operation. If you’re using the typical Spring Security included <code>AccessDecisionManager</code> implementations, having no configuration attributes defined for a particular secure method invocation will cause each <code>AccessDecisionVoter</code> to abstain from voting. In turn, if the <code>AccessDecisionManager</code> property "<code>allowIfAllAbstainDecisions</code>" is <code>false</code>, an <code>AccessDeniedException</code> will be thrown. You may avoid this potential issue by either (i) setting "<code>allowIfAllAbstainDecisions</code>" to <code>true</code> (although this is generally not recommended) or (ii) simply ensure that there is at least one configuration attribute that an <code>AccessDecisionVoter</code> will vote to grant access for. This latter (recommended) approach is usually achieved through a <code>ROLE_USER</code> or <code>ROLE_AUTHENTICATED</code> configuration attribute.</p> </div> </div> <div class="sect2"> <h3 id="authz-hierarchical-roles"><a class="anchor" href="#authz-hierarchical-roles"></a>1.4. Hierarchical Roles</h3> <div class="paragraph"> <p>It is a common requirement that a particular role in an application should automatically "include" other roles. For example, in an application which has the concept of an "admin" and a "user" role, you may want an admin to be able to do everything a normal user can. To achieve this, you can either make sure that all admin users are also assigned the "user" role. Alternatively, you can modify every access constraint which requires the "user" role to also include the "admin" role. This can get quite complicated if you have a lot of different roles in your application.</p> </div> <div class="paragraph"> <p>The use of a role-hierarchy allows you to configure which roles (or authorities) should include others. An extended version of Spring Security’s <a href="#authz-role-voter">RoleVoter</a>, <code>RoleHierarchyVoter</code>, is configured with a <code>RoleHierarchy</code>, from which it obtains all the "reachable authorities" which the user is assigned. A typical configuration might look like this:</p> </div> <div class="listingblock"> <div class="content"> <pre style="" class="prettyprint xml language-xml prettyprinted"><code><span class="pln"> </span><span class="tag"><bean</span><span class="pln"> </span><span class="atn">id</span><span class="pun">=</span><span class="atv">"roleVoter"</span><span class="pln"> </span><span class="atn">class</span><span class="pun">=</span><span class="atv">"org.springframework.security.access.vote.RoleHierarchyVoter"</span><span class="tag">></span><span class="pln"> </span><span class="tag"><constructor-arg</span><span class="pln"> </span><span class="atn">ref</span><span class="pun">=</span><span class="atv">"roleHierarchy"</span><span class="pln"> </span><span class="tag">/></span><span class="pln"> </span><span class="tag"></bean></span><span class="pln"> </span><span class="tag"><bean</span><span class="pln"> </span><span class="atn">id</span><span class="pun">=</span><span class="atv">"roleHierarchy"</span><span class="pln"> </span><span class="atn">class</span><span class="pun">=</span><span class="atv">"org.springframework.security.access.hierarchicalroles.RoleHierarchyImpl"</span><span class="tag">></span><span class="pln"> </span><span class="tag"><property</span><span class="pln"> </span><span class="atn">name</span><span class="pun">=</span><span class="atv">"hierarchy"</span><span class="tag">></span><span class="pln"> </span><span class="tag"><value></span><span class="pln"> ROLE_ADMIN > ROLE_STAFF ROLE_STAFF > ROLE_USER ROLE_USER > ROLE_GUEST </span><span class="tag"></value></span><span class="pln"> </span><span class="tag"></property></span><span class="pln"> </span><span class="tag"></bean></span></code></pre> </div> </div> <div class="paragraph"> <p>Here we have four roles in a hierarchy <code>ROLE_ADMIN => ROLE_STAFF => ROLE_USER => ROLE_GUEST</code>. A user who is authenticated with <code>ROLE_ADMIN</code>, will behave as if they have all four roles when security contraints are evaluated against an <code>AccessDecisionManager</code> cconfigured with the above <code>RoleHierarchyVoter</code>. The <code>></code> symbol can be thought of as meaning "includes".</p> </div> <div class="paragraph"> <p>Role hierarchies offer a convenient means of simplifying the access-control configuration data for your application and/or reducing the number of authorities which you need to assign to a user. For more complex requirements you may wish to define a logical mapping between the specific access-rights your application requires and the roles that are assigned to users, translating between the two when loading the user information.</p> </div> </div> </div> </div> <div class="sect1"> <h2 id="secure-object-impls"><a class="anchor" href="#secure-object-impls"></a>2. Secure Object Implementations</h2> <div class="sectionbody"> <div class="sect2"> <h3 id="aop-alliance"><a class="anchor" href="#aop-alliance"></a>2.1. AOP Alliance (MethodInvocation) Security Interceptor</h3> <div class="paragraph"> <p>Prior to Spring Security 2.0, securing <code>MethodInvocation</code> s needed quite a lot of boiler plate configuration. Now the recommended approach for method security is to use <a href="#ns-method-security">namespace configuration</a>. This way the method security infrastructure beans are configured automatically for you so you don’t really need to know about the implementation classes. We’ll just provide a quick overview of the classes that are involved here.</p> </div> <div class="paragraph"> <p>Method security in enforced using a <code>MethodSecurityInterceptor</code>, which secures <code>MethodInvocation</code> s. Depending on the configuration approach, an interceptor may be specific to a single bean or shared between multiple beans. The interceptor uses a <code>MethodSecurityMetadataSource</code> instance to obtain the configuration attributes that apply to a particular method invocation. <code>MapBasedMethodSecurityMetadataSource</code> is used to store configuration attributes keyed by method names (which can be wildcarded) and will be used internally when the attributes are defined in the application context using the <code><intercept-methods></code> or <code><protect-point></code> elements. Other implementations will be used to handle annotation-based configuration.</p> </div> <div class="sect3"> <h4 id="explicit-methodsecurityinterceptor-configuration"><a class="anchor" href="#explicit-methodsecurityinterceptor-configuration"></a>2.1.1. Explicit MethodSecurityInterceptor Configuration</h4> <div class="paragraph"> <p>You can of course configure a <code>MethodSecurityIterceptor</code> directly in your application context for use with one of Spring AOP’s proxying mechanisms:</p> </div> <div class="listingblock"> <div class="content"> <pre style="" class="prettyprint xml language-xml prettyprinted"><code><span class="pln"> </span><span class="tag"><bean</span><span class="pln"> </span><span class="atn">id</span><span class="pun">=</span><span class="atv">"bankManagerSecurity"</span><span class="pln"> </span><span class="atn">class</span><span class="pun">=</span><span class="pln"> </span><span class="atv">"org.springframework.security.access.intercept.aopalliance.MethodSecurityInterceptor"</span><span class="tag">></span><span class="pln"> </span><span class="tag"><property</span><span class="pln"> </span><span class="atn">name</span><span class="pun">=</span><span class="atv">"authenticationManager"</span><span class="pln"> </span><span class="atn">ref</span><span class="pun">=</span><span class="atv">"authenticationManager"</span><span class="tag">/></span><span class="pln"> </span><span class="tag"><property</span><span class="pln"> </span><span class="atn">name</span><span class="pun">=</span><span class="atv">"accessDecisionManager"</span><span class="pln"> </span><span class="atn">ref</span><span class="pun">=</span><span class="atv">"accessDecisionManager"</span><span class="tag">/></span><span class="pln"> </span><span class="tag"><property</span><span class="pln"> </span><span class="atn">name</span><span class="pun">=</span><span class="atv">"afterInvocationManager"</span><span class="pln"> </span><span class="atn">ref</span><span class="pun">=</span><span class="atv">"afterInvocationManager"</span><span class="tag">/></span><span class="pln"> </span><span class="tag"><property</span><span class="pln"> </span><span class="atn">name</span><span class="pun">=</span><span class="atv">"securityMetadataSource"</span><span class="tag">></span><span class="pln"> </span><span class="tag"><sec:method-security-metadata-source></span><span class="pln"> </span><span class="tag"><sec:protect</span><span class="pln"> </span><span class="atn">method</span><span class="pun">=</span><span class="atv">"com.mycompany.BankManager.delete*"</span><span class="pln"> </span><span class="atn">access</span><span class="pun">=</span><span class="atv">"ROLE_SUPERVISOR"</span><span class="tag">/></span><span class="pln"> </span><span class="tag"><sec:protect</span><span class="pln"> </span><span class="atn">method</span><span class="pun">=</span><span class="atv">"com.mycompany.BankManager.getBalance"</span><span class="pln"> </span><span class="atn">access</span><span class="pun">=</span><span class="atv">"ROLE_TELLER,ROLE_SUPERVISOR"</span><span class="tag">/></span><span class="pln"> </span><span class="tag"></sec:method-security-metadata-source></span><span class="pln"> </span><span class="tag"></property></span><span class="pln"> </span><span class="tag"></bean></span></code></pre> </div> </div> </div> </div> <div class="sect2"> <h3 id="aspectj"><a class="anchor" href="#aspectj"></a>2.2. AspectJ (JoinPoint) Security Interceptor</h3> <div class="paragraph"> <p>The AspectJ security interceptor is very similar to the AOP Alliance security interceptor discussed in the previous section. Indeed we will only discuss the differences in this section.</p> </div> <div class="paragraph"> <p>The AspectJ interceptor is named <code>AspectJSecurityInterceptor</code>. Unlike the AOP Alliance security interceptor, which relies on the Spring application context to weave in the security interceptor via proxying, the <code>AspectJSecurityInterceptor</code> is weaved in via the AspectJ compiler. It would not be uncommon to use both types of security interceptors in the same application, with <code>AspectJSecurityInterceptor</code> being used for domain object instance security and the AOP Alliance <code>MethodSecurityInterceptor</code> being used for services layer security.</p> </div> <div class="paragraph"> <p>Let’s first consider how the <code>AspectJSecurityInterceptor</code> is configured in the Spring application context:</p> </div> <div class="listingblock"> <div class="content"> <pre style="" class="prettyprint xml language-xml prettyprinted"><code><span class="pln"> </span><span class="tag"><bean</span><span class="pln"> </span><span class="atn">id</span><span class="pun">=</span><span class="atv">"bankManagerSecurity"</span><span class="pln"> </span><span class="atn">class</span><span class="pun">=</span><span class="pln"> </span><span class="atv">"org.springframework.security.access.intercept.aspectj.AspectJMethodSecurityInterceptor"</span><span class="tag">></span><span class="pln"> </span><span class="tag"><property</span><span class="pln"> </span><span class="atn">name</span><span class="pun">=</span><span class="atv">"authenticationManager"</span><span class="pln"> </span><span class="atn">ref</span><span class="pun">=</span><span class="atv">"authenticationManager"</span><span class="tag">/></span><span class="pln"> </span><span class="tag"><property</span><span class="pln"> </span><span class="atn">name</span><span class="pun">=</span><span class="atv">"accessDecisionManager"</span><span class="pln"> </span><span class="atn">ref</span><span class="pun">=</span><span class="atv">"accessDecisionManager"</span><span class="tag">/></span><span class="pln"> </span><span class="tag"><property</span><span class="pln"> </span><span class="atn">name</span><span class="pun">=</span><span class="atv">"afterInvocationManager"</span><span class="pln"> </span><span class="atn">ref</span><span class="pun">=</span><span class="atv">"afterInvocationManager"</span><span class="tag">/></span><span class="pln"> </span><span class="tag"><property</span><span class="pln"> </span><span class="atn">name</span><span class="pun">=</span><span class="atv">"securityMetadataSource"</span><span class="tag">></span><span class="pln"> </span><span class="tag"><sec:method-security-metadata-source></span><span class="pln"> </span><span class="tag"><sec:protect</span><span class="pln"> </span><span class="atn">method</span><span class="pun">=</span><span class="atv">"com.mycompany.BankManager.delete*"</span><span class="pln"> </span><span class="atn">access</span><span class="pun">=</span><span class="atv">"ROLE_SUPERVISOR"</span><span class="tag">/></span><span class="pln"> </span><span class="tag"><sec:protect</span><span class="pln"> </span><span class="atn">method</span><span class="pun">=</span><span class="atv">"com.mycompany.BankManager.getBalance"</span><span class="pln"> </span><span class="atn">access</span><span class="pun">=</span><span class="atv">"ROLE_TELLER,ROLE_SUPERVISOR"</span><span class="tag">/></span><span class="pln"> </span><span class="tag"></sec:method-security-metadata-source></span><span class="pln"> </span><span class="tag"></property></span><span class="pln"> </span><span class="tag"></bean></span></code></pre> </div> </div> <div class="paragraph"> <p>As you can see, aside from the class name, the <code>AspectJSecurityInterceptor</code> is exactly the same as the AOP Alliance security interceptor. Indeed the two interceptors can share the same`securityMetadataSource`, as the <code>SecurityMetadataSource</code> works with <code>java.lang.reflect.Method</code> s rather than an AOP library-specific class. Of course, your access decisions have access to the relevant AOP library-specific invocation (ie <code>MethodInvocation</code> or <code>JoinPoint</code>) and as such can consider a range of addition criteria when making access decisions (such as method arguments).</p> </div> <div class="paragraph"> <p>Next you’ll need to define an AspectJ <code>aspect</code>. For example:</p> </div> <div class="listingblock"> <div class="content"> <pre style="" class="prettyprint java language-java prettyprinted"><code><span class="pln"> </span><span class="kwd">package</span><span class="pln"> org</span><span class="pun">.</span><span class="pln">springframework</span><span class="pun">.</span><span class="pln">security</span><span class="pun">.</span><span class="pln">samples</span><span class="pun">.</span><span class="pln">aspectj</span><span class="pun">;</span><span class="pln"> </span><span class="kwd">import</span><span class="pln"> org</span><span class="pun">.</span><span class="pln">springframework</span><span class="pun">.</span><span class="pln">security</span><span class="pun">.</span><span class="pln">access</span><span class="pun">.</span><span class="pln">intercept</span><span class="pun">.</span><span class="pln">aspectj</span><span class="pun">.</span><span class="typ">AspectJSecurityInterceptor</span><span class="pun">;</span><span class="pln"> </span><span class="kwd">import</span><span class="pln"> org</span><span class="pun">.</span><span class="pln">springframework</span><span class="pun">.</span><span class="pln">security</span><span class="pun">.</span><span class="pln">access</span><span class="pun">.</span><span class="pln">intercept</span><span class="pun">.</span><span class="pln">aspectj</span><span class="pun">.</span><span class="typ">AspectJCallback</span><span class="pun">;</span><span class="pln"> </span><span class="kwd">import</span><span class="pln"> org</span><span class="pun">.</span><span class="pln">springframework</span><span class="pun">.</span><span class="pln">beans</span><span class="pun">.</span><span class="pln">factory</span><span class="pun">.</span><span class="typ">InitializingBean</span><span class="pun">;</span><span class="pln"> </span><span class="kwd">public</span><span class="pln"> aspect </span><span class="typ">DomainObjectInstanceSecurityAspect</span><span class="pln"> </span><span class="kwd">implements</span><span class="pln"> </span><span class="typ">InitializingBean</span><span class="pln"> </span><span class="pun">{</span><span class="pln"> </span><span class="kwd">private</span><span class="pln"> </span><span class="typ">AspectJSecurityInterceptor</span><span class="pln"> securityInterceptor</span><span class="pun">;</span><span class="pln"> pointcut domainObjectInstanceExecution</span><span class="pun">():</span><span class="pln"> target</span><span class="pun">(</span><span class="typ">PersistableEntity</span><span class="pun">)</span><span class="pln"> </span><span class="pun">&&</span><span class="pln"> execution</span><span class="pun">(</span><span class="kwd">public</span><span class="pln"> </span><span class="pun">*</span><span class="pln"> </span><span class="pun">*(..))</span><span class="pln"> </span><span class="pun">&&</span><span class="pln"> </span><span class="pun">!</span><span class="pln">within</span><span class="pun">(</span><span class="typ">DomainObjectInstanceSecurityAspect</span><span class="pun">);</span><span class="pln"> </span><span class="typ">Object</span><span class="pln"> around</span><span class="pun">():</span><span class="pln"> domainObjectInstanceExecution</span><span class="pun">()</span><span class="pln"> </span><span class="pun">{</span><span class="pln"> </span><span class="kwd">if</span><span class="pln"> </span><span class="pun">(</span><span class="kwd">this</span><span class="pun">.</span><span class="pln">securityInterceptor </span><span class="pun">==</span><span class="pln"> </span><span class="kwd">null</span><span class="pun">)</span><span class="pln"> </span><span class="pun">{</span><span class="pln"> </span><span class="kwd">return</span><span class="pln"> proceed</span><span class="pun">();</span><span class="pln"> </span><span class="pun">}</span><span class="pln"> </span><span class="typ">AspectJCallback</span><span class="pln"> callback </span><span class="pun">=</span><span class="pln"> </span><span class="kwd">new</span><span class="pln"> </span><span class="typ">AspectJCallback</span><span class="pun">()</span><span class="pln"> </span><span class="pun">{</span><span class="pln"> </span><span class="kwd">public</span><span class="pln"> </span><span class="typ">Object</span><span class="pln"> proceedWithObject</span><span class="pun">()</span><span class="pln"> </span><span class="pun">{</span><span class="pln"> </span><span class="kwd">return</span><span class="pln"> proceed</span><span class="pun">();</span><span class="pln"> </span><span class="pun">}</span><span class="pln"> </span><span class="pun">};</span><span class="pln"> </span><span class="kwd">return</span><span class="pln"> </span><span class="kwd">this</span><span class="pun">.</span><span class="pln">securityInterceptor</span><span class="pun">.</span><span class="pln">invoke</span><span class="pun">(</span><span class="pln">thisJoinPoint</span><span class="pun">,</span><span class="pln"> callback</span><span class="pun">);</span><span class="pln"> </span><span class="pun">}</span><span class="pln"> </span><span class="kwd">public</span><span class="pln"> </span><span class="typ">AspectJSecurityInterceptor</span><span class="pln"> getSecurityInterceptor</span><span class="pun">()</span><span class="pln"> </span><span class="pun">{</span><span class="pln"> </span><span class="kwd">return</span><span class="pln"> securityInterceptor</span><span class="pun">;</span><span class="pln"> </span><span class="pun">}</span><span class="pln"> </span><span class="kwd">public</span><span class="pln"> </span><span class="kwd">void</span><span class="pln"> setSecurityInterceptor</span><span class="pun">(</span><span class="typ">AspectJSecurityInterceptor</span><span class="pln"> securityInterceptor</span><span class="pun">)</span><span class="pln"> </span><span class="pun">{</span><span class="pln"> </span><span class="kwd">this</span><span class="pun">.</span><span class="pln">securityInterceptor </span><span class="pun">=</span><span class="pln"> securityInterceptor</span><span class="pun">;</span><span class="pln"> </span><span class="pun">}</span><span class="pln"> </span><span class="kwd">public</span><span class="pln"> </span><span class="kwd">void</span><span class="pln"> afterPropertiesSet</span><span class="pun">()</span><span class="pln"> </span><span class="kwd">throws</span><span class="pln"> </span><span class="typ">Exception</span><span class="pln"> </span><span class="pun">{</span><span class="pln"> </span><span class="kwd">if</span><span class="pln"> </span><span class="pun">(</span><span class="kwd">this</span><span class="pun">.</span><span class="pln">securityInterceptor </span><span class="pun">==</span><span class="pln"> </span><span class="kwd">null</span><span class="pun">)</span><span class="pln"> </span><span class="kwd">throw</span><span class="pln"> </span><span class="kwd">new</span><span class="pln"> </span><span class="typ">IllegalArgumentException</span><span class="pun">(</span><span class="str">"securityInterceptor required"</span><span class="pun">);</span><span class="pln"> </span><span class="pun">}</span><span class="pln"> </span><span class="pun">}</span><span class="pln"> </span><span class="pun">}</span></code></pre> </div> </div> <div class="paragraph"> <p>In the above example, the security interceptor will be applied to every instance of <code>PersistableEntity</code>, which is an abstract class not shown (you can use any other class or <code>pointcut</code> expression you like). For those curious, <code>AspectJCallback</code> is needed because the <code>proceed();</code> statement has special meaning only within an <code>around()</code> body. The <code>AspectJSecurityInterceptor</code> calls this anonymous <code>AspectJCallback</code> class when it wants the target object to continue.</p> </div> <div class="paragraph"> <p>You will need to configure Spring to load the aspect and wire it with the <code>AspectJSecurityInterceptor</code>. A bean declaration which achieves this is shown below:</p> </div> <div class="listingblock"> <div class="content"> <pre style="" class="prettyprint xml language-xml prettyprinted"><code><span class="pln"> </span><span class="tag"><bean</span><span class="pln"> </span><span class="atn">id</span><span class="pun">=</span><span class="atv">"domainObjectInstanceSecurityAspect"</span><span class="pln"> </span><span class="atn">class</span><span class="pun">=</span><span class="atv">"security.samples.aspectj.DomainObjectInstanceSecurityAspect"</span><span class="pln"> </span><span class="atn">factory-method</span><span class="pun">=</span><span class="atv">"aspectOf"</span><span class="tag">></span><span class="pln"> </span><span class="tag"><property</span><span class="pln"> </span><span class="atn">name</span><span class="pun">=</span><span class="atv">"securityInterceptor"</span><span class="pln"> </span><span class="atn">ref</span><span class="pun">=</span><span class="atv">"bankManagerSecurity"</span><span class="tag">/></span><span class="pln"> </span><span class="tag"></bean></span></code></pre> </div> </div> <div class="paragraph"> <p>That’s it! Now you can create your beans from anywhere within your application, using whatever means you think fit (eg <code>new Person();</code>) and they will have the security interceptor applied.</p> </div> </div> </div> </div> <div class="sect1"> <h2 id="el-access"><a class="anchor" href="#el-access"></a>3. Expression-Based Access Control</h2> <div class="sectionbody"> <div class="paragraph"> <p>Spring Security 3.0 introduced the ability to use Spring EL expressions as an authorization mechanism in addition to the simple use of configuration attributes and access-decision voters which have seen before. Expression-based access control is built on the same architecture but allows complicated boolean logic to be encapsulated in a single expression.</p> </div> <div class="sect2"> <h3 id="overview"><a class="anchor" href="#overview"></a>3.1. Overview</h3> <div class="paragraph"> <p>Spring Security uses Spring EL for expression support and you should look at how that works if you are interested in understanding the topic in more depth. Expressions are evaluated with a "root object" as part of the evaluation context. Spring Security uses specific classes for web and method security as the root object, in order to provide built-in expressions and access to values such as the current principal.</p> </div> <div class="sect3"> <h4 id="el-common-built-in"><a class="anchor" href="#el-common-built-in"></a>3.1.1. Common Built-In Expressions</h4> <div class="paragraph"> <p>The base class for expression root objects is <code>SecurityExpressionRoot</code>. This provides some common expressions which are available in both web and method security.</p> </div> <table id="common-expressions" class="tableblock frame-all grid-all" style="width:100%; "> <caption class="title">Table 2. Common built-in expressions</caption> <colgroup> <col style="width:50%;"> <col style="width:50%;"> </colgroup> <thead> <tr> <th class="tableblock halign-left valign-top">Expression</th> <th class="tableblock halign-left valign-top">Description</th> </tr> </thead> <tbody> <tr> <td class="tableblock halign-left valign-top"><p class="tableblock"><code>hasRole([role])</code></p></td> <td class="tableblock halign-left valign-top"><p class="tableblock">Returns <code>true</code> if the current principal has the specified role. This is a synonym for <code>hasAuthority([authority])</code></p></td> </tr> <tr> <td class="tableblock halign-left valign-top"><p class="tableblock"><code>hasAnyRole([role1,role2])</code></p></td> <td class="tableblock halign-left valign-top"><p class="tableblock">Returns <code>true</code> if the current principal has any of the supplied roles (given as a comma-separated list of strings) This is a synonym for <code>hasAnyAuthority([authority1,authority2])</code></p></td> </tr> <tr> <td class="tableblock halign-left valign-top"><p class="tableblock"><code>hasAuthority([authority])</code></p></td> <td class="tableblock halign-left valign-top"><p class="tableblock">Returns <code>true</code> if the current principal has the specified authority. This is a synonym for <code>hasRole([role])</code></p></td> </tr> <tr> <td class="tableblock halign-left valign-top"><p class="tableblock"><code>hasAnyAuthority([authority1,authority2])</code></p></td> <td class="tableblock halign-left valign-top"><p class="tableblock">Returns <code>true</code> if the current principal has any of the supplied roles (given as a comma-separated list of strings) <code>hasAnyRole([role1,role2])``hasAnyRole([role1,role2])</code></p></td> </tr> <tr> <td class="tableblock halign-left valign-top"><p class="tableblock"><code>principal</code></p></td> <td class="tableblock halign-left valign-top"><p class="tableblock">Allows direct access to the principal object representing the current user</p></td> </tr> <tr> <td class="tableblock halign-left valign-top"><p class="tableblock"><code>authentication</code></p></td> <td class="tableblock halign-left valign-top"><p class="tableblock">Allows direct access to the current <code>Authentication</code> object obtained from the <code>SecurityContext</code></p></td> </tr> <tr> <td class="tableblock halign-left valign-top"><p class="tableblock"><code>permitAll</code></p></td> <td class="tableblock halign-left valign-top"><p class="tableblock">Always evaluates to <code>true</code></p></td> </tr> <tr> <td class="tableblock halign-left valign-top"><p class="tableblock"><code>denyAll</code></p></td> <td class="tableblock halign-left valign-top"><p class="tableblock">Always evaluates to <code>false</code></p></td> </tr> <tr> <td class="tableblock halign-left valign-top"><p class="tableblock"><code>isAnonymous()</code></p></td> <td class="tableblock halign-left valign-top"><p class="tableblock">Returns <code>true</code> if the current principal is an anonymous user</p></td> </tr> <tr> <td class="tableblock halign-left valign-top"><p class="tableblock"><code>isRememberMe()</code></p></td> <td class="tableblock halign-left valign-top"><p class="tableblock">Returns <code>true</code> if the current principal is a remember-me user</p></td> </tr> <tr> <td class="tableblock halign-left valign-top"><p class="tableblock"><code>isAuthenticated()</code></p></td> <td class="tableblock halign-left valign-top"><p class="tableblock">Returns <code>true</code> if the user is not anonymous</p></td> </tr> <tr> <td class="tableblock halign-left valign-top"><p class="tableblock"><code>isFullyAuthenticated()</code></p></td> <td class="tableblock halign-left valign-top"><p class="tableblock">Returns <code>true</code> if the user is not an anonymous or a remember-me user</p></td> </tr> <tr> <td class="tableblock halign-left valign-top"><p class="tableblock"><code>hasPermission(Object target, Object permission)</code></p></td> <td class="tableblock halign-left valign-top"><p class="tableblock">Returns <code>true</code> if the user has access to the provided target for the given permission. For example, <code>hasPermission(domainObject, 'read')</code></p></td> </tr> <tr> <td class="tableblock halign-left valign-top"><p class="tableblock"><code>hasPermission(Object targetId, String targetType, Object permission)</code></p></td> <td class="tableblock halign-left valign-top"><p class="tableblock">Returns <code>true</code> if the user has access to the provided target for the given permission. For example, <code>hasPermission(1, 'com.example.domain.Message', 'read')</code></p></td> </tr> </tbody> </table> </div> </div> <div class="sect2"> <h3 id="el-access-web"><a class="anchor" href="#el-access-web"></a>3.2. Web Security Expressions</h3> <div class="paragraph"> <p>To use expressions to secure individual URLs, you would first need to set the <code>use-expressions</code> attribute in the <code><http></code> element to <code>true</code>. Spring Security will then expect the <code>access</code> attributes of the <code><intercept-url></code> elements to contain Spring EL expressions. The expressions should evaluate to a boolean, defining whether access should be allowed or not. For example:</p> </div> <div class="listingblock"> <div class="content"> <pre style="" class="prettyprint xml language-xml prettyprinted"><code><span class="pln"> </span><span class="tag"><http</span><span class="pln"> </span><span class="atn">use-expressions</span><span class="pun">=</span><span class="atv">"true"</span><span class="tag">></span><span class="pln"> </span><span class="tag"><intercept-url</span><span class="pln"> </span><span class="atn">pattern</span><span class="pun">=</span><span class="atv">"/admin*"</span><span class="pln"> </span><span class="atn">access</span><span class="pun">=</span><span class="atv">"hasRole('admin') and hasIpAddress('192.168.1.0/24')"</span><span class="tag">/></span><span class="pln"> ... </span><span class="tag"></http></span></code></pre> </div> </div> <div class="paragraph"> <p>Here we have defined that the "admin" area of an application (defined by the URL pattern) should only be available to users who have the granted authority "admin" and whose IP address matches a local subnet. We’ve already seen the built-in <code>hasRole</code> expression in the previous section. The expression <code>hasIpAddress</code> is an additional built-in expression which is specific to web security. It is defined by the <code>WebSecurityExpressionRoot</code> class, an instance of which is used as the expression root object when evaluation web-access expressions. This object also directly exposed the <code>HttpServletRequest</code> object under the name <code>request</code> so you can invoke the request directly in an expressio If expressions are being used, a <code>WebExpressionVoter</code> will be added to the <code>AccessDecisionManager</code> which is used by the namespace. So if you aren’t using the namespace and want to use expressions, you will have to add one of these to your configuration.</p> </div> </div> <div class="sect2"> <h3 id="method-security-expressions"><a class="anchor" href="#method-security-expressions"></a>3.3. Method Security Expressions</h3> <div class="paragraph"> <p>Method security is a bit more complicated than a simple allow or deny rule. Spring Security 3.0 introduced some new annotations in order to allow comprehensive support for the use of expressions.</p> </div> <div class="sect3"> <h4 id="el-pre-post-annotations"><a class="anchor" href="#el-pre-post-annotations"></a>3.3.1. @Pre and @Post Annotations</h4> <div class="paragraph"> <p>There are four annotations which support expression attributes to allow pre and post-invocation authorization checks and also to support filtering of submitted collection arguments or return values. They are <code>@PreAuthorize</code>, <code>@PreFilter</code>, <code>@PostAuthorize</code> and <code>@PostFilter</code>. Their use is enabled through the <code>global-method-security</code> namespace element:</p> </div> <div class="listingblock"> <div class="content"> <pre style="" class="prettyprint xml language-xml prettyprinted"><code><span class="tag"><global-method-security</span><span class="pln"> </span><span class="atn">pre-post-annotations</span><span class="pun">=</span><span class="atv">"enabled"</span><span class="tag">/></span></code></pre> </div> </div> <div class="sect4"> <h5 id="access-control-using-preauthorize-and-postauthorize"><a class="anchor" href="#access-control-using-preauthorize-and-postauthorize"></a>Access Control using @PreAuthorize and @PostAuthorize</h5> <div class="paragraph"> <p>The most obviously useful annotation is <code>@PreAuthorize</code> which decides whether a method can actually be invoked or not. For example (from the"Contacts" sample application)</p> </div> <div class="listingblock"> <div class="content"> <pre style="" class="prettyprint java language-java prettyprinted"><code><span class="lit">@PreAuthorize</span><span class="pun">(</span><span class="str">"hasRole('ROLE_USER')"</span><span class="pun">)</span><span class="pln"> </span><span class="kwd">public</span><span class="pln"> </span><span class="kwd">void</span><span class="pln"> create</span><span class="pun">(</span><span class="typ">Contact</span><span class="pln"> contact</span><span class="pun">);</span></code></pre> </div> </div> <div class="paragraph"> <p>which means that access will only be allowed for users with the role "ROLE_USER". Obviously the same thing could easily be achieved using a traditional configuration and a simple configuration attribute for the required role. But what about:</p> </div> <div class="listingblock"> <div class="content"> <pre style="" class="prettyprint java language-java prettyprinted"><code><span class="lit">@PreAuthorize</span><span class="pun">(</span><span class="str">"hasPermission(#contact, 'admin')"</span><span class="pun">)</span><span class="pln"> </span><span class="kwd">public</span><span class="pln"> </span><span class="kwd">void</span><span class="pln"> deletePermission</span><span class="pun">(</span><span class="typ">Contact</span><span class="pln"> contact</span><span class="pun">,</span><span class="pln"> </span><span class="typ">Sid</span><span class="pln"> recipient</span><span class="pun">,</span><span class="pln"> </span><span class="typ">Permission</span><span class="pln"> permission</span><span class="pun">);</span></code></pre> </div> </div> <div class="paragraph"> <p>Here we’re actually using a method argument as part of the expression to decide whether the current user has the "admin"permission for the given contact. The built-in <code>hasPermission()</code> expression is linked into the Spring Security ACL module through the application context, as we’ll<a href="#el-permission-evaluator">see below</a>. You can access any of the method arguments by name as expression variables.</p> </div> <div class="paragraph"> <p>There are a number of ways in which Spring Security can resolve the method arguments. Spring Security uses <code>DefaultSecurityParameterNameDiscoverer</code> to discover the parameter names. By default, the following options are tried for a method as a whole.</p> </div> <div class="ulist"> <ul> <li> <p>If Spring Security’s <code>@P</code> annotation is present on a single argument to the method, the value will be used. This is useful for interfaces compiled with a JDK prior to JDK 8 which do not contain any information about the parameter names. For example:</p> <div class="listingblock"> <div class="content"> <pre style="" class="prettyprint java language-java prettyprinted"><code><span class="kwd">import</span><span class="pln"> org</span><span class="pun">.</span><span class="pln">springframework</span><span class="pun">.</span><span class="pln">security</span><span class="pun">.</span><span class="pln">access</span><span class="pun">.</span><span class="pln">method</span><span class="pun">.</span><span class="pln">P</span><span class="pun">;</span><span class="pln"> </span><span class="pun">...</span><span class="pln"> </span><span class="lit">@PreAuthorize</span><span class="pun">(</span><span class="str">"#c.name == authentication.name"</span><span class="pun">)</span><span class="pln"> </span><span class="kwd">public</span><span class="pln"> </span><span class="kwd">void</span><span class="pln"> doSomething</span><span class="pun">(</span><span class="lit">@P</span><span class="pun">(</span><span class="str">"c"</span><span class="pun">)</span><span class="pln"> </span><span class="typ">Contact</span><span class="pln"> contact</span><span class="pun">);</span></code></pre> </div> </div> <div class="paragraph"> <p>Behind the scenes this use implemented using <code>AnnotationParameterNameDiscoverer</code> which can be customized to support the value attribute of any specified annotation.</p> </div> </li> <li> <p>If Spring Data’s <code>@Param</code> annotation is present on at least one parameter for the method, the value will be used. This is useful for interfaces compiled with a JDK prior to JDK 8 which do not contain any information about the parameter names. For example:</p> <div class="listingblock"> <div class="content"> <pre style="" class="prettyprint java language-java prettyprinted"><code><span class="kwd">import</span><span class="pln"> org</span><span class="pun">.</span><span class="pln">springframework</span><span class="pun">.</span><span class="pln">data</span><span class="pun">.</span><span class="pln">repository</span><span class="pun">.</span><span class="pln">query</span><span class="pun">.</span><span class="typ">Param</span><span class="pun">;</span><span class="pln"> </span><span class="pun">...</span><span class="pln"> </span><span class="lit">@PreAuthorize</span><span class="pun">(</span><span class="str">"#n == authentication.name"</span><span class="pun">)</span><span class="pln"> </span><span class="typ">Contact</span><span class="pln"> findContactByName</span><span class="pun">(</span><span class="lit">@Param</span><span class="pun">(</span><span class="str">"n"</span><span class="pun">)</span><span class="pln"> </span><span class="typ">String</span><span class="pln"> name</span><span class="pun">);</span></code></pre> </div> </div> <div class="paragraph"> <p>Behind the scenes this use implemented using <code>AnnotationParameterNameDiscoverer</code> which can be customized to support the value attribute of any specified annotation.</p> </div> </li> <li> <p>If JDK 8 was used to compile the source with the -parameters argument and Spring 4+ is being used, then the standard JDK reflection API is used to discover the parameter names. This works on both classes and interfaces.</p> </li> <li> <p>Last, if the code was compiled with the debug symbols, the parameter names will be discovered using the debug symbols. This will not work for interfaces since they do not have debug information about the parameter names. For interfaces, annotations or the JDK 8 approach must be used.</p> </li> </ul> </div> <div class="openblock"><div class="title"><a id="el-pre-post-annotations-spel"></a></div> <div class="content"> <div class="paragraph"> <p>Any Spring-EL functionality is available within the expression, so you can also access properties on the arguments. For example, if you wanted a particular method to only allow access to a user whose username matched that of the contact, you could write</p> </div> </div> </div> <div class="listingblock"> <div class="content"> <pre style="" class="prettyprint java language-java prettyprinted"><code><span class="lit">@PreAuthorize</span><span class="pun">(</span><span class="str">"#contact.name == authentication.name"</span><span class="pun">)</span><span class="pln"> </span><span class="kwd">public</span><span class="pln"> </span><span class="kwd">void</span><span class="pln"> doSomething</span><span class="pun">(</span><span class="typ">Contact</span><span class="pln"> contact</span><span class="pun">);</span></code></pre> </div> </div> <div class="paragraph"> <p>Here we are accessing another built-in expression, <code>authentication</code>, which is the <code>Authentication</code> stored in the security context. You can also access its "principal" property directly, using the expression <code>principal</code>. The value will often be a <code>UserDetails</code> instance, so you might use an expression like <code>principal.username</code> or <code>principal.enabled</code>.</p> </div> <div class="openblock"><div class="title"><a id="el-pre-post-annotations-post"></a></div> <div class="content"> <div class="paragraph"> <p>Less commonly, you may wish to perform an access-control check after the method has been invoked. This can be achieved using the <code>@PostAuthorize</code> annotation. To access the return value from a method, use the built-in name <code>returnObject</code> in the expression.</p> </div> </div> </div> </div> <div class="sect4"> <h5 id="filtering-using-prefilter-and-postfilter"><a class="anchor" href="#filtering-using-prefilter-and-postfilter"></a>Filtering using @PreFilter and @PostFilter</h5> <div class="paragraph"> <p>As you may already be aware, Spring Security supports filtering of collections and arrays and this can now be achieved using expressions. This is most commonly performed on the return value of a method. For example:</p> </div> <div class="listingblock"> <div class="content"> <pre style="" class="prettyprint java language-java prettyprinted"><code><span class="lit">@PreAuthorize</span><span class="pun">(</span><span class="str">"hasRole('ROLE_USER')"</span><span class="pun">)</span><span class="pln"> </span><span class="lit">@PostFilter</span><span class="pun">(</span><span class="str">"hasPermission(filterObject, 'read') or hasPermission(filterObject, 'admin')"</span><span class="pun">)</span><span class="pln"> </span><span class="kwd">public</span><span class="pln"> </span><span class="typ">List</span><span class="pun"><</span><span class="typ">Contact</span><span class="pun">></span><span class="pln"> getAll</span><span class="pun">();</span></code></pre> </div> </div> <div class="paragraph"> <p>When using the <code>@PostFilter</code> annotation, Spring Security iterates through the returned collection and removes any elements for which the supplied expression is false. The name <code>filterObject</code> refers to the current object in the collection. You can also filter before the method call, using <code>@PreFilter</code>, though this is a less common requirement. The syntax is just the same, but if there is more than one argument which is a collection type then you have to select one by name using the <code>filterTarget</code> property of this annotation.</p> </div> <div class="paragraph"> <p>Note that filtering is obviously not a substitute for tuning your data retrieval queries. If you are filtering large collections and removing many of the entries then this is likely to be inefficient.</p> </div> </div> </div> <div class="sect3"> <h4 id="el-method-built-in"><a class="anchor" href="#el-method-built-in"></a>3.3.2. Built-In Expressions</h4> <div class="paragraph"> <p>There are some built-in expressions which are specific to method security, which we have already seen in use above. The <code>filterTarget</code> and <code>returnValue</code> values are simple enough, but the use of the <code>hasPermission()</code> expression warrants a closer look.</p> </div> <div class="sect4"> <h5 id="el-permission-evaluator"><a class="anchor" href="#el-permission-evaluator"></a>The PermissionEvaluator interface</h5> <div class="paragraph"> <p><code>hasPermission()</code> expressions are delegated to an instance of <code>PermissionEvaluator</code>. It is intended to bridge between the expression system and Spring Security’s ACL system, allowing you to specify authorization constraints on domain objects, based on abstract permissions. It has no explicit dependencies on the ACL module, so you could swap that out for an alternative implementation if required. The interface has two methods:</p> </div> <div class="listingblock"> <div class="content"> <pre style="" class="prettyprint java language-java prettyprinted"><code><span class="kwd">boolean</span><span class="pln"> hasPermission</span><span class="pun">(</span><span class="typ">Authentication</span><span class="pln"> authentication</span><span class="pun">,</span><span class="pln"> </span><span class="typ">Object</span><span class="pln"> targetDomainObject</span><span class="pun">,</span><span class="pln"> </span><span class="typ">Object</span><span class="pln"> permission</span><span class="pun">);</span><span class="pln"> </span><span class="kwd">boolean</span><span class="pln"> hasPermission</span><span class="pun">(</span><span class="typ">Authentication</span><span class="pln"> authentication</span><span class="pun">,</span><span class="pln"> </span><span class="typ">Serializable</span><span class="pln"> targetId</span><span class="pun">,</span><span class="pln"> </span><span class="typ">String</span><span class="pln"> targetType</span><span class="pun">,</span><span class="pln"> </span><span class="typ">Object</span><span class="pln"> permission</span><span class="pun">);</span></code></pre> </div> </div> <div class="paragraph"> <p>which map directly to the available versions of the expression, with the exception that the first argument (the <code>Authentication</code> object) is not supplied. The first is used in situations where the domain object, to which access is being controlled, is already loaded. Then expression will return true if the current user has the given permission for that object. The second version is used in cases where the object is not loaded, but its identifier is known. An abstract "type" specifier for the domain object is also required, allowing the correct ACL permissions to be loaded. This has traditionally been the Java class of the object, but does not have to be as long as it is consistent with how the permissions are loaded.</p> </div> <div class="paragraph"> <p>To use <code>hasPermission()</code> expressions, you have to explicitly configure a <code>PermissionEvaluator</code> in your application context. This would look something like this:</p> </div> <div class="listingblock"> <div class="content"> <pre style="" class="prettyprint xml language-xml prettyprinted"><code><span class="tag"><security:global-method-security</span><span class="pln"> </span><span class="atn">pre-post-annotations</span><span class="pun">=</span><span class="atv">"enabled"</span><span class="tag">></span><span class="pln"> </span><span class="tag"><security:expression-handler</span><span class="pln"> </span><span class="atn">ref</span><span class="pun">=</span><span class="atv">"expressionHandler"</span><span class="tag">/></span><span class="pln"> </span><span class="tag"></security:global-method-security></span><span class="pln"> </span><span class="tag"><bean</span><span class="pln"> </span><span class="atn">id</span><span class="pun">=</span><span class="atv">"expressionHandler"</span><span class="pln"> </span><span class="atn">class</span><span class="pun">=</span><span class="pln"> </span><span class="atv">"org.springframework.security.access.expression.method.DefaultMethodSecurityExpressionHandler"</span><span class="tag">></span><span class="pln"> </span><span class="tag"><property</span><span class="pln"> </span><span class="atn">name</span><span class="pun">=</span><span class="atv">"permissionEvaluator"</span><span class="pln"> </span><span class="atn">ref</span><span class="pun">=</span><span class="atv">"myPermissionEvaluator"</span><span class="tag">/></span><span class="pln"> </span><span class="tag"></bean></span></code></pre> </div> </div> <div class="paragraph"> <p>Where <code>myPermissionEvaluator</code> is the bean which implements <code>PermissionEvaluator</code>. Usually this will be the implementation from the ACL module which is called`AclPermissionEvaluator`. See the "Contacts" sample application configuration for more details.</p> </div> </div> </div> </div> </div> </div> <h1 id="advanced-topics" class="sect0"><a class="anchor" href="#advanced-topics"></a>Additional Topics</h1> <div class="paragraph"> <p>In this part we cover features which require a knowledge of previous chapters as well as some of the more advanced and less-commonly used features of the framework.</p> </div> <div class="sect1"> <h2 id="domain-acls"><a class="anchor" href="#domain-acls"></a>1. Domain Object Security (ACLs)</h2> <div class="sectionbody"> <div class="sect2"> <h3 id="domain-acls-overview"><a class="anchor" href="#domain-acls-overview"></a>1.1. Overview</h3> <div class="paragraph"> <p>Complex applications often will find the need to define access permissions not simply at a web request or method invocation level. Instead, security decisions need to comprise both who (<code>Authentication</code>), where (<code>MethodInvocation</code>) and what (<code>SomeDomainObject</code>). In other words, authorization decisions also need to consider the actual domain object instance subject of a method invocation.</p> </div> <div class="paragraph"> <p>Imagine you’re designing an application for a pet clinic. There will be two main groups of users of your Spring-based application: staff of the pet clinic, as well as the pet clinic’s customers. The staff will have access to all of the data, whilst your customers will only be able to see their own customer records. To make it a little more interesting, your customers can allow other users to see their customer records, such as their "puppy preschool" mentor or president of their local "Pony Club". Using Spring Security as the foundation, you have several approaches that can be used:</p> </div> <div class="ulist"> <ul> <li> <p>Write your business methods to enforce the security. You could consult a collection within the <code>Customer</code> domain object instance to determine which users have access. By using the <code>SecurityContextHolder.getContext().getAuthentication()</code>, you’ll be able to access the <code>Authentication</code> object.</p> </li> <li> <p>Write an <code>AccessDecisionVoter</code> to enforce the security from the <code>GrantedAuthority[]</code> s stored in the <code>Authentication</code> object. This would mean your <code>AuthenticationManager</code> would need to populate the <code>Authentication</code> with custom <code>GrantedAuthority</code>[]s representing each of the <code>Customer</code> domain object instances the principal has access to.</p> </li> <li> <p>Write an <code>AccessDecisionVoter</code> to enforce the security and open the target <code>Customer</code> domain object directly. This would mean your voter needs access to a DAO that allows it to retrieve the <code>Customer</code> object. It would then access the <code>Customer</code> object’s collection of approved users and make the appropriate decision.</p> </li> </ul> </div> <div class="paragraph"> <p>Each one of these approaches is perfectly legitimate. However, the first couples your authorization checking to your business code. The main problems with this include the enhanced difficulty of unit testing and the fact it would be more difficult to reuse the <code>Customer</code> authorization logic elsewhere. Obtaining the <code>GrantedAuthority[]</code> s from the <code>Authentication</code> object is also fine, but will not scale to large numbers of <code>Customer</code> s. If a user might be able to access 5,000 <code>Customer</code> s (unlikely in this case, but imagine if it were a popular vet for a large Pony Club!) the amount of memory consumed and time required to construct the <code>Authentication</code> object would be undesirable. The final method, opening the <code>Customer</code> directly from external code, is probably the best of the three. It achieves separation of concerns, and doesn’t misuse memory or CPU cycles, but it is still inefficient in that both the <code>AccessDecisionVoter</code> and the eventual business method itself will perform a call to the DAO responsible for retrieving the <code>Customer</code> object. Two accesses per method invocation is clearly undesirable. In addition, with every approach listed you’ll need to write your own access control list (ACL) persistence and business logic from scratch.</p> </div> <div class="paragraph"> <p>Fortunately, there is another alternative, which we’ll talk about below.</p> </div> </div> <div class="sect2"> <h3 id="domain-acls-key-concepts"><a class="anchor" href="#domain-acls-key-concepts"></a>1.2. Key Concepts</h3> <div class="paragraph"> <p>Spring Security’s ACL services are shipped in the <code>spring-security-acl-xxx.jar</code>. You will need to add this JAR to your classpath to use Spring Security’s domain object instance security capabilities.</p> </div> <div class="paragraph"> <p>Spring Security’s domain object instance security capabilities centre on the concept of an access control list (ACL). Every domain object instance in your system has its own ACL, and the ACL records details of who can and can’t work with that domain object. With this in mind, Spring Security delivers three main ACL-related capabilities to your application:</p> </div> <div class="ulist"> <ul> <li> <p>A way of efficiently retrieving ACL entries for all of your domain objects (and modifying those ACLs)</p> </li> <li> <p>A way of ensuring a given principal is permitted to work with your objects, before methods are called</p> </li> <li> <p>A way of ensuring a given principal is permitted to work with your objects (or something they return), after methods are called</p> </li> </ul> </div> <div class="paragraph"> <p>As indicated by the first bullet point, one of the main capabilities of the Spring Security ACL module is providing a high-performance way of retrieving ACLs. This ACL repository capability is extremely important, because every domain object instance in your system might have several access control entries, and each ACL might inherit from other ACLs in a tree-like structure (this is supported out-of-the-box by Spring Security, and is very commonly used). Spring Security’s ACL capability has been carefully designed to provide high performance retrieval of ACLs, together with pluggable caching, deadlock-minimizing database updates, independence from ORM frameworks (we use JDBC directly), proper encapsulation, and transparent database updating.</p> </div> <div class="paragraph"> <p>Given databases are central to the operation of the ACL module, let’s explore the four main tables used by default in the implementation. The tables are presented below in order of size in a typical Spring Security ACL deployment, with the table with the most rows listed last:</p> </div> <div class="ulist"> <ul> <li> <p>ACL_SID allows us to uniquely identify any principal or authority in the system ("SID" stands for "security identity"). The only columns are the ID, a textual representation of the SID, and a flag to indicate whether the textual representation refers to a principal name or a <code>GrantedAuthority</code>. Thus, there is a single row for each unique principal or <code>GrantedAuthority</code>. When used in the context of receiving a permission, a SID is generally called a "recipient".</p> </li> <li> <p>ACL_CLASS allows us to uniquely identify any domain object class in the system. The only columns are the ID and the Java class name. Thus, there is a single row for each unique Class we wish to store ACL permissions for.</p> </li> <li> <p>ACL_OBJECT_IDENTITY stores information for each unique domain object instance in the system. Columns include the ID, a foreign key to the ACL_CLASS table, a unique identifier so we know which ACL_CLASS instance we’re providing information for, the parent, a foreign key to the ACL_SID table to represent the owner of the domain object instance, and whether we allow ACL entries to inherit from any parent ACL. We have a single row for every domain object instance we’re storing ACL permissions for.</p> </li> <li> <p>Finally, ACL_ENTRY stores the individual permissions assigned to each recipient. Columns include a foreign key to the ACL_OBJECT_IDENTITY, the recipient (ie a foreign key to ACL_SID), whether we’ll be auditing or not, and the integer bit mask that represents the actual permission being granted or denied. We have a single row for every recipient that receives a permission to work with a domain object.</p> </li> </ul> </div> <div class="paragraph"> <p>As mentioned in the last paragraph, the ACL system uses integer bit masking. Don’t worry, you need not be aware of the finer points of bit shifting to use the ACL system, but suffice to say that we have 32 bits we can switch on or off. Each of these bits represents a permission, and by default the permissions are read (bit 0), write (bit 1), create (bit 2), delete (bit 3) and administer (bit 4). It’s easy to implement your own <code>Permission</code> instance if you wish to use other permissions, and the remainder of the ACL framework will operate without knowledge of your extensions.</p> </div> <div class="paragraph"> <p>It is important to understand that the number of domain objects in your system has absolutely no bearing on the fact we’ve chosen to use integer bit masking. Whilst you have 32 bits available for permissions, you could have billions of domain object instances (which will mean billions of rows in ACL_OBJECT_IDENTITY and quite probably ACL_ENTRY). We make this point because we’ve found sometimes people mistakenly believe they need a bit for each potential domain object, which is not the case.</p> </div> <div class="paragraph"> <p>Now that we’ve provided a basic overview of what the ACL system does, and what it looks like at a table structure, let’s explore the key interfaces. The key interfaces are:</p> </div> <div class="ulist"> <ul> <li> <p><code>Acl</code>: Every domain object has one and only one <code>Acl</code> object, which internally holds the <code>AccessControlEntry</code> s as well as knows the owner of the <code>Acl</code>. An Acl does not refer directly to the domain object, but instead to an <code>ObjectIdentity</code>. The <code>Acl</code> is stored in the ACL_OBJECT_IDENTITY table.</p> </li> <li> <p><code>AccessControlEntry</code>: An <code>Acl</code> holds multiple <code>AccessControlEntry</code> s, which are often abbreviated as ACEs in the framework. Each ACE refers to a specific tuple of`Permission`, <code>Sid</code> and <code>Acl</code>. An ACE can also be granting or non-granting and contain audit settings. The ACE is stored in the ACL_ENTRY table.</p> </li> <li> <p><code>Permission</code>: A permission represents a particular immutable bit mask, and offers convenience functions for bit masking and outputting information. The basic permissions presented above (bits 0 through 4) are contained in the <code>BasePermission</code> class.</p> </li> <li> <p><code>Sid</code>: The ACL module needs to refer to principals and <code>GrantedAuthority[]</code> s. A level of indirection is provided by the <code>Sid</code> interface, which is an abbreviation of "security identity". Common classes include <code>PrincipalSid</code> (to represent the principal inside an <code>Authentication</code> object) and <code>GrantedAuthoritySid</code>. The security identity information is stored in the ACL_SID table.</p> </li> <li> <p><code>ObjectIdentity</code>: Each domain object is represented internally within the ACL module by an <code>ObjectIdentity</code>. The default implementation is called <code>ObjectIdentityImpl</code>.</p> </li> <li> <p><code>AclService</code>: Retrieves the <code>Acl</code> applicable for a given <code>ObjectIdentity</code>. In the included implementation (<code>JdbcAclService</code>), retrieval operations are delegated to a <code>LookupStrategy</code>. The <code>LookupStrategy</code> provides a highly optimized strategy for retrieving ACL information, using batched retrievals <code>(BasicLookupStrategy</code>) and supporting custom implementations that leverage materialized views, hierarchical queries and similar performance-centric, non-ANSI SQL capabilities.</p> </li> <li> <p><code>MutableAclService</code>: Allows a modified <code>Acl</code> to be presented for persistence. It is not essential to use this interface if you do not wish.</p> </li> </ul> </div> <div class="paragraph"> <p>Please note that our out-of-the-box AclService and related database classes all use ANSI SQL. This should therefore work with all major databases. At the time of writing, the system had been successfully tested using Hypersonic SQL, PostgreSQL, Microsoft SQL Server and Oracle.</p> </div> <div class="paragraph"> <p>Two samples ship with Spring Security that demonstrate the ACL module. The first is the Contacts Sample, and the other is the Document Management System (DMS) Sample. We suggest taking a look over these for examples.</p> </div> </div> <div class="sect2"> <h3 id="domain-acls-getting-started"><a class="anchor" href="#domain-acls-getting-started"></a>1.3. Getting Started</h3> <div class="paragraph"> <p>To get starting using Spring Security’s ACL capability, you will need to store your ACL information somewhere. This necessitates the instantiation of a <code>DataSource</code> using Spring. The <code>DataSource</code> is then injected into a <code>JdbcMutableAclService</code> and <code>BasicLookupStrategy</code> instance. The latter provides high-performance ACL retrieval capabilities, and the former provides mutator capabilities. Refer to one of the samples that ship with Spring Security for an example configuration. You’ll also need to populate the database with the four ACL-specific tables listed in the last section (refer to the ACL samples for the appropriate SQL statements).</p> </div> <div class="paragraph"> <p>Once you’ve created the required schema and instantiated <code>JdbcMutableAclService</code>, you’ll next need to ensure your domain model supports interoperability with the Spring Security ACL package. Hopefully <code>ObjectIdentityImpl</code> will prove sufficient, as it provides a large number of ways in which it can be used. Most people will have domain objects that contain a <code>public Serializable getId()</code> method. If the return type is long, or compatible with long (eg an int), you will find you need not give further consideration to <code>ObjectIdentity</code> issues. Many parts of the ACL module rely on long identifiers. If you’re not using long (or an int, byte etc), there is a very good chance you’ll need to reimplement a number of classes. We do not intend to support non-long identifiers in Spring Security’s ACL module, as longs are already compatible with all database sequences, the most common identifier data type, and are of sufficient length to accommodate all common usage scenarios.</p> </div> <div class="paragraph"> <p>The following fragment of code shows how to create an <code>Acl</code>, or modify an existing`Acl`:</p> </div> <div class="listingblock"> <div class="content"> <pre style="" class="prettyprint java language-java prettyprinted"><code><span class="com">// Prepare the information we'd like in our access control entry (ACE)</span><span class="pln"> </span><span class="typ">ObjectIdentity</span><span class="pln"> oi </span><span class="pun">=</span><span class="pln"> </span><span class="kwd">new</span><span class="pln"> </span><span class="typ">ObjectIdentityImpl</span><span class="pun">(</span><span class="typ">Foo</span><span class="pun">.</span><span class="kwd">class</span><span class="pun">,</span><span class="pln"> </span><span class="kwd">new</span><span class="pln"> </span><span class="typ">Long</span><span class="pun">(</span><span class="lit">44</span><span class="pun">));</span><span class="pln"> </span><span class="typ">Sid</span><span class="pln"> sid </span><span class="pun">=</span><span class="pln"> </span><span class="kwd">new</span><span class="pln"> </span><span class="typ">PrincipalSid</span><span class="pun">(</span><span class="str">"Samantha"</span><span class="pun">);</span><span class="pln"> </span><span class="typ">Permission</span><span class="pln"> p </span><span class="pun">=</span><span class="pln"> </span><span class="typ">BasePermission</span><span class="pun">.</span><span class="pln">ADMINISTRATION</span><span class="pun">;</span><span class="pln"> </span><span class="com">// Create or update the relevant ACL</span><span class="pln"> </span><span class="typ">MutableAcl</span><span class="pln"> acl </span><span class="pun">=</span><span class="pln"> </span><span class="kwd">null</span><span class="pun">;</span><span class="pln"> </span><span class="kwd">try</span><span class="pln"> </span><span class="pun">{</span><span class="pln"> acl </span><span class="pun">=</span><span class="pln"> </span><span class="pun">(</span><span class="typ">MutableAcl</span><span class="pun">)</span><span class="pln"> aclService</span><span class="pun">.</span><span class="pln">readAclById</span><span class="pun">(</span><span class="pln">oi</span><span class="pun">);</span><span class="pln"> </span><span class="pun">}</span><span class="pln"> </span><span class="kwd">catch</span><span class="pln"> </span><span class="pun">(</span><span class="typ">NotFoundException</span><span class="pln"> nfe</span><span class="pun">)</span><span class="pln"> </span><span class="pun">{</span><span class="pln"> acl </span><span class="pun">=</span><span class="pln"> aclService</span><span class="pun">.</span><span class="pln">createAcl</span><span class="pun">(</span><span class="pln">oi</span><span class="pun">);</span><span class="pln"> </span><span class="pun">}</span><span class="pln"> </span><span class="com">// Now grant some permissions via an access control entry (ACE)</span><span class="pln"> acl</span><span class="pun">.</span><span class="pln">insertAce</span><span class="pun">(</span><span class="pln">acl</span><span class="pun">.</span><span class="pln">getEntries</span><span class="pun">().</span><span class="pln">length</span><span class="pun">,</span><span class="pln"> p</span><span class="pun">,</span><span class="pln"> sid</span><span class="pun">,</span><span class="pln"> </span><span class="kwd">true</span><span class="pun">);</span><span class="pln"> aclService</span><span class="pun">.</span><span class="pln">updateAcl</span><span class="pun">(</span><span class="pln">acl</span><span class="pun">);</span></code></pre> </div> </div> <div class="paragraph"> <p>In the example above, we’re retrieving the ACL associated with the "Foo" domain object with identifier number 44. We’re then adding an ACE so that a principal named "Samantha" can "administer" the object. The code fragment is relatively self-explanatory, except the insertAce method. The first argument to the insertAce method is determining at what position in the Acl the new entry will be inserted. In the example above, we’re just putting the new ACE at the end of the existing ACEs. The final argument is a boolean indicating whether the ACE is granting or denying. Most of the time it will be granting (true), but if it is denying (false), the permissions are effectively being blocked.</p> </div> <div class="paragraph"> <p>Spring Security does not provide any special integration to automatically create, update or delete ACLs as part of your DAO or repository operations. Instead, you will need to write code like shown above for your individual domain objects. It’s worth considering using AOP on your services layer to automatically integrate the ACL information with your services layer operations. We’ve found this quite an effective approach in the past.</p> </div> <div class="paragraph"> <p>Once you’ve used the above techniques to store some ACL information in the database, the next step is to actually use the ACL information as part of authorization decision logic. You have a number of choices here. You could write your own <code>AccessDecisionVoter</code> or <code>AfterInvocationProvider</code> that respectively fires before or after a method invocation. Such classes would use <code>AclService</code> to retrieve the relevant ACL and then call <code>Acl.isGranted(Permission[] permission, Sid[] sids, boolean administrativeMode)</code> to decide whether permission is granted or denied. Alternately, you could use our <code>AclEntryVoter</code>, <code>AclEntryAfterInvocationProvider</code> or <code>AclEntryAfterInvocationCollectionFilteringProvider</code> classes. All of these classes provide a declarative-based approach to evaluating ACL information at runtime, freeing you from needing to write any code. Please refer to the sample applications to learn how to use these classes.</p> </div> </div> </div> </div> <div class="sect1"> <h2 id="preauth"><a class="anchor" href="#preauth"></a>2. Pre-Authentication Scenarios</h2> <div class="sectionbody"> <div class="paragraph"> <p>There are situations where you want to use Spring Security for authorization, but the user has already been reliably authenticated by some external system prior to accessing the application. We refer to these situations as "pre-authenticated" scenarios. Examples include X.509, Siteminder and authentication by the Java EE container in which the application is running. When using pre-authentication, Spring Security has to</p> </div> <div class="ulist"> <ul> <li> <p>Identify the user making the request.</p> </li> <li> <p>Obtain the authorities for the user.</p> </li> </ul> </div> <div class="paragraph"> <p>The details will depend on the external authentication mechanism. A user might be identified by their certificate information in the case of X.509, or by an HTTP request header in the case of Siteminder. If relying on container authentication, the user will be identified by calling the <code>getUserPrincipal()</code> method on the incoming HTTP request. In some cases, the external mechanism may supply role/authority information for the user but in others the authorities must be obtained from a separate source, such as a <code>UserDetailsService</code>.</p> </div> <div class="sect2"> <h3 id="pre-authentication-framework-classes"><a class="anchor" href="#pre-authentication-framework-classes"></a>2.1. Pre-Authentication Framework Classes</h3> <div class="paragraph"> <p>Because most pre-authentication mechanisms follow the same pattern, Spring Security has a set of classes which provide an internal framework for implementing pre-authenticated authentication providers. This removes duplication and allows new implementations to be added in a structured fashion, without having to write everything from scratch. You don’t need to know about these classes if you want to use something like <a href="#x509">X.509 authentication</a>, as it already has a namespace configuration option which is simpler to use and get started with. If you need to use explicit bean configuration or are planning on writing your own implementation then an understanding of how the provided implementations work will be useful. You will find classes under the <code>org.springframework.security.web.authentication.preauth</code>. We just provide an outline here so you should consult the Javadoc and source where appropriate.</p> </div> <div class="sect3"> <h4 id="abstractpreauthenticatedprocessingfilter"><a class="anchor" href="#abstractpreauthenticatedprocessingfilter"></a>2.1.1. AbstractPreAuthenticatedProcessingFilter</h4> <div class="paragraph"> <p>This class will check the current contents of the security context and, if empty, it will attempt to extract user information from the HTTP request and submit it to the <code>AuthenticationManager</code>. Subclasses override the following methods to obtain this information:</p> </div> <div class="listingblock"> <div class="content"> <pre style="" class="prettyprint java language-java prettyprinted"><code><span class="kwd">protected</span><span class="pln"> </span><span class="kwd">abstract</span><span class="pln"> </span><span class="typ">Object</span><span class="pln"> getPreAuthenticatedPrincipal</span><span class="pun">(</span><span class="typ">HttpServletRequest</span><span class="pln"> request</span><span class="pun">);</span><span class="pln"> </span><span class="kwd">protected</span><span class="pln"> </span><span class="kwd">abstract</span><span class="pln"> </span><span class="typ">Object</span><span class="pln"> getPreAuthenticatedCredentials</span><span class="pun">(</span><span class="typ">HttpServletRequest</span><span class="pln"> request</span><span class="pun">);</span></code></pre> </div> </div> <div class="paragraph"> <p>After calling these, the filter will create a <code>PreAuthenticatedAuthenticationToken</code> containing the returned data and submit it for authentication. By "authentication" here, we really just mean further processing to perhaps load the user’s authorities, but the standard Spring Security authentication architecture is followed.</p> </div> <div class="paragraph"> <p>Like other Spring Security authentication filters, the pre-authentication filter has an <code>authenticationDetailsSource</code> property which by default will create a <code>WebAuthenticationDetails</code> object to store additional information such as the session-identifier and originating IP address in the <code>details</code> property of the <code>Authentication</code> object. In cases where user role information can be obtained from the pre-authentication mechanism, the data is also stored in this property, with the details implementing the <code>GrantedAuthoritiesContainer</code> interface. This enables the authentication provider to read the authorities which were externally allocated to the user. We’ll look at a concrete example next.</p> </div> <div class="sect4"> <h5 id="j2ee-preauth-details"><a class="anchor" href="#j2ee-preauth-details"></a>J2eeBasedPreAuthenticatedWebAuthenticationDetailsSource</h5> <div class="paragraph"> <p>If the filter is configured with an <code>authenticationDetailsSource</code> which is an instance of this class, the authority information is obtained by calling the <code>isUserInRole(String role)</code> method for each of a pre-determined set of "mappable roles". The class gets these from a configured <code>MappableAttributesRetriever</code>. Possible implementations include hard-coding a list in the application context and reading the role information from the <code><security-role></code> information in a <code>web.xml</code> file. The pre-authentication sample application uses the latter approach.</p> </div> <div class="paragraph"> <p>There is an additional stage where the roles (or attributes) are mapped to Spring Security <code>GrantedAuthority</code> objects using a configured <code>Attributes2GrantedAuthoritiesMapper</code>. The default will just add the usual <code>ROLE_</code> prefix to the names, but it gives you full control over the behaviour.</p> </div> </div> </div> <div class="sect3"> <h4 id="preauthenticatedauthenticationprovider"><a class="anchor" href="#preauthenticatedauthenticationprovider"></a>2.1.2. PreAuthenticatedAuthenticationProvider</h4> <div class="paragraph"> <p>The pre-authenticated provider has little more to do than load the <code>UserDetails</code> object for the user. It does this by delegating to a <code>AuthenticationUserDetailsService</code>. The latter is similar to the standard <code>UserDetailsService</code> but takes an <code>Authentication</code> object rather than just user name:</p> </div> <div class="listingblock"> <div class="content"> <pre style="" class="prettyprint java language-java prettyprinted"><code><span class="kwd">public</span><span class="pln"> </span><span class="kwd">interface</span><span class="pln"> </span><span class="typ">AuthenticationUserDetailsService</span><span class="pln"> </span><span class="pun">{</span><span class="pln"> </span><span class="typ">UserDetails</span><span class="pln"> loadUserDetails</span><span class="pun">(</span><span class="typ">Authentication</span><span class="pln"> token</span><span class="pun">)</span><span class="pln"> </span><span class="kwd">throws</span><span class="pln"> </span><span class="typ">UsernameNotFoundException</span><span class="pun">;</span><span class="pln"> </span><span class="pun">}</span></code></pre> </div> </div> <div class="paragraph"> <p>This interface may have also other uses but with pre-authentication it allows access to the authorities which were packaged in the <code>Authentication</code> object, as we saw in the previous section. the <code>PreAuthenticatedGrantedAuthoritiesUserDetailsService</code> class does this. Alternatively, it may delegate to a standard <code>UserDetailsService</code> via the <code>UserDetailsByNameServiceWrapper</code> implementation.</p> </div> </div> <div class="sect3"> <h4 id="http403forbiddenentrypoint"><a class="anchor" href="#http403forbiddenentrypoint"></a>2.1.3. Http403ForbiddenEntryPoint</h4> <div class="paragraph"> <p>The <code>AuthenticationEntryPoint</code> was discussed in the <a href="#tech-intro-auth-entry-point">technical overview</a> chapter. Normally it is responsible for kick-starting the authentication process for an unauthenticated user (when they try to access a protected resource), but in the pre-authenticated case this doesn’t apply. You would only configure the <code>ExceptionTranslationFilter</code> with an instance of this class if you aren’t using pre-authentication in combination with other authentication mechanisms. It will be called if the user is rejected by the <code>AbstractPreAuthenticatedProcessingFilter</code> resulting in a null authentication. It always returns a <code>403</code>-forbidden response code if called.</p> </div> </div> </div> <div class="sect2"> <h3 id="concrete-implementations"><a class="anchor" href="#concrete-implementations"></a>2.2. Concrete Implementations</h3> <div class="paragraph"> <p>X.509 authentication is covered in its <a href="#x509">own chapter</a>. Here we’ll look at some classes which provide support for other pre-authenticated scenarios.</p> </div> <div class="sect3"> <h4 id="request-header-authentication-siteminder"><a class="anchor" href="#request-header-authentication-siteminder"></a>2.2.1. Request-Header Authentication (Siteminder)</h4> <div class="paragraph"> <p>An external authentication system may supply information to the application by setting specific headers on the HTTP request. A well known example of this is Siteminder, which passes the username in a header called <code>SM_USER</code>. This mechanism is supported by the class <code>RequestHeaderAuthenticationFilter</code> which simply extracts the username from the header. It defaults to using the name <code>SM_USER</code> as the header name. See the Javadoc for more details.</p> </div> <div class="admonitionblock tip"> <table> <tbody><tr> <td class="icon"> <i class="icon-tip" title="Tip"></i> </td> <td class="content"> <div class="paragraph"> <p>Note that when using a system like this, the framework performs no authentication checks at all and it is <em>extremely</em> important that the external system is configured properly and protects all access to the application. If an attacker is able to forge the headers in their original request without this being detected then they could potentially choose any username they wished.</p> </div> </td> </tr> </tbody></table> </div> <div class="sect4"> <h5 id="siteminder-example-configuration"><a class="anchor" href="#siteminder-example-configuration"></a>Siteminder Example Configuration</h5> <div class="paragraph"> <p>A typical configuration using this filter would look like this:</p> </div> <div class="listingblock"> <div class="content"> <pre style="" class="prettyprint xml language-xml prettyprinted"><code><span class="tag"><security:http></span><span class="pln"> </span><span class="com"><!-- Additional http configuration omitted --></span><span class="pln"> </span><span class="tag"><security:custom-filter</span><span class="pln"> </span><span class="atn">position</span><span class="pun">=</span><span class="atv">"PRE_AUTH_FILTER"</span><span class="pln"> </span><span class="atn">ref</span><span class="pun">=</span><span class="atv">"siteminderFilter"</span><span class="pln"> </span><span class="tag">/></span><span class="pln"> </span><span class="tag"></security:http></span><span class="pln"> </span><span class="tag"><bean</span><span class="pln"> </span><span class="atn">id</span><span class="pun">=</span><span class="atv">"siteminderFilter"</span><span class="pln"> </span><span class="atn">class</span><span class="pun">=</span><span class="atv">"org.springframework.security.web.authentication.preauth.RequestHeaderAuthenticationFilter"</span><span class="tag">></span><span class="pln"> </span><span class="tag"><property</span><span class="pln"> </span><span class="atn">name</span><span class="pun">=</span><span class="atv">"principalRequestHeader"</span><span class="pln"> </span><span class="atn">value</span><span class="pun">=</span><span class="atv">"SM_USER"</span><span class="tag">/></span><span class="pln"> </span><span class="tag"><property</span><span class="pln"> </span><span class="atn">name</span><span class="pun">=</span><span class="atv">"authenticationManager"</span><span class="pln"> </span><span class="atn">ref</span><span class="pun">=</span><span class="atv">"authenticationManager"</span><span class="pln"> </span><span class="tag">/></span><span class="pln"> </span><span class="tag"></bean></span><span class="pln"> </span><span class="tag"><bean</span><span class="pln"> </span><span class="atn">id</span><span class="pun">=</span><span class="atv">"preauthAuthProvider"</span><span class="pln"> </span><span class="atn">class</span><span class="pun">=</span><span class="atv">"org.springframework.security.web.authentication.preauth.PreAuthenticatedAuthenticationProvider"</span><span class="tag">></span><span class="pln"> </span><span class="tag"><property</span><span class="pln"> </span><span class="atn">name</span><span class="pun">=</span><span class="atv">"preAuthenticatedUserDetailsService"</span><span class="tag">></span><span class="pln"> </span><span class="tag"><bean</span><span class="pln"> </span><span class="atn">id</span><span class="pun">=</span><span class="atv">"userDetailsServiceWrapper"</span><span class="pln"> </span><span class="atn">class</span><span class="pun">=</span><span class="atv">"org.springframework.security.core.userdetails.UserDetailsByNameServiceWrapper"</span><span class="tag">></span><span class="pln"> </span><span class="tag"><property</span><span class="pln"> </span><span class="atn">name</span><span class="pun">=</span><span class="atv">"userDetailsService"</span><span class="pln"> </span><span class="atn">ref</span><span class="pun">=</span><span class="atv">"userDetailsService"</span><span class="tag">/></span><span class="pln"> </span><span class="tag"></bean></span><span class="pln"> </span><span class="tag"></property></span><span class="pln"> </span><span class="tag"></bean></span><span class="pln"> </span><span class="tag"><security:authentication-manager</span><span class="pln"> </span><span class="atn">alias</span><span class="pun">=</span><span class="atv">"authenticationManager"</span><span class="tag">></span><span class="pln"> </span><span class="tag"><security:authentication-provider</span><span class="pln"> </span><span class="atn">ref</span><span class="pun">=</span><span class="atv">"preauthAuthProvider"</span><span class="pln"> </span><span class="tag">/></span><span class="pln"> </span><span class="tag"></security:authentication-manager></span></code></pre> </div> </div> <div class="paragraph"> <p>We’ve assumed here that the <a href="#ns-config">security namespace</a> is being used for configuration. It’s also assumed that you have added a <code>UserDetailsService</code> (called "userDetailsService") to your configuration to load the user’s roles.</p> </div> </div> </div> <div class="sect3"> <h4 id="java-ee-container-authentication"><a class="anchor" href="#java-ee-container-authentication"></a>2.2.2. Java EE Container Authentication</h4> <div class="paragraph"> <p>The class <code>J2eePreAuthenticatedProcessingFilter</code> will extract the username from the <code>userPrincipal</code> property of the <code>HttpServletRequest</code>. Use of this filter would usually be combined with the use of Java EE roles as described above in <a href="#j2ee-preauth-details">J2eeBasedPreAuthenticatedWebAuthenticationDetailsSource</a>.</p> </div> <div class="paragraph"> <p>There is a sample application in the codebase which uses this approach, so get hold of the code from subversion and have a look at the application context file if you are interested. The code is in the <code>samples/preauth</code> directory.</p> </div> </div> </div> </div> </div> <div class="sect1"> <h2 id="ldap"><a class="anchor" href="#ldap"></a>3. LDAP Authentication</h2> <div class="sectionbody"> <div class="sect2"> <h3 id="ldap-overview"><a class="anchor" href="#ldap-overview"></a>3.1. Overview</h3> <div class="paragraph"> <p>LDAP is often used by organizations as a central repository for user information and as an authentication service. It can also be used to store the role information for application users.</p> </div> <div class="paragraph"> <p>There are many different scenarios for how an LDAP server may be configured so Spring Security’s LDAP provider is fully configurable. It uses separate strategy interfaces for authentication and role retrieval and provides default implementations which can be configured to handle a wide range of situations.</p> </div> <div class="paragraph"> <p>You should be familiar with LDAP before trying to use it with Spring Security. The following link provides a good introduction to the concepts involved and a guide to setting up a directory using the free LDAP server OpenLDAP: <a href="http://www.zytrax.com/books/ldap/">http://www.zytrax.com/books/ldap/</a>. Some familiarity with the JNDI APIs used to access LDAP from Java may also be useful. We don’t use any third-party LDAP libraries (Mozilla, JLDAP etc.) in the LDAP provider, but extensive use is made of Spring LDAP, so some familiarity with that project may be useful if you plan on adding your own customizations.</p> </div> <div class="paragraph"> <p>When using LDAP authentication, it is important to ensure that you configure LDAP connection pooling properly. If you are unfamiliar with how to do this, you can refer to the <a href="http://docs.oracle.com/javase/jndi/tutorial/ldap/connect/config.html">Java LDAP documentation</a>.</p> </div> </div> <div class="sect2"> <h3 id="using-ldap-with-spring-security"><a class="anchor" href="#using-ldap-with-spring-security"></a>3.2. Using LDAP with Spring Security</h3> <div class="paragraph"> <p>LDAP authentication in Spring Security can be roughly divided into the following stages.</p> </div> <div class="ulist"> <ul> <li> <p>Obtaining the unique LDAP "Distinguished Name", or DN, from the login name. This will often mean performing a search in the directory, unless the exact mapping of usernames to DNs is known in advance. So a user might enter the name "joe" when logging in, but the actual name used to authenticate to LDAP will be the full DN, such as`uid=joe,ou=users,dc=springsource,dc=com`.</p> </li> <li> <p>Authenticating the user, either by "binding" as that user or by performing a remote "compare" operation of the user’s password against the password attribute in the directory entry for the DN.</p> </li> <li> <p>Loading the list of authorities for the user.</p> </li> </ul> </div> <div class="paragraph"> <p>The exception is when the LDAP directory is just being used to retrieve user information and authenticate against it locally. This may not be possible as directories are often set up with limited read access for attributes such as user passwords.</p> </div> <div class="paragraph"> <p>We will look at some configuration scenarios below. For full information on available configuration options, please consult the security namespace schema (information from which should be available in your XML editor).</p> </div> </div> <div class="sect2"> <h3 id="ldap-server"><a class="anchor" href="#ldap-server"></a>3.3. Configuring an LDAP Server</h3> <div class="paragraph"> <p>The first thing you need to do is configure the server against which authentication should take place. This is done using the <code><ldap-server></code> element from the security namespace. This can be configured to point at an external LDAP server, using the <code>url</code> attribute:</p> </div> <div class="listingblock"> <div class="content"> <pre style="" class="prettyprint xml language-xml prettyprinted"><code><span class="tag"><ldap-server</span><span class="pln"> </span><span class="atn">url</span><span class="pun">=</span><span class="atv">"ldap://springframework.org:389/dc=springframework,dc=org"</span><span class="pln"> </span><span class="tag">/></span></code></pre> </div> </div> <div class="sect3"> <h4 id="using-an-embedded-test-server"><a class="anchor" href="#using-an-embedded-test-server"></a>3.3.1. Using an Embedded Test Server</h4> <div class="paragraph"> <p>The <code><ldap-server></code> element can also be used to create an embedded server, which can be very useful for testing and demonstrations. In this case you use it without the <code>url</code> attribute:</p> </div> <div class="listingblock"> <div class="content"> <pre style="" class="prettyprint xml language-xml prettyprinted"><code><span class="tag"><ldap-server</span><span class="pln"> </span><span class="atn">root</span><span class="pun">=</span><span class="atv">"dc=springframework,dc=org"</span><span class="tag">/></span></code></pre> </div> </div> <div class="paragraph"> <p>Here we’ve specified that the root DIT of the directory should be "dc=springframework,dc=org", which is the default. Used this way, the namespace parser will create an embedded Apache Directory server and scan the classpath for any LDIF files, which it will attempt to load into the server. You can customize this behaviour using the <code>ldif</code> attribute, which defines an LDIF resource to be loaded:</p> </div> <div class="listingblock"> <div class="content"> <pre style="" class="prettyprint xml language-xml prettyprinted"><code><span class="tag"><ldap-server</span><span class="pln"> </span><span class="atn">ldif</span><span class="pun">=</span><span class="atv">"classpath:users.ldif"</span><span class="pln"> </span><span class="tag">/></span></code></pre> </div> </div> <div class="paragraph"> <p>This makes it a lot easier to get up and running with LDAP, since it can be inconvenient to work all the time with an external server. It also insulates the user from the complex bean configuration needed to wire up an Apache Directory server. Using plain Spring Beans the configuration would be much more cluttered. You must have the necessary Apache Directory dependency jars available for your application to use. These can be obtained from the LDAP sample application.</p> </div> </div> <div class="sect3"> <h4 id="using-bind-authentication"><a class="anchor" href="#using-bind-authentication"></a>3.3.2. Using Bind Authentication</h4> <div class="paragraph"> <p>This is the most common LDAP authentication scenario.</p> </div> <div class="listingblock"> <div class="content"> <pre style="" class="prettyprint xml language-xml prettyprinted"><code><span class="tag"><ldap-authentication-provider</span><span class="pln"> </span><span class="atn">user-dn-pattern</span><span class="pun">=</span><span class="atv">"uid={0},ou=people"</span><span class="tag">/></span></code></pre> </div> </div> <div class="paragraph"> <p>This simple example would obtain the DN for the user by substituting the user login name in the supplied pattern and attempting to bind as that user with the login password. This is OK if all your users are stored under a single node in the directory. If instead you wished to configure an LDAP search filter to locate the user, you could use the following:</p> </div> <div class="listingblock"> <div class="content"> <pre style="" class="prettyprint xml language-xml prettyprinted"><code><span class="tag"><ldap-authentication-provider</span><span class="pln"> </span><span class="atn">user-search-filter</span><span class="pun">=</span><span class="atv">"(uid={0})"</span><span class="pln"> </span><span class="atn">user-search-base</span><span class="pun">=</span><span class="atv">"ou=people"</span><span class="tag">/></span></code></pre> </div> </div> <div class="paragraph"> <p>If used with the server definition above, this would perform a search under the DN <code>ou=people,dc=springframework,dc=org</code> using the value of the <code>user-search-filter</code> attribute as a filter. Again the user login name is substituted for the parameter in the filter name, so it will search for an entry with the <code>uid</code> attribute equal to the user name. If <code>user-search-base</code> isn’t supplied, the search will be performed from the root.</p> </div> </div> <div class="sect3"> <h4 id="loading-authorities"><a class="anchor" href="#loading-authorities"></a>3.3.3. Loading Authorities</h4> <div class="paragraph"> <p>How authorities are loaded from groups in the LDAP directory is controlled by the following attributes.</p> </div> <div class="ulist"> <ul> <li> <p><code>group-search-base</code>. Defines the part of the directory tree under which group searches should be performed.</p> </li> <li> <p><code>group-role-attribute</code>. The attribute which contains the name of the authority defined by the group entry. Defaults to`cn`</p> </li> <li> <p><code>group-search-filter</code>. The filter which is used to search for group membership. The default is`uniqueMember={0}<code>, corresponding to the `groupOfUniqueNames</code> LDAP class <span class="footnote">[<a id="_footnoteref_21" class="footnote" href="#_footnote_21" title="View footnote.">21</a>]</span>. In this case, the substituted parameter is the full distinguished name of the user. The parameter <code>{1}</code> can be used if you want to filter on the login name.</p> </li> </ul> </div> <div class="paragraph"> <p>So if we used the following configuration</p> </div> <div class="listingblock"> <div class="content"> <pre style="" class="prettyprint xml language-xml prettyprinted"><code><span class="tag"><ldap-authentication-provider</span><span class="pln"> </span><span class="atn">user-dn-pattern</span><span class="pun">=</span><span class="atv">"uid={0},ou=people"</span><span class="pln"> </span><span class="atn">group-search-base</span><span class="pun">=</span><span class="atv">"ou=groups"</span><span class="pln"> </span><span class="tag">/></span></code></pre> </div> </div> <div class="paragraph"> <p>and authenticated successfully as user "ben", the subsequent loading of authorities would perform a search under the directory entry`ou=groups,dc=springframework,dc=org`, looking for entries which contain the attribute <code>uniqueMember</code> with value <code>uid=ben,ou=people,dc=springframework,dc=org</code>. By default the authority names will have the prefix <code>ROLE_</code> prepended. You can change this using the <code>role-prefix</code> attribute. If you don’t want any prefix, use <code>role-prefix="none"</code>. For more information on loading authorities, see the Javadoc for the <code>DefaultLdapAuthoritiesPopulator</code> class.</p> </div> </div> </div> <div class="sect2"> <h3 id="implementation-classes"><a class="anchor" href="#implementation-classes"></a>3.4. Implementation Classes</h3> <div class="paragraph"> <p>The namespace configuration options we’ve used above are simple to use and much more concise than using Spring beans explicitly. There are situations when you may need to know how to configure Spring Security LDAP directly in your application context. You may wish to customize the behaviour of some of the classes, for example. If you’re happy using namespace configuration then you can skip this section and the next one.</p> </div> <div class="paragraph"> <p>The main LDAP provider class, <code>LdapAuthenticationProvider</code>, doesn’t actually do much itself but delegates the work to two other beans, an <code>LdapAuthenticator</code> and an <code>LdapAuthoritiesPopulator</code> which are responsible for authenticating the user and retrieving the user’s set of <code>GrantedAuthority</code> s respectively.</p> </div> <div class="sect3"> <h4 id="ldap-ldap-authenticators"><a class="anchor" href="#ldap-ldap-authenticators"></a>3.4.1. LdapAuthenticator Implementations</h4> <div class="paragraph"> <p>The authenticator is also responsible for retrieving any required user attributes. This is because the permissions on the attributes may depend on the type of authentication being used. For example, if binding as the user, it may be necessary to read them with the user’s own permissions.</p> </div> <div class="paragraph"> <p>There are currently two authentication strategies supplied with Spring Security:</p> </div> <div class="ulist"> <ul> <li> <p>Authentication directly to the LDAP server ("bind" authentication).</p> </li> <li> <p>Password comparison, where the password supplied by the user is compared with the one stored in the repository. This can either be done by retrieving the value of the password attribute and checking it locally or by performing an LDAP "compare" operation, where the supplied password is passed to the server for comparison and the real password value is never retrieved.</p> </li> </ul> </div> <div class="sect4"> <h5 id="ldap-ldap-authenticators-common"><a class="anchor" href="#ldap-ldap-authenticators-common"></a>Common Functionality</h5> <div class="paragraph"> <p>Before it is possible to authenticate a user (by either strategy), the distinguished name (DN) has to be obtained from the login name supplied to the application. This can be done either by simple pattern-matching (by setting the <code>setUserDnPatterns</code> array property) or by setting the <code>userSearch</code> property. For the DN pattern-matching approach, a standard Java pattern format is used, and the login name will be substituted for the parameter <code>{0}</code>. The pattern should be relative to the DN that the configured <code>SpringSecurityContextSource</code> will bind to (see the section on <a href="#ldap-context-source">connecting to the LDAP server</a> for more information on this). For example, if you are using an LDAP server with the URL`ldap://monkeymachine.co.uk/dc=springframework,dc=org`, and have a pattern <code>uid={0},ou=greatapes</code>, then a login name of "gorilla" will map to a DN`uid=gorilla,ou=greatapes,dc=springframework,dc=org`. Each configured DN pattern will be tried in turn until a match is found. For information on using a search, see the section on <a href="#ldap-searchobjects">search objects</a> below. A combination of the two approaches can also be used - the patterns will be checked first and if no matching DN is found, the search will be used.</p> </div> </div> <div class="sect4"> <h5 id="ldap-ldap-authenticators-bind"><a class="anchor" href="#ldap-ldap-authenticators-bind"></a>BindAuthenticator</h5> <div class="paragraph"> <p>The class <code>BindAuthenticator</code> in the package <code>org.springframework.security.ldap.authentication</code> implements the bind authentication strategy. It simply attempts to bind as the user.</p> </div> </div> <div class="sect4"> <h5 id="ldap-ldap-authenticators-password"><a class="anchor" href="#ldap-ldap-authenticators-password"></a>PasswordComparisonAuthenticator</h5> <div class="paragraph"> <p>The class <code>PasswordComparisonAuthenticator</code> implements the password comparison authentication strategy.</p> </div> </div> </div> <div class="sect3"> <h4 id="ldap-context-source"><a class="anchor" href="#ldap-context-source"></a>3.4.2. Connecting to the LDAP Server</h4> <div class="paragraph"> <p>The beans discussed above have to be able to connect to the server. They both have to be supplied with a <code>SpringSecurityContextSource</code> which is an extension of Spring LDAP’s <code>ContextSource</code>. Unless you have special requirements, you will usually configure a <code>DefaultSpringSecurityContextSource</code> bean, which can be configured with the URL of your LDAP server and optionally with the username and password of a "manager" user which will be used by default when binding to the server (instead of binding anonymously). For more information read the Javadoc for this class and for Spring LDAP’s <code>AbstractContextSource</code>.</p> </div> </div> <div class="sect3"> <h4 id="ldap-searchobjects"><a class="anchor" href="#ldap-searchobjects"></a>3.4.3. LDAP Search Objects</h4> <div class="paragraph"> <p>Often a more complicated strategy than simple DN-matching is required to locate a user entry in the directory. This can be encapsulated in an <code>LdapUserSearch</code> instance which can be supplied to the authenticator implementations, for example, to allow them to locate a user. The supplied implementation is <code>FilterBasedLdapUserSearch</code>.</p> </div> <div class="sect4"> <h5 id="ldap-searchobjects-filter"><a class="anchor" href="#ldap-searchobjects-filter"></a>FilterBasedLdapUserSearch</h5> <div class="paragraph"> <p>This bean uses an LDAP filter to match the user object in the directory. The process is explained in the Javadoc for the corresponding search method on thehttp://java.sun.com/j2se/1.4.2/docs/api/javax/naming/directory/DirContext.html#search(javax.naming.Name,%20java.lang.String,%20java.lang.Object[],%20javax.naming.directory.SearchControls)[JDK DirContext class]. As explained there, the search filter can be supplied with parameters. For this class, the only valid parameter is <code>{0}</code> which will be replaced with the user’s login name.</p> </div> </div> </div> <div class="sect3"> <h4 id="ldap-authorities"><a class="anchor" href="#ldap-authorities"></a>3.4.4. LdapAuthoritiesPopulator</h4> <div class="paragraph"> <p>After authenticating the user successfully, the <code>LdapAuthenticationProvider</code> will attempt to load a set of authorities for the user by calling the configured <code>LdapAuthoritiesPopulator</code> bean. The <code>DefaultLdapAuthoritiesPopulator</code> is an implementation which will load the authorities by searching the directory for groups of which the user is a member (typically these will be <code>groupOfNames</code> or <code>groupOfUniqueNames</code> entries in the directory). Consult the Javadoc for this class for more details on how it works.</p> </div> <div class="paragraph"> <p>If you want to use LDAP only for authentication, but load the authorities from a difference source (such as a database) then you can provide your own implementation of this interface and inject that instead.</p> </div> </div> <div class="sect3"> <h4 id="ldap-bean-config"><a class="anchor" href="#ldap-bean-config"></a>3.4.5. Spring Bean Configuration</h4> <div class="paragraph"> <p>A typical configuration, using some of the beans we’ve discussed here, might look like this:</p> </div> <div class="listingblock"> <div class="content"> <pre style="" class="prettyprint xml language-xml prettyprinted"><code><span class="tag"><bean</span><span class="pln"> </span><span class="atn">id</span><span class="pun">=</span><span class="atv">"contextSource"</span><span class="pln"> </span><span class="atn">class</span><span class="pun">=</span><span class="atv">"org.springframework.security.ldap.DefaultSpringSecurityContextSource"</span><span class="tag">></span><span class="pln"> </span><span class="tag"><constructor-arg</span><span class="pln"> </span><span class="atn">value</span><span class="pun">=</span><span class="atv">"ldap://monkeymachine:389/dc=springframework,dc=org"</span><span class="tag">/></span><span class="pln"> </span><span class="tag"><property</span><span class="pln"> </span><span class="atn">name</span><span class="pun">=</span><span class="atv">"userDn"</span><span class="pln"> </span><span class="atn">value</span><span class="pun">=</span><span class="atv">"cn=manager,dc=springframework,dc=org"</span><span class="tag">/></span><span class="pln"> </span><span class="tag"><property</span><span class="pln"> </span><span class="atn">name</span><span class="pun">=</span><span class="atv">"password"</span><span class="pln"> </span><span class="atn">value</span><span class="pun">=</span><span class="atv">"password"</span><span class="tag">/></span><span class="pln"> </span><span class="tag"></bean></span><span class="pln"> </span><span class="tag"><bean</span><span class="pln"> </span><span class="atn">id</span><span class="pun">=</span><span class="atv">"ldapAuthProvider"</span><span class="pln"> </span><span class="atn">class</span><span class="pun">=</span><span class="atv">"org.springframework.security.ldap.authentication.LdapAuthenticationProvider"</span><span class="tag">></span><span class="pln"> </span><span class="tag"><constructor-arg></span><span class="pln"> </span><span class="tag"><bean</span><span class="pln"> </span><span class="atn">class</span><span class="pun">=</span><span class="atv">"org.springframework.security.ldap.authentication.BindAuthenticator"</span><span class="tag">></span><span class="pln"> </span><span class="tag"><constructor-arg</span><span class="pln"> </span><span class="atn">ref</span><span class="pun">=</span><span class="atv">"contextSource"</span><span class="tag">/></span><span class="pln"> </span><span class="tag"><property</span><span class="pln"> </span><span class="atn">name</span><span class="pun">=</span><span class="atv">"userDnPatterns"</span><span class="tag">></span><span class="pln"> </span><span class="tag"><list><value></span><span class="pln">uid={0},ou=people</span><span class="tag"></value></list></span><span class="pln"> </span><span class="tag"></property></span><span class="pln"> </span><span class="tag"></bean></span><span class="pln"> </span><span class="tag"></constructor-arg></span><span class="pln"> </span><span class="tag"><constructor-arg></span><span class="pln"> </span><span class="tag"><bean</span><span class="pln"> </span><span class="atn">class</span><span class="pun">=</span><span class="atv">"org.springframework.security.ldap.userdetails.DefaultLdapAuthoritiesPopulator"</span><span class="tag">></span><span class="pln"> </span><span class="tag"><constructor-arg</span><span class="pln"> </span><span class="atn">ref</span><span class="pun">=</span><span class="atv">"contextSource"</span><span class="tag">/></span><span class="pln"> </span><span class="tag"><constructor-arg</span><span class="pln"> </span><span class="atn">value</span><span class="pun">=</span><span class="atv">"ou=groups"</span><span class="tag">/></span><span class="pln"> </span><span class="tag"><property</span><span class="pln"> </span><span class="atn">name</span><span class="pun">=</span><span class="atv">"groupRoleAttribute"</span><span class="pln"> </span><span class="atn">value</span><span class="pun">=</span><span class="atv">"ou"</span><span class="tag">/></span><span class="pln"> </span><span class="tag"></bean></span><span class="pln"> </span><span class="tag"></constructor-arg></span><span class="pln"> </span><span class="tag"></bean></span></code></pre> </div> </div> <div class="paragraph"> <p>This would set up the provider to access an LDAP server with URL <code>ldap://monkeymachine:389/dc=springframework,dc=org</code>. Authentication will be performed by attempting to bind with the DN`uid=<user-login-name>,ou=people,dc=springframework,dc=org`. After successful authentication, roles will be assigned to the user by searching under the DN <code>ou=groups,dc=springframework,dc=org</code> with the default filter <code>(member=<user's-DN>)</code>. The role name will be taken from the "ou" attribute of each match.</p> </div> <div class="paragraph"> <p>To configure a user search object, which uses the filter <code>(uid=<user-login-name>)</code> for use instead of the DN-pattern (or in addition to it), you would configure the following bean</p> </div> <div class="listingblock"> <div class="content"> <pre style="" class="prettyprint xml language-xml prettyprinted"><code><span class="pln"> </span><span class="tag"><bean</span><span class="pln"> </span><span class="atn">id</span><span class="pun">=</span><span class="atv">"userSearch"</span><span class="pln"> </span><span class="atn">class</span><span class="pun">=</span><span class="atv">"org.springframework.security.ldap.search.FilterBasedLdapUserSearch"</span><span class="tag">></span><span class="pln"> </span><span class="tag"><constructor-arg</span><span class="pln"> </span><span class="atn">index</span><span class="pun">=</span><span class="atv">"0"</span><span class="pln"> </span><span class="atn">value</span><span class="pun">=</span><span class="atv">""</span><span class="tag">/></span><span class="pln"> </span><span class="tag"><constructor-arg</span><span class="pln"> </span><span class="atn">index</span><span class="pun">=</span><span class="atv">"1"</span><span class="pln"> </span><span class="atn">value</span><span class="pun">=</span><span class="atv">"(uid={0})"</span><span class="tag">/></span><span class="pln"> </span><span class="tag"><constructor-arg</span><span class="pln"> </span><span class="atn">index</span><span class="pun">=</span><span class="atv">"2"</span><span class="pln"> </span><span class="atn">ref</span><span class="pun">=</span><span class="atv">"contextSource"</span><span class="pln"> </span><span class="tag">/></span><span class="pln"> </span><span class="tag"></bean></span></code></pre> </div> </div> <div class="paragraph"> <p>and use it by setting the <code>BindAuthenticator</code> bean’s <code>userSearch</code> property. The authenticator would then call the search object to obtain the correct user’s DN before attempting to bind as this user.</p> </div> </div> <div class="sect3"> <h4 id="ldap-custom-user-details"><a class="anchor" href="#ldap-custom-user-details"></a>3.4.6. LDAP Attributes and Customized UserDetails</h4> <div class="paragraph"> <p>The net result of an authentication using <code>LdapAuthenticationProvider</code> is the same as a normal Spring Security authentication using the standard <code>UserDetailsService</code> interface. A <code>UserDetails</code> object is created and stored in the returned <code>Authentication</code> object. As with using a <code>UserDetailsService</code>, a common requirement is to be able to customize this implementation and add extra properties. When using LDAP, these will normally be attributes from the user entry. The creation of the <code>UserDetails</code> object is controlled by the provider’s <code>UserDetailsContextMapper</code> strategy, which is responsible for mapping user objects to and from LDAP context data:</p> </div> <div class="listingblock"> <div class="content"> <pre style="" class="prettyprint java language-java prettyprinted"><code><span class="kwd">public</span><span class="pln"> </span><span class="kwd">interface</span><span class="pln"> </span><span class="typ">UserDetailsContextMapper</span><span class="pln"> </span><span class="pun">{</span><span class="pln"> </span><span class="typ">UserDetails</span><span class="pln"> mapUserFromContext</span><span class="pun">(</span><span class="typ">DirContextOperations</span><span class="pln"> ctx</span><span class="pun">,</span><span class="pln"> </span><span class="typ">String</span><span class="pln"> username</span><span class="pun">,</span><span class="pln"> </span><span class="typ">Collection</span><span class="pun"><</span><span class="typ">GrantedAuthority</span><span class="pun">></span><span class="pln"> authorities</span><span class="pun">);</span><span class="pln"> </span><span class="kwd">void</span><span class="pln"> mapUserToContext</span><span class="pun">(</span><span class="typ">UserDetails</span><span class="pln"> user</span><span class="pun">,</span><span class="pln"> </span><span class="typ">DirContextAdapter</span><span class="pln"> ctx</span><span class="pun">);</span><span class="pln"> </span><span class="pun">}</span></code></pre> </div> </div> <div class="paragraph"> <p>Only the first method is relevant for authentication. If you provide an implementation of this interface and inject it into the <code>LdapAuthenticationProvider</code>, you have control over exactly how the UserDetails object is created. The first parameter is an instance of Spring LDAP’s <code>DirContextOperations</code> which gives you access to the LDAP attributes which were loaded during authentication. the <code>username</code> parameter is the name used to authenticate and the final parameter is the collection of authorities loaded for the user by the configured`LdapAuthoritiesPopulator`.</p> </div> <div class="paragraph"> <p>The way the context data is loaded varies slightly depending on the type of authentication you are using. With the <code>BindAuthenticator</code>, the context returned from the bind operation will be used to read the attributes, otherwise the data will be read using the standard context obtained from the configured <code>ContextSource</code> (when a search is configured to locate the user, this will be the data returned by the search object).</p> </div> </div> </div> <div class="sect2"> <h3 id="ldap-active-directory"><a class="anchor" href="#ldap-active-directory"></a>3.5. Active Directory Authentication</h3> <div class="paragraph"> <p>Active Directory supports its own non-standard authentication options, and the normal usage pattern doesn’t fit too cleanly with the standard <code>LdapAuthenticationProvider</code>. Typically authentication is performed using the domain username (in the form <code>user@domain</code>), rather than using an LDAP distinguished name. To make this easier, Spring Security 3.1 has an authentication provider which is customized for a typical Active Directory setup.</p> </div> <div class="sect3"> <h4 id="activedirectoryldapauthenticationprovider"><a class="anchor" href="#activedirectoryldapauthenticationprovider"></a>3.5.1. ActiveDirectoryLdapAuthenticationProvider</h4> <div class="paragraph"> <p>Configuring <code>ActiveDirectoryLdapAuthenticationProvider</code> is quite straightforward. You just need to supply the domain name and an LDAP URL supplying the address of the server <span class="footnote">[<a id="_footnoteref_22" class="footnote" href="#_footnote_22" title="View footnote.">22</a>]</span>. An example configuration would then look like this:</p> </div> <div class="listingblock"> <div class="content"> <pre style="" class="prettyprint xml language-xml prettyprinted"><code><span class="pln"> </span><span class="tag"><bean</span><span class="pln"> </span><span class="atn">id</span><span class="pun">=</span><span class="atv">"adAuthenticationProvider"</span><span class="pln"> </span><span class="atn">class</span><span class="pun">=</span><span class="atv">"org.springframework.security.ldap.authentication.ad.ActiveDirectoryLdapAuthenticationProvider"</span><span class="tag">></span><span class="pln"> </span><span class="tag"><constructor-arg</span><span class="pln"> </span><span class="atn">value</span><span class="pun">=</span><span class="atv">"mydomain.com"</span><span class="pln"> </span><span class="tag">/></span><span class="pln"> </span><span class="tag"><constructor-arg</span><span class="pln"> </span><span class="atn">value</span><span class="pun">=</span><span class="atv">"ldap://adserver.mydomain.com/"</span><span class="pln"> </span><span class="tag">/></span><span class="pln"> </span><span class="tag"></bean></span><span class="pln"> }</span></code></pre> </div> </div> <div class="paragraph"> <p>Note that there is no need to specify a separate <code>ContextSource</code> in order to define the server location - the bean is completely self-contained. A user named "Sharon", for example, would then be able to authenticate by entering either the username <code>sharon</code> or the full Active Directory <code>userPrincipalName</code>, namely <code>sharon@mydomain.com<script cf-hash="f9e31" type="text/javascript"> /* <![CDATA[ */!function(){try{var t="currentScript"in document?document.currentScript:function(){for(var t=document.getElementsByTagName("script"),e=t.length;e--;)if(t[e].getAttribute("cf-hash"))return t[e]}();if(t&&t.previousSibling){var e,r,n,i,c=t.previousSibling,a=c.getAttribute("data-cfemail");if(a){for(e="",r=parseInt(a.substr(0,2),16),n=2;a.length-n;n+=2)i=parseInt(a.substr(n,2),16)^r,e+=String.fromCharCode(i);e=document.createTextNode(e),c.parentNode.replaceChild(e,c)}}}catch(u){}}();/* ]]> */</script></code>. The user’s directory entry will then be located, and the attributes returned for possible use in customizing the created <code>UserDetails</code> object (a <code>UserDetailsContextMapper</code> can be injected for this purpose, as described above). All interaction with the directory takes place with the identity of the user themselves. There is no concept of a "manager" user.</p> </div> <div class="paragraph"> <p>By default, the user authorities are obtained from the <code>memberOf</code> attribute values of the user entry. The authorities allocated to the user can again be customized using a <code>UserDetailsContextMapper</code>. You can also inject a <code>GrantedAuthoritiesMapper</code> into the provider instance to control the authorities which end up in the <code>Authentication</code> object.</p> </div> <div class="sect4"> <h5 id="active-directory-error-codes"><a class="anchor" href="#active-directory-error-codes"></a>Active Directory Error Codes</h5> <div class="paragraph"> <p>By default, a failed result will cause a standard Spring Security <code>BadCredentialsException</code>. If you set the property <code>convertSubErrorCodesToExceptions</code> to <code>true</code>, the exception messages will be parsed to attempt to extract the Active Directory-specific error code and raise a more specific exception. Check the class Javadoc for more information.</p> </div> </div> </div> </div> </div> </div> <div class="sect1"> <h2 id="taglibs"><a class="anchor" href="#taglibs"></a>4. JSP Tag Libraries</h2> <div class="sectionbody"> <div class="paragraph"> <p>Spring Security has its own taglib which provides basic support for accessing security information and applying security constraints in JSPs.</p> </div> <div class="sect2"> <h3 id="declaring-the-taglib"><a class="anchor" href="#declaring-the-taglib"></a>4.1. Declaring the Taglib</h3> <div class="paragraph"> <p>To use any of the tags, you must have the security taglib declared in your JSP:</p> </div> <div class="listingblock"> <div class="content"> <pre style="" class="prettyprint xml language-xml prettyprinted"><code><span class="pun"><%@</span><span class="pln"> taglib prefix</span><span class="pun">=</span><span class="str">"sec"</span><span class="pln"> uri</span><span class="pun">=</span><span class="str">"http://www.springframework.org/security/tags"</span><span class="pln"> %></span></code></pre> </div> </div> </div> <div class="sect2"> <h3 id="the-authorize-tag"><a class="anchor" href="#the-authorize-tag"></a>4.2. The authorize Tag</h3> <div class="paragraph"> <p>This tag is used to determine whether its contents should be evaluated or not. In Spring Security 3.0, it can be used in two ways <span class="footnote">[<a id="_footnoteref_23" class="footnote" href="#_footnote_23" title="View footnote.">23</a>]</span>. The first approach uses a <a href="#el-access-web">web-security expression</a>, specified in the <code>access</code> attribute of the tag. The expression evaluation will be delegated to the <code>SecurityExpressionHandler<FilterInvocation></code> defined in the application context (you should have web expressions enabled in your <code><http></code> namespace configuration to make sure this service is available). So, for example, you might have</p> </div> <div class="listingblock"> <div class="content"> <pre style="" class="prettyprint xml language-xml prettyprinted"><code><span class="tag"><sec:authorize</span><span class="pln"> </span><span class="atn">access</span><span class="pun">=</span><span class="atv">"hasRole('supervisor')"</span><span class="tag">></span><span class="pln"> This content will only be visible to users who have the "supervisor" authority in their list of </span><span class="tag"><tt></span><span class="pln">GrantedAuthority</span><span class="tag"></tt></span><span class="pln">s. </span><span class="tag"></sec:authorize></span></code></pre> </div> </div> <div class="paragraph"> <p>A common requirement is to only show a particular link, if the user is actually allowed to click it. How can we determine in advance whether something will be allowed? This tag can also operate in an alternative mode which allows you to define a particular URL as an attribute. If the user is allowed to invoke that URL, then the tag body will be evaluated, otherwise it will be skipped. So you might have something like</p> </div> <div class="listingblock"> <div class="content"> <pre style="" class="prettyprint xml language-xml prettyprinted"><code><span class="tag"><sec:authorize</span><span class="pln"> </span><span class="atn">url</span><span class="pun">=</span><span class="atv">"/admin"</span><span class="tag">></span><span class="pln"> This content will only be visible to users who are authorized to send requests to the "/admin" URL. </span><span class="tag"></sec:authorize></span></code></pre> </div> </div> <div class="paragraph"> <p>To use this tag there must also be an instance of <code>WebInvocationPrivilegeEvaluator</code> in your application context. If you are using the namespace, one will automatically be registered. This is an instance of <code>DefaultWebInvocationPrivilegeEvaluator</code>, which creates a dummy web request for the supplied URL and invokes the security interceptor to see whether the request would succeed or fail. This allows you to delegate to the access-control setup you defined using <code>intercept-url</code> declarations within the <code><http></code> namespace configuration and saves having to duplicate the information (such as the required roles) within your JSPs. This approach can also be combined with a <code>method</code> attribute, supplying the HTTP method, for a more specific match.</p> </div> <div class="paragraph"> <p>The boolean result of evaluating the tag (whether it grants or denies access) can be stored in a page context scope variable by setting the <code>var</code> attribute to the variable name, avoiding the need for duplicating and re-evaluating the condition at other points in the page.</p> </div> <div class="sect3"> <h4 id="disabling-tag-authorization-for-testing"><a class="anchor" href="#disabling-tag-authorization-for-testing"></a>4.2.1. Disabling Tag Authorization for Testing</h4> <div class="paragraph"> <p>Hiding a link in a page for unauthorized users doesn’t prevent them from accessing the URL. They could just type it into their browser directly, for example. As part of your testing process, you may want to reveal the hidden areas in order to check that links really are secured at the back end. If you set the system property <code>spring.security.disableUISecurity</code> to <code>true</code>, the <code>authorize</code> tag will still run but will not hide its contents. By default it will also surround the content with <code><span class="securityHiddenUI">...</span></code> tags. This allows you to display "hidden" content with a particular CSS style such as a different background colour. Try running the "tutorial" sample application with this property enabled, for example.</p> </div> <div class="paragraph"> <p>You can also set the properties <code>spring.security.securedUIPrefix</code> and <code>spring.security.securedUISuffix</code> if you want to change surrounding text from the default <code>span</code> tags (or use empty strings to remove it completely).</p> </div> </div> </div> <div class="sect2"> <h3 id="the-authentication-tag"><a class="anchor" href="#the-authentication-tag"></a>4.3. The authentication Tag</h3> <div class="paragraph"> <p>This tag allows access to the current <code>Authentication</code> object stored in the security context. It renders a property of the object directly in the JSP. So, for example, if the <code>principal</code> property of the <code>Authentication</code> is an instance of Spring Security’s <code>UserDetails</code> object, then using <code><sec:authentication property="principal.username" /></code> will render the name of the current user.</p> </div> <div class="paragraph"> <p>Of course, it isn’t necessary to use JSP tags for this kind of thing and some people prefer to keep as little logic as possible in the view. You can access the <code>Authentication</code> object in your MVC controller (by calling <code>SecurityContextHolder.getContext().getAuthentication()</code>) and add the data directly to your model for rendering by the view.</p> </div> </div> <div class="sect2"> <h3 id="the-accesscontrollist-tag"><a class="anchor" href="#the-accesscontrollist-tag"></a>4.4. The accesscontrollist Tag</h3> <div class="paragraph"> <p>This tag is only valid when used with Spring Security’s ACL module. It checks a comma-separated list of required permissions for a specified domain object. If the current user has any of those permissions, then the tag body will be evaluated. If they don’t, it will be skipped. An example might be</p> </div> <div class="listingblock"> <div class="content"> <pre style="" class="prettyprint xml language-xml prettyprinted"><code><span class="tag"><sec:accesscontrollist</span><span class="pln"> </span><span class="atn">hasPermission</span><span class="pun">=</span><span class="atv">"1,2"</span><span class="pln"> </span><span class="atn">domainObject</span><span class="pun">=</span><span class="atv">"${someObject}"</span><span class="tag">></span><span class="pln"> This will be shown if the user has either of the permissions represented by the values "1" or "2" on the given object. </span><span class="tag"></sec:accesscontrollist></span></code></pre> </div> </div> <div class="paragraph"> <p>The permissions are passed to the <code>PermissionFactory</code> defined in the application context, converting them to ACL <code>Permission</code> instances, so they may be any format which is supported by the factory - they don’t have to be integers, they could be strings like <code>READ</code> or <code>WRITE</code>. If no <code>PermissionFactory</code> is found, an instance of <code>DefaultPermissionFactory</code> will be used. The <code>AclService</code> from the application context will be used to load the <code>Acl</code> instance for the supplied object. The <code>Acl</code> will be invoked with the required permissions to check if any of them are granted.</p> </div> <div class="paragraph"> <p>This tag also supports the <code>var</code> attribute, in the same way as the <code>authorize</code> tag.</p> </div> </div> <div class="sect2"> <h3 id="the-csrfinput-tag"><a class="anchor" href="#the-csrfinput-tag"></a>4.5. The csrfInput Tag</h3> <div class="paragraph"> <p>If CSRF protection is enabled, this tag inserts a hidden form field with the correct name and value for the CSRF protection token. If CSRF protection is not enabled, this tag outputs nothing.</p> </div> <div class="paragraph"> <p>Normally Spring Security automatically inserts a CSRF form field for any <code><form:form></code> tags you use, but if for some reason you cannot use <code><form:form></code>, <code>csrfInput</code> is a handy replacement.</p> </div> <div class="paragraph"> <p>You should place this tag within an HTML <code><form></form></code> block, where you would normally place other input fields. Do NOT place this tag within a Spring <code><form:form></form:form></code> block—Spring Security handles Spring forms automatically.</p> </div> <div class="listingblock"> <div class="content"> <pre style="" class="prettyprint xml language-xml prettyprinted"><code><span class="pln"> </span><span class="tag"><form</span><span class="pln"> </span><span class="atn">method</span><span class="pun">=</span><span class="atv">"post"</span><span class="pln"> </span><span class="atn">action</span><span class="pun">=</span><span class="atv">"/do/something"</span><span class="tag">></span><span class="pln"> </span><span class="tag"><sec:csrfInput</span><span class="pln"> </span><span class="tag">/></span><span class="pln"> Name:</span><span class="tag"><br</span><span class="pln"> </span><span class="tag">/></span><span class="pln"> </span><span class="tag"><input</span><span class="pln"> </span><span class="atn">type</span><span class="pun">=</span><span class="atv">"text"</span><span class="pln"> </span><span class="atn">name</span><span class="pun">=</span><span class="atv">"name"</span><span class="pln"> </span><span class="tag">/></span><span class="pln"> ... </span><span class="tag"></form></span></code></pre> </div> </div> </div> <div class="sect2"> <h3 id="the-csrfmetatags-tag"><a class="anchor" href="#the-csrfmetatags-tag"></a>4.6. The csrfMetaTags Tag</h3> <div class="paragraph"> <p>If CSRF protection is enabled, this tag inserts meta tags containing the CSRF protection token form field and header names and CSRF protection token value. These meta tags are useful for employing CSRF protection within JavaScript in your applications.</p> </div> <div class="paragraph"> <p>You should place <code>csrfMetaTags</code> within an HTML <code><head></head></code> block, where you would normally place other meta tags. Once you use this tag, you can access the form field name, header name, and token value easily using JavaScript. JQuery is used in this example to make the task easier.</p> </div> <div class="listingblock"> <div class="content"> <pre style="" class="prettyprint xml language-xml prettyprinted"><code><span class="dec"><!DOCTYPE html></span><span class="pln"> </span><span class="tag"><html></span><span class="pln"> </span><span class="tag"><head></span><span class="pln"> </span><span class="tag"><title></span><span class="pln">CSRF Protected JavaScript Page</span><span class="tag"></title></span><span class="pln"> </span><span class="tag"><meta</span><span class="pln"> </span><span class="atn">name</span><span class="pun">=</span><span class="atv">"description"</span><span class="pln"> </span><span class="atn">content</span><span class="pun">=</span><span class="atv">"This is the description for this page"</span><span class="pln"> </span><span class="tag">/></span><span class="pln"> </span><span class="tag"><sec:csrfMetaTags</span><span class="pln"> </span><span class="tag">/></span><span class="pln"> </span><span class="tag"><script</span><span class="pln"> </span><span class="atn">type</span><span class="pun">=</span><span class="atv">"text/javascript"</span><span class="pln"> </span><span class="atn">language</span><span class="pun">=</span><span class="atv">"javascript"</span><span class="tag">></span><span class="pln"> var csrfParameter = $("meta[name='_csrf_parameter']").attr("content"); var csrfHeader = $("meta[name='_csrf_header']").attr("content"); var csrfToken = $("meta[name='_csrf']").attr("content"); // using XMLHttpRequest directly to send an x-www-form-urlencoded request var ajax = new XMLHttpRequest(); ajax.open("POST", "http://www.example.org/do/something", true); ajax.setRequestHeader("Content-Type", "application/x-www-form-urlencoded data"); ajax.send(csrfParameter + "=" + csrfToken + "&name=John&..."); // using XMLHttpRequest directly to send a non-x-www-form-urlencoded request var ajax = new XMLHttpRequest(); ajax.open("POST", "http://www.example.org/do/something", true); ajax.setRequestHeader(csrfHeader, csrfToken); ajax.send("..."); // using JQuery to send an x-www-form-urlencoded request var data = {}; data[csrfParameter] = csrfToken; data["name"] = "John"; ... $.ajax({ url: "http://www.example.org/do/something", type: "POST", data: data, ... }); // using JQuery to send a non-x-www-form-urlencoded request var headers = {}; headers[csrfHeader] = csrfToken; $.ajax({ url: "http://www.example.org/do/something", type: "POST", headers: headers, ... }); </span><span class="tag"><script></span><span class="pln"> </span><span class="tag"></head></span><span class="pln"> </span><span class="tag"><body></span><span class="pln"> ... </span><span class="tag"></body></span><span class="pln"> </span><span class="tag"></html></span></code></pre> </div> </div> <div class="paragraph"> <p>If CSRF protection is not enabled, <code>csrfMetaTags</code> outputs nothing.</p> </div> </div> </div> </div> <div class="sect1"> <h2 id="jaas"><a class="anchor" href="#jaas"></a>5. Java Authentication and Authorization Service (JAAS) Provider</h2> <div class="sectionbody"> <div class="sect2"> <h3 id="overview-2"><a class="anchor" href="#overview-2"></a>5.1. Overview</h3> <div class="paragraph"> <p>Spring Security provides a package able to delegate authentication requests to the Java Authentication and Authorization Service (JAAS). This package is discussed in detail below.</p> </div> </div> <div class="sect2"> <h3 id="jaas-abstractjaasauthenticationprovider"><a class="anchor" href="#jaas-abstractjaasauthenticationprovider"></a>5.2. AbstractJaasAuthenticationProvider</h3> <div class="paragraph"> <p>The <code>AbstractJaasAuthenticationProvider</code> is the basis for the provided JAAS <code>AuthenticationProvider</code> implementations. Subclasses must implement a method that creates the <code>LoginContext</code>. The <code>AbstractJaasAuthenticationProvider</code> has a number of dependencies that can be injected into it that are discussed below.</p> </div> <div class="sect3"> <h4 id="jaas-callbackhandler"><a class="anchor" href="#jaas-callbackhandler"></a>5.2.1. JAAS CallbackHandler</h4> <div class="paragraph"> <p>Most JAAS <code>LoginModule</code> s require a callback of some sort. These callbacks are usually used to obtain the username and password from the user.</p> </div> <div class="paragraph"> <p>In a Spring Security deployment, Spring Security is responsible for this user interaction (via the authentication mechanism). Thus, by the time the authentication request is delegated through to JAAS, Spring Security’s authentication mechanism will already have fully-populated an <code>Authentication</code> object containing all the information required by the JAAS <code>LoginModule</code>.</p> </div> <div class="paragraph"> <p>Therefore, the JAAS package for Spring Security provides two default callback handlers, <code>JaasNameCallbackHandler</code> and <code>JaasPasswordCallbackHandler</code>. Each of these callback handlers implement <code>JaasAuthenticationCallbackHandler</code>. In most cases these callback handlers can simply be used without understanding the internal mechanics.</p> </div> <div class="paragraph"> <p>For those needing full control over the callback behavior, internally <code>AbstractJaasAuthenticationProvider</code> wraps these <code>JaasAuthenticationCallbackHandler</code> s with an <code>InternalCallbackHandler</code>. The <code>InternalCallbackHandler</code> is the class that actually implements JAAS normal <code>CallbackHandler</code> interface. Any time that the JAAS <code>LoginModule</code> is used, it is passed a list of application context configured <code>InternalCallbackHandler</code> s. If the <code>LoginModule</code> requests a callback against the <code>InternalCallbackHandler</code> s, the callback is in-turn passed to the <code>JaasAuthenticationCallbackHandler</code> s being wrapped.</p> </div> </div> <div class="sect3"> <h4 id="jaas-authoritygranter"><a class="anchor" href="#jaas-authoritygranter"></a>5.2.2. JAAS AuthorityGranter</h4> <div class="paragraph"> <p>JAAS works with principals. Even "roles" are represented as principals in JAAS. Spring Security, on the other hand, works with <code>Authentication</code> objects. Each <code>Authentication</code> object contains a single principal, and multiple <code>GrantedAuthority</code> s. To facilitate mapping between these different concepts, Spring Security’s JAAS package includes an <code>AuthorityGranter</code> interface.</p> </div> <div class="paragraph"> <p>An <code>AuthorityGranter</code> is responsible for inspecting a JAAS principal and returning a set of <code>String</code> s, representing the authorities assigned to the principal. For each returned authority string, the <code>AbstractJaasAuthenticationProvider</code> creates a <code>JaasGrantedAuthority</code> (which implements Spring Security’s <code>GrantedAuthority</code> interface) containing the authority string and the JAAS principal that the <code>AuthorityGranter</code> was passed. The <code>AbstractJaasAuthenticationProvider</code> obtains the JAAS principals by firstly successfully authenticating the user’s credentials using the JAAS <code>LoginModule</code>, and then accessing the <code>LoginContext</code> it returns. A call to <code>LoginContext.getSubject().getPrincipals()</code> is made, with each resulting principal passed to each <code>AuthorityGranter</code> defined against the <code>AbstractJaasAuthenticationProvider.setAuthorityGranters(List)</code> property.</p> </div> <div class="paragraph"> <p>Spring Security does not include any production <code>AuthorityGranter</code> s given that every JAAS principal has an implementation-specific meaning. However, there is a <code>TestAuthorityGranter</code> in the unit tests that demonstrates a simple <code>AuthorityGranter</code> implementation.</p> </div> </div> </div> <div class="sect2"> <h3 id="jaas-defaultjaasauthenticationprovider"><a class="anchor" href="#jaas-defaultjaasauthenticationprovider"></a>5.3. DefaultJaasAuthenticationProvider</h3> <div class="paragraph"> <p>The <code>DefaultJaasAuthenticationProvider</code> allows a JAAS <code>Configuration</code> object to be injected into it as a dependency. It then creates a <code>LoginContext</code> using the injected JAAS <code>Configuration</code>. This means that <code>DefaultJaasAuthenticationProvider</code> is not bound any particular implementation of <code>Configuration</code> as <code>JaasAuthenticationProvider</code> is.</p> </div> <div class="sect3"> <h4 id="jaas-inmemoryconfiguration"><a class="anchor" href="#jaas-inmemoryconfiguration"></a>5.3.1. InMemoryConfiguration</h4> <div class="paragraph"> <p>In order to make it easy to inject a <code>Configuration</code> into <code>DefaultJaasAuthenticationProvider</code>, a default in memory implementation named <code>InMemoryConfiguration</code> is provided. The implementation constructor accepts a <code>Map</code> where each key represents a login configuration name and the value represents an <code>Array</code> of <code>AppConfigurationEntry</code> s. <code>InMemoryConfiguration</code> also supports a default <code>Array</code> of <code>AppConfigurationEntry</code> objects that will be used if no mapping is found within the provided <code>Map</code>. For details, refer to the class level javadoc of <code>InMemoryConfiguration</code>.</p> </div> </div> <div class="sect3"> <h4 id="jaas-djap-config"><a class="anchor" href="#jaas-djap-config"></a>5.3.2. DefaultJaasAuthenticationProvider Example Configuration</h4> <div class="paragraph"> <p>While the Spring configuration for <code>InMemoryConfiguration</code> can be more verbose than the standarad JAAS configuration files, using it in conjuction with <code>DefaultJaasAuthenticationProvider</code> is more flexible than <code>JaasAuthenticationProvider</code> since it not dependant on the default <code>Configuration</code> implementation.</p> </div> <div class="paragraph"> <p>An example configuration of <code>DefaultJaasAuthenticationProvider</code> using <code>InMemoryConfiguration</code> is provided below. Note that custom implementations of <code>Configuration</code> can easily be injected into <code>DefaultJaasAuthenticationProvider</code> as well.</p> </div> <div class="listingblock"> <div class="content"> <pre style="" class="prettyprint xml language-xml prettyprinted"><code><span class="pln"> </span><span class="tag"><bean</span><span class="pln"> </span><span class="atn">id</span><span class="pun">=</span><span class="atv">"jaasAuthProvider"</span><span class="pln"> </span><span class="atn">class</span><span class="pun">=</span><span class="atv">"org.springframework.security.authentication.jaas.DefaultJaasAuthenticationProvider"</span><span class="tag">></span><span class="pln"> </span><span class="tag"><property</span><span class="pln"> </span><span class="atn">name</span><span class="pun">=</span><span class="atv">"configuration"</span><span class="tag">></span><span class="pln"> </span><span class="tag"><bean</span><span class="pln"> </span><span class="atn">class</span><span class="pun">=</span><span class="atv">"org.springframework.security.authentication.jaas.memory.InMemoryConfiguration"</span><span class="tag">></span><span class="pln"> </span><span class="tag"><constructor-arg></span><span class="pln"> </span><span class="tag"><map></span><span class="pln"> </span><span class="com"><!-- SPRINGSECURITY is the default loginContextName for AbstractJaasAuthenticationProvider --></span><span class="pln"> </span><span class="tag"><entry</span><span class="pln"> </span><span class="atn">key</span><span class="pun">=</span><span class="atv">"SPRINGSECURITY"</span><span class="tag">></span><span class="pln"> </span><span class="tag"><array></span><span class="pln"> </span><span class="tag"><bean</span><span class="pln"> </span><span class="atn">class</span><span class="pun">=</span><span class="atv">"javax.security.auth.login.AppConfigurationEntry"</span><span class="tag">></span><span class="pln"> </span><span class="tag"><constructor-arg</span><span class="pln"> </span><span class="atn">value</span><span class="pun">=</span><span class="atv">"sample.SampleLoginModule"</span><span class="pln"> </span><span class="tag">/></span><span class="pln"> </span><span class="tag"><constructor-arg></span><span class="pln"> </span><span class="tag"><util:constant</span><span class="pln"> </span><span class="atn">static-field</span><span class="pun">=</span><span class="pln"> </span><span class="atv">"javax.security.auth.login.AppConfigurationEntry$LoginModuleControlFlag.REQUIRED"</span><span class="tag">/></span><span class="pln"> </span><span class="tag"></constructor-arg></span><span class="pln"> </span><span class="tag"><constructor-arg></span><span class="pln"> </span><span class="tag"><map></map></span><span class="pln"> </span><span class="tag"></constructor-arg></span><span class="pln"> </span><span class="tag"></bean></span><span class="pln"> </span><span class="tag"></array></span><span class="pln"> </span><span class="tag"></entry></span><span class="pln"> </span><span class="tag"></map></span><span class="pln"> </span><span class="tag"></constructor-arg></span><span class="pln"> </span><span class="tag"></bean></span><span class="pln"> </span><span class="tag"></property></span><span class="pln"> </span><span class="tag"><property</span><span class="pln"> </span><span class="atn">name</span><span class="pun">=</span><span class="atv">"authorityGranters"</span><span class="tag">></span><span class="pln"> </span><span class="tag"><list></span><span class="pln"> </span><span class="com"><!-- You will need to write your own implementation of AuthorityGranter --></span><span class="pln"> </span><span class="tag"><bean</span><span class="pln"> </span><span class="atn">class</span><span class="pun">=</span><span class="atv">"org.springframework.security.authentication.jaas.TestAuthorityGranter"</span><span class="tag">/></span><span class="pln"> </span><span class="tag"></list></span><span class="pln"> </span><span class="tag"></property></span><span class="pln"> </span><span class="tag"></bean></span></code></pre> </div> </div> </div> </div> <div class="sect2"> <h3 id="jaas-jaasauthenticationprovider"><a class="anchor" href="#jaas-jaasauthenticationprovider"></a>5.4. JaasAuthenticationProvider</h3> <div class="paragraph"> <p>The <code>JaasAuthenticationProvider</code> assumes the default <code>Configuration</code> is an instance of <a href="http://download.oracle.com/javase/1.4.2/docs/guide/security/jaas/spec/com/sun/security/auth/login/ConfigFile.html"> ConfigFile</a>. This assumption is made in order to attempt to update the <code>Configuration</code>. The <code>JaasAuthenticationProvider</code> then uses the default <code>Configuration</code> to create the <code>LoginContext</code>.</p> </div> <div class="paragraph"> <p>Let’s assume we have a JAAS login configuration file, <code>/WEB-INF/login.conf</code>, with the following contents:</p> </div> <div class="listingblock"> <div class="content"> <pre style="" class="prettyprint txt language-txt prettyprinted"><code><span class="typ">JAASTest</span><span class="pln"> </span><span class="pun">{</span><span class="pln"> sample</span><span class="pun">.</span><span class="typ">SampleLoginModule</span><span class="pln"> required</span><span class="pun">;</span><span class="pln"> </span><span class="pun">};</span></code></pre> </div> </div> <div class="paragraph"> <p>Like all Spring Security beans, the <code>JaasAuthenticationProvider</code> is configured via the application context. The following definitions would correspond to the above JAAS login configuration file:</p> </div> <div class="listingblock"> <div class="content"> <pre style="" class="prettyprint xml language-xml prettyprinted"><code><span class="pln"> </span><span class="tag"><bean</span><span class="pln"> </span><span class="atn">id</span><span class="pun">=</span><span class="atv">"jaasAuthenticationProvider"</span><span class="pln"> </span><span class="atn">class</span><span class="pun">=</span><span class="atv">"org.springframework.security.authentication.jaas.JaasAuthenticationProvider"</span><span class="tag">></span><span class="pln"> </span><span class="tag"><property</span><span class="pln"> </span><span class="atn">name</span><span class="pun">=</span><span class="atv">"loginConfig"</span><span class="pln"> </span><span class="atn">value</span><span class="pun">=</span><span class="atv">"/WEB-INF/login.conf"</span><span class="tag">/></span><span class="pln"> </span><span class="tag"><property</span><span class="pln"> </span><span class="atn">name</span><span class="pun">=</span><span class="atv">"loginContextName"</span><span class="pln"> </span><span class="atn">value</span><span class="pun">=</span><span class="atv">"JAASTest"</span><span class="tag">/></span><span class="pln"> </span><span class="tag"><property</span><span class="pln"> </span><span class="atn">name</span><span class="pun">=</span><span class="atv">"callbackHandlers"</span><span class="tag">></span><span class="pln"> </span><span class="tag"><list></span><span class="pln"> </span><span class="tag"><bean</span><span class="pln"> </span><span class="atn">class</span><span class="pun">=</span><span class="atv">"org.springframework.security.authentication.jaas.JaasNameCallbackHandler"</span><span class="tag">/></span><span class="pln"> </span><span class="tag"><bean</span><span class="pln"> </span><span class="atn">class</span><span class="pun">=</span><span class="atv">"org.springframework.security.authentication.jaas.JaasPasswordCallbackHandler"</span><span class="tag">/></span><span class="pln"> </span><span class="tag"></list></span><span class="pln"> </span><span class="tag"></property></span><span class="pln"> </span><span class="tag"><property</span><span class="pln"> </span><span class="atn">name</span><span class="pun">=</span><span class="atv">"authorityGranters"</span><span class="tag">></span><span class="pln"> </span><span class="tag"><list></span><span class="pln"> </span><span class="tag"><bean</span><span class="pln"> </span><span class="atn">class</span><span class="pun">=</span><span class="atv">"org.springframework.security.authentication.jaas.TestAuthorityGranter"</span><span class="tag">/></span><span class="pln"> </span><span class="tag"></list></span><span class="pln"> </span><span class="tag"></property></span><span class="pln"> </span><span class="tag"></bean></span></code></pre> </div> </div> </div> <div class="sect2"> <h3 id="jaas-apiprovision"><a class="anchor" href="#jaas-apiprovision"></a>5.5. Running as a Subject</h3> <div class="paragraph"> <p>If configured, the <code>JaasApiIntegrationFilter</code> will attempt to run as the <code>Subject</code> on the <code>JaasAuthenticationToken</code>. This means that the <code>Subject</code> can be accessed using:</p> </div> <div class="listingblock"> <div class="content"> <pre style="" class="prettyprint java language-java prettyprinted"><code><span class="typ">Subject</span><span class="pln"> subject </span><span class="pun">=</span><span class="pln"> </span><span class="typ">Subject</span><span class="pun">.</span><span class="pln">getSubject</span><span class="pun">(</span><span class="typ">AccessController</span><span class="pun">.</span><span class="pln">getContext</span><span class="pun">());</span></code></pre> </div> </div> <div class="paragraph"> <p>This integration can easily be configured using the <a href="#nsa-http-jaas-api-provision">jaas-api-provision</a> attribute. This feature is useful when integrating with legacy or external API’s that rely on the JAAS Subject being populated.</p> </div> </div> </div> </div> <div class="sect1"> <h2 id="cas"><a class="anchor" href="#cas"></a>6. CAS Authentication</h2> <div class="sectionbody"> <div class="sect2"> <h3 id="cas-overview"><a class="anchor" href="#cas-overview"></a>6.1. Overview</h3> <div class="paragraph"> <p>JA-SIG produces an enterprise-wide single sign on system known as CAS. Unlike other initiatives, JA-SIG’s Central Authentication Service is open source, widely used, simple to understand, platform independent, and supports proxy capabilities. Spring Security fully supports CAS, and provides an easy migration path from single-application deployments of Spring Security through to multiple-application deployments secured by an enterprise-wide CAS server.</p> </div> <div class="paragraph"> <p>You can learn more about CAS at <a href="http://www.ja-sig.org/cas">http://www.ja-sig.org/cas</a>. You will also need to visit this site to download the CAS Server files.</p> </div> </div> <div class="sect2"> <h3 id="cas-how-it-works"><a class="anchor" href="#cas-how-it-works"></a>6.2. How CAS Works</h3> <div class="paragraph"> <p>Whilst the CAS web site contains documents that detail the architecture of CAS, we present the general overview again here within the context of Spring Security. Spring Security 3.x supports CAS 3. At the time of writing, the CAS server was at version 3.4.</p> </div> <div class="paragraph"> <p>Somewhere in your enterprise you will need to setup a CAS server. The CAS server is simply a standard WAR file, so there isn’t anything difficult about setting up your server. Inside the WAR file you will customise the login and other single sign on pages displayed to users.</p> </div> <div class="paragraph"> <p>When deploying a CAS 3.4 server, you will also need to specify an <code>AuthenticationHandler</code> in the <code>deployerConfigContext.xml</code> included with CAS. The <code>AuthenticationHandler</code> has a simple method that returns a boolean as to whether a given set of Credentials is valid. Your <code>AuthenticationHandler</code> implementation will need to link into some type of backend authentication repository, such as an LDAP server or database. CAS itself includes numerous <code>AuthenticationHandler</code> s out of the box to assist with this. When you download and deploy the server war file, it is set up to successfully authenticate users who enter a password matching their username, which is useful for testing.</p> </div> <div class="paragraph"> <p>Apart from the CAS server itself, the other key players are of course the secure web applications deployed throughout your enterprise. These web applications are known as "services". There are three types of services. Those that authenticate service tickets, those that can obtain proxy tickets, and those that authenticate proxy tickets. Authenticating a proxy ticket differs because the list of proxies must be validated and often times a proxy ticket can be reused.</p> </div> <div class="sect3"> <h4 id="cas-sequence"><a class="anchor" href="#cas-sequence"></a>6.2.1. Spring Security and CAS Interaction Sequence</h4> <div class="paragraph"> <p>The basic interaction between a web browser, CAS server and a Spring Security-secured service is as follows:</p> </div> <div class="ulist"> <ul> <li> <p>The web user is browsing the service’s public pages. CAS or Spring Security is not involved.</p> </li> <li> <p>The user eventually requests a page that is either secure or one of the beans it uses is secure. Spring Security’s <code>ExceptionTranslationFilter</code> will detect the <code>AccessDeniedException</code> or <code>AuthenticationException</code>.</p> </li> <li> <p>Because the user’s <code>Authentication</code> object (or lack thereof) caused an <code>AuthenticationException</code>, the <code>ExceptionTranslationFilter</code> will call the configured <code>AuthenticationEntryPoint</code>. If using CAS, this will be the <code>CasAuthenticationEntryPoint</code> class.</p> </li> <li> <p>The <code>CasAuthenticationEntryPoint</code> will redirect the user’s browser to the CAS server. It will also indicate a <code>service</code> parameter, which is the callback URL for the Spring Security service (your application). For example, the URL to which the browser is redirected might be <a href="https://my.company.com/cas/login?service=https%3A%2F%2Fserver3.company.com%2Fwebapp%2Fj_spring_cas_security_check">https://my.company.com/cas/login?service=https%3A%2F%2Fserver3.company.com%2Fwebapp%2Fj_spring_cas_security_check</a>.</p> </li> <li> <p>After the user’s browser redirects to CAS, they will be prompted for their username and password. If the user presents a session cookie which indicates they’ve previously logged on, they will not be prompted to login again (there is an exception to this procedure, which we’ll cover later). CAS will use the <code>PasswordHandler</code> (or <code>AuthenticationHandler</code> if using CAS 3.0) discussed above to decide whether the username and password is valid.</p> </li> <li> <p>Upon successful login, CAS will redirect the user’s browser back to the original service. It will also include a <code>ticket</code> parameter, which is an opaque string representing the "service ticket". Continuing our earlier example, the URL the browser is redirected to might be <a href="https://server3.company.com/webapp/j_spring_cas_security_check?ticket=ST-0-ER94xMJmn6pha35CQRoZ">https://server3.company.com/webapp/j_spring_cas_security_check?ticket=ST-0-ER94xMJmn6pha35CQRoZ</a>.</p> </li> <li> <p>Back in the service web application, the <code>CasAuthenticationFilter</code> is always listening for requests to <code>/j_spring_cas_security_check</code> (this is configurable, but we’ll use the defaults in this introduction). The processing filter will construct a <code>UsernamePasswordAuthenticationToken</code> representing the service ticket. The principal will be equal to <code>CasAuthenticationFilter.CAS_STATEFUL_IDENTIFIER</code>, whilst the credentials will be the service ticket opaque value. This authentication request will then be handed to the configured <code>AuthenticationManager</code>.</p> </li> <li> <p>The <code>AuthenticationManager</code> implementation will be the <code>ProviderManager</code>, which is in turn configured with the <code>CasAuthenticationProvider</code>. The <code>CasAuthenticationProvider</code> only responds to <code>UsernamePasswordAuthenticationToken</code> s containing the CAS-specific principal (such as <code>CasAuthenticationFilter.CAS_STATEFUL_IDENTIFIER</code>) and <code>CasAuthenticationToken</code> s (discussed later).</p> </li> <li> <p><code>CasAuthenticationProvider</code> will validate the service ticket using a <code>TicketValidator</code> implementation. This will typically be a <code>Cas20ServiceTicketValidator</code> which is one of the classes included in the CAS client library. In the event the application needs to validate proxy tickets, the <code>Cas20ProxyTicketValidator</code> is used. The <code>TicketValidator</code> makes an HTTPS request to the CAS server in order to validate the service ticket. It may also include a proxy callback URL, which is included in this example: <a href="https://my.company.com/cas/proxyValidate?service=https%3A%2F%2Fserver3.company.com%2Fwebapp%2Fj_spring_cas_security_check&ticket=ST-0-ER94xMJmn6pha35CQRoZ&pgtUrl=https://server3.company.com/webapp/j_spring_cas_security_proxyreceptor">https://my.company.com/cas/proxyValidate?service=https%3A%2F%2Fserver3.company.com%2Fwebapp%2Fj_spring_cas_security_check&ticket=ST-0-ER94xMJmn6pha35CQRoZ&pgtUrl=https://server3.company.com/webapp/j_spring_cas_security_proxyreceptor</a>.</p> </li> <li> <p>Back on the CAS server, the validation request will be received. If the presented service ticket matches the service URL the ticket was issued to, CAS will provide an affirmative response in XML indicating the username. If any proxy was involved in the authentication (discussed below), the list of proxies is also included in the XML response.</p> </li> <li> <p>[OPTIONAL] If the request to the CAS validation service included the proxy callback URL (in the <code>pgtUrl</code> parameter), CAS will include a <code>pgtIou</code> string in the XML response. This <code>pgtIou</code> represents a proxy-granting ticket IOU. The CAS server will then create its own HTTPS connection back to the <code>pgtUrl</code>. This is to mutually authenticate the CAS server and the claimed service URL. The HTTPS connection will be used to send a proxy granting ticket to the original web application. For example, <a href="https://server3.company.com/webapp/j_spring_cas_security_proxyreceptor?pgtIou=PGTIOU-0-R0zlgrl4pdAQwBvJWO3vnNpevwqStbSGcq3vKB2SqSFFRnjPHt&pgtId=PGT-1-si9YkkHLrtACBo64rmsi3v2nf7cpCResXg5MpESZFArbaZiOKH">https://server3.company.com/webapp/j_spring_cas_security_proxyreceptor?pgtIou=PGTIOU-0-R0zlgrl4pdAQwBvJWO3vnNpevwqStbSGcq3vKB2SqSFFRnjPHt&pgtId=PGT-1-si9YkkHLrtACBo64rmsi3v2nf7cpCResXg5MpESZFArbaZiOKH</a>.</p> </li> <li> <p>The <code>Cas20TicketValidator</code> will parse the XML received from the CAS server. It will return to the <code>CasAuthenticationProvider</code> a <code>TicketResponse</code>, which includes the username (mandatory), proxy list (if any were involved), and proxy-granting ticket IOU (if the proxy callback was requested).</p> </li> <li> <p>Next <code>CasAuthenticationProvider</code> will call a configured <code>CasProxyDecider</code>. The <code>CasProxyDecider</code> indicates whether the proxy list in the <code>TicketResponse</code> is acceptable to the service. Several implementations are provided with Spring Security: <code>RejectProxyTickets</code>, <code>AcceptAnyCasProxy</code> and <code>NamedCasProxyDecider</code>. These names are largely self-explanatory, except <code>NamedCasProxyDecider</code> which allows a <code>List</code> of trusted proxies to be provided.</p> </li> <li> <p><code>CasAuthenticationProvider</code> will next request a <code>AuthenticationUserDetailsService</code> to load the <code>GrantedAuthority</code> objects that apply to the user contained in the <code>Assertion</code>.</p> </li> <li> <p>If there were no problems, <code>CasAuthenticationProvider</code> constructs a <code>CasAuthenticationToken</code> including the details contained in the <code>TicketResponse</code> and the `GrantedAuthority`s.</p> </li> <li> <p>Control then returns to <code>CasAuthenticationFilter</code>, which places the created <code>CasAuthenticationToken</code> in the security context.</p> </li> <li> <p>The user’s browser is redirected to the original page that caused the <code>AuthenticationException</code> (or a <a href="#form-login-flow-handling">custom destination</a> depending on the configuration).</p> </li> </ul> </div> <div class="paragraph"> <p>It’s good that you’re still here! Let’s now look at how this is configured</p> </div> </div> </div> <div class="sect2"> <h3 id="cas-client"><a class="anchor" href="#cas-client"></a>6.3. Configuration of CAS Client</h3> <div class="paragraph"> <p>The web application side of CAS is made easy due to Spring Security. It is assumed you already know the basics of using Spring Security, so these are not covered again below. We’ll assume a namespace based configuration is being used and add in the CAS beans as required. Each section builds upon the previous section. A full<a href="#cas-sample">CAS sample application</a> can be found in the Spring Security Samples.</p> </div> <div class="sect3"> <h4 id="cas-st"><a class="anchor" href="#cas-st"></a>6.3.1. Service Ticket Authentication</h4> <div class="paragraph"> <p>This section describes how to setup Spring Security to authenticate Service Tickets. Often times this is all a web application requires. You will need to add a <code>ServiceProperties</code> bean to your application context. This represents your CAS service:</p> </div> <div class="listingblock"> <div class="content"> <pre style="" class="prettyprint xml language-xml prettyprinted"><code><span class="tag"><bean</span><span class="pln"> </span><span class="atn">id</span><span class="pun">=</span><span class="atv">"serviceProperties"</span><span class="pln"> </span><span class="atn">class</span><span class="pun">=</span><span class="atv">"org.springframework.security.cas.ServiceProperties"</span><span class="tag">></span><span class="pln"> </span><span class="tag"><property</span><span class="pln"> </span><span class="atn">name</span><span class="pun">=</span><span class="atv">"service"</span><span class="pln"> </span><span class="atn">value</span><span class="pun">=</span><span class="atv">"https://localhost:8443/cas-sample/j_spring_cas_security_check"</span><span class="tag">/></span><span class="pln"> </span><span class="tag"><property</span><span class="pln"> </span><span class="atn">name</span><span class="pun">=</span><span class="atv">"sendRenew"</span><span class="pln"> </span><span class="atn">value</span><span class="pun">=</span><span class="atv">"false"</span><span class="tag">/></span><span class="pln"> </span><span class="tag"></bean></span></code></pre> </div> </div> <div class="paragraph"> <p>The <code>service</code> must equal a URL that will be monitored by the <code>CasAuthenticationFilter</code>. The <code>sendRenew</code> defaults to false, but should be set to true if your application is particularly sensitive. What this parameter does is tell the CAS login service that a single sign on login is unacceptable. Instead, the user will need to re-enter their username and password in order to gain access to the service.</p> </div> <div class="paragraph"> <p>The following beans should be configured to commence the CAS authentication process (assuming you’re using a namespace configuration):</p> </div> <div class="listingblock"> <div class="content"> <pre style="" class="prettyprint xml language-xml prettyprinted"><code><span class="tag"><security:http</span><span class="pln"> </span><span class="atn">entry-point-ref</span><span class="pun">=</span><span class="atv">"casEntryPoint"</span><span class="tag">></span><span class="pln"> ... </span><span class="tag"><security:custom-filter</span><span class="pln"> </span><span class="atn">position</span><span class="pun">=</span><span class="atv">"CAS_FILTER"</span><span class="pln"> </span><span class="atn">ref</span><span class="pun">=</span><span class="atv">"casFilter"</span><span class="pln"> </span><span class="tag">/></span><span class="pln"> </span><span class="tag"></security:http></span><span class="pln"> </span><span class="tag"><bean</span><span class="pln"> </span><span class="atn">id</span><span class="pun">=</span><span class="atv">"casFilter"</span><span class="pln"> </span><span class="atn">class</span><span class="pun">=</span><span class="atv">"org.springframework.security.cas.web.CasAuthenticationFilter"</span><span class="tag">></span><span class="pln"> </span><span class="tag"><property</span><span class="pln"> </span><span class="atn">name</span><span class="pun">=</span><span class="atv">"authenticationManager"</span><span class="pln"> </span><span class="atn">ref</span><span class="pun">=</span><span class="atv">"authenticationManager"</span><span class="tag">/></span><span class="pln"> </span><span class="tag"></bean></span><span class="pln"> </span><span class="tag"><bean</span><span class="pln"> </span><span class="atn">id</span><span class="pun">=</span><span class="atv">"casEntryPoint"</span><span class="pln"> </span><span class="atn">class</span><span class="pun">=</span><span class="atv">"org.springframework.security.cas.web.CasAuthenticationEntryPoint"</span><span class="tag">></span><span class="pln"> </span><span class="tag"><property</span><span class="pln"> </span><span class="atn">name</span><span class="pun">=</span><span class="atv">"loginUrl"</span><span class="pln"> </span><span class="atn">value</span><span class="pun">=</span><span class="atv">"https://localhost:9443/cas/login"</span><span class="tag">/></span><span class="pln"> </span><span class="tag"><property</span><span class="pln"> </span><span class="atn">name</span><span class="pun">=</span><span class="atv">"serviceProperties"</span><span class="pln"> </span><span class="atn">ref</span><span class="pun">=</span><span class="atv">"serviceProperties"</span><span class="tag">/></span><span class="pln"> </span><span class="tag"></bean></span></code></pre> </div> </div> <div class="paragraph"> <p>For CAS to operate, the <code>ExceptionTranslationFilter</code> must have its <code>authenticationEntryPoint</code> property set to the <code>CasAuthenticationEntryPoint</code> bean. This can easily be done using <a href="#ns-entry-point-ref">entry-point-ref</a> as is done in the example above. The <code>CasAuthenticationEntryPoint</code> must refer to the <code>ServiceProperties</code> bean (discussed above), which provides the URL to the enterprise’s CAS login server. This is where the user’s browser will be redirected.</p> </div> <div class="paragraph"> <p>The <code>CasAuthenticationFilter</code> has very similar properties to the <code>UsernamePasswordAuthenticationFilter</code> (used for form-based logins). You can use these properties to customize things like behavior for authentication success and failure.</p> </div> <div class="paragraph"> <p>Next you need to add a <code>CasAuthenticationProvider</code> and its collaborators:</p> </div> <div class="listingblock"> <div class="content"> <pre style="" class="prettyprint xml language-xml prettyprinted"><code><span class="tag"><security:authentication-manager</span><span class="pln"> </span><span class="atn">alias</span><span class="pun">=</span><span class="atv">"authenticationManager"</span><span class="tag">></span><span class="pln"> </span><span class="tag"><security:authentication-provider</span><span class="pln"> </span><span class="atn">ref</span><span class="pun">=</span><span class="atv">"casAuthenticationProvider"</span><span class="pln"> </span><span class="tag">/></span><span class="pln"> </span><span class="tag"></security:authentication-manager></span><span class="pln"> </span><span class="tag"><bean</span><span class="pln"> </span><span class="atn">id</span><span class="pun">=</span><span class="atv">"casAuthenticationProvider"</span><span class="pln"> </span><span class="atn">class</span><span class="pun">=</span><span class="atv">"org.springframework.security.cas.authentication.CasAuthenticationProvider"</span><span class="tag">></span><span class="pln"> </span><span class="tag"><property</span><span class="pln"> </span><span class="atn">name</span><span class="pun">=</span><span class="atv">"authenticationUserDetailsService"</span><span class="tag">></span><span class="pln"> </span><span class="tag"><bean</span><span class="pln"> </span><span class="atn">class</span><span class="pun">=</span><span class="atv">"org.springframework.security.core.userdetails.UserDetailsByNameServiceWrapper"</span><span class="tag">></span><span class="pln"> </span><span class="tag"><constructor-arg</span><span class="pln"> </span><span class="atn">ref</span><span class="pun">=</span><span class="atv">"userService"</span><span class="pln"> </span><span class="tag">/></span><span class="pln"> </span><span class="tag"></bean></span><span class="pln"> </span><span class="tag"></property></span><span class="pln"> </span><span class="tag"><property</span><span class="pln"> </span><span class="atn">name</span><span class="pun">=</span><span class="atv">"serviceProperties"</span><span class="pln"> </span><span class="atn">ref</span><span class="pun">=</span><span class="atv">"serviceProperties"</span><span class="pln"> </span><span class="tag">/></span><span class="pln"> </span><span class="tag"><property</span><span class="pln"> </span><span class="atn">name</span><span class="pun">=</span><span class="atv">"ticketValidator"</span><span class="tag">></span><span class="pln"> </span><span class="tag"><bean</span><span class="pln"> </span><span class="atn">class</span><span class="pun">=</span><span class="atv">"org.jasig.cas.client.validation.Cas20ServiceTicketValidator"</span><span class="tag">></span><span class="pln"> </span><span class="tag"><constructor-arg</span><span class="pln"> </span><span class="atn">index</span><span class="pun">=</span><span class="atv">"0"</span><span class="pln"> </span><span class="atn">value</span><span class="pun">=</span><span class="atv">"https://localhost:9443/cas"</span><span class="pln"> </span><span class="tag">/></span><span class="pln"> </span><span class="tag"></bean></span><span class="pln"> </span><span class="tag"></property></span><span class="pln"> </span><span class="tag"><property</span><span class="pln"> </span><span class="atn">name</span><span class="pun">=</span><span class="atv">"key"</span><span class="pln"> </span><span class="atn">value</span><span class="pun">=</span><span class="atv">"an_id_for_this_auth_provider_only"</span><span class="tag">/></span><span class="pln"> </span><span class="tag"></bean></span><span class="pln"> </span><span class="tag"><security:user-service</span><span class="pln"> </span><span class="atn">id</span><span class="pun">=</span><span class="atv">"userService"</span><span class="tag">></span><span class="pln"> </span><span class="tag"><security:user</span><span class="pln"> </span><span class="atn">name</span><span class="pun">=</span><span class="atv">"joe"</span><span class="pln"> </span><span class="atn">password</span><span class="pun">=</span><span class="atv">"joe"</span><span class="pln"> </span><span class="atn">authorities</span><span class="pun">=</span><span class="atv">"ROLE_USER"</span><span class="pln"> </span><span class="tag">/></span><span class="pln"> ... </span><span class="tag"></security:user-service></span></code></pre> </div> </div> <div class="paragraph"> <p>The <code>CasAuthenticationProvider</code> uses a <code>UserDetailsService</code> instance to load the authorities for a user, once they have been authenticated by CAS. We’ve shown a simple in-memory setup here. Note that the <code>CasAuthenticationProvider</code> does not actually use the password for authentication, but it does use the authorities.</p> </div> <div class="paragraph"> <p>The beans are all reasonably self-explanatory if you refer back to the <a href="#cas-how-it-works">How CAS Works</a> section.</p> </div> <div class="paragraph"> <p>This completes the most basic configuration for CAS. If you haven’t made any mistakes, your web application should happily work within the framework of CAS single sign on. No other parts of Spring Security need to be concerned about the fact CAS handled authentication. In the following sections we will discuss some (optional) more advanced configurations.</p> </div> </div> <div class="sect3"> <h4 id="cas-singlelogout"><a class="anchor" href="#cas-singlelogout"></a>6.3.2. Single Logout</h4> <div class="paragraph"> <p>The CAS protocol supports Single Logout and can be easily added to your Spring Security configuration. Below are updates to the Spring Security configuration that handle Single Logout</p> </div> <div class="listingblock"> <div class="content"> <pre style="" class="prettyprint xml language-xml prettyprinted"><code><span class="tag"><security:http</span><span class="pln"> </span><span class="atn">entry-point-ref</span><span class="pun">=</span><span class="atv">"casEntryPoint"</span><span class="tag">></span><span class="pln"> ... </span><span class="tag"><security:logout</span><span class="pln"> </span><span class="atn">logout-success-url</span><span class="pun">=</span><span class="atv">"/cas-logout.jsp"</span><span class="tag">/></span><span class="pln"> </span><span class="tag"><security:custom-filter</span><span class="pln"> </span><span class="atn">ref</span><span class="pun">=</span><span class="atv">"requestSingleLogoutFilter"</span><span class="pln"> </span><span class="atn">before</span><span class="pun">=</span><span class="atv">"LOGOUT_FILTER"</span><span class="tag">/></span><span class="pln"> </span><span class="tag"><security:custom-filter</span><span class="pln"> </span><span class="atn">ref</span><span class="pun">=</span><span class="atv">"singleLogoutFilter"</span><span class="pln"> </span><span class="atn">before</span><span class="pun">=</span><span class="atv">"CAS_FILTER"</span><span class="tag">/></span><span class="pln"> </span><span class="tag"></security:http></span><span class="pln"> </span><span class="com"><!-- This filter handles a Single Logout Request from the CAS Server --></span><span class="pln"> </span><span class="tag"><bean</span><span class="pln"> </span><span class="atn">id</span><span class="pun">=</span><span class="atv">"singleLogoutFilter"</span><span class="pln"> </span><span class="atn">class</span><span class="pun">=</span><span class="atv">"org.jasig.cas.client.session.SingleSignOutFilter"</span><span class="tag">/></span><span class="pln"> </span><span class="com"><!-- This filter redirects to the CAS Server to signal Single Logout should be performed --></span><span class="pln"> </span><span class="tag"><bean</span><span class="pln"> </span><span class="atn">id</span><span class="pun">=</span><span class="atv">"requestSingleLogoutFilter"</span><span class="pln"> </span><span class="atn">class</span><span class="pun">=</span><span class="atv">"org.springframework.security.web.authentication.logout.LogoutFilter"</span><span class="tag">></span><span class="pln"> </span><span class="tag"><constructor-arg</span><span class="pln"> </span><span class="atn">value</span><span class="pun">=</span><span class="atv">"https://localhost:9443/cas/logout"</span><span class="tag">/></span><span class="pln"> </span><span class="tag"><constructor-arg></span><span class="pln"> </span><span class="tag"><bean</span><span class="pln"> </span><span class="atn">class</span><span class="pun">=</span><span class="pln"> </span><span class="atv">"org.springframework.security.web.authentication.logout.SecurityContextLogoutHandler"</span><span class="tag">/></span><span class="pln"> </span><span class="tag"></constructor-arg></span><span class="pln"> </span><span class="tag"><property</span><span class="pln"> </span><span class="atn">name</span><span class="pun">=</span><span class="atv">"filterProcessesUrl"</span><span class="pln"> </span><span class="atn">value</span><span class="pun">=</span><span class="atv">"/j_spring_cas_security_logout"</span><span class="tag">/></span><span class="pln"> </span><span class="tag"></bean></span></code></pre> </div> </div> <div class="paragraph"> <p>The <code>logout</code> element logs the user out of the local application, but does not terminate the session with the CAS server or any other applications that have been logged into. The <code>requestSingleLogoutFilter</code> filter will allow the url of <code>/spring_security_cas_logout</code> to be requested to redirect the application to the configured CAS Server logout url. Then the CAS Server will send a Single Logout request to all the services that were signed into. The <code>singleLogoutFilter</code> handles the Single Logout request by looking up the <code>HttpSession</code> in a static <code>Map</code> and then invalidating it.</p> </div> <div class="paragraph"> <p>It might be confusing why both the <code>logout</code> element and the <code>singleLogoutFilter</code> are needed. It is considered best practice to logout locally first since the <code>SingleSignOutFilter</code> just stores the <code>HttpSession</code> in a static <code>Map</code> in order to call invalidate on it. With the configuration above, the flow of logout would be:</p> </div> <div class="ulist"> <ul> <li> <p>The user requests <code>/j_spring_security_logout</code> which would log the user out of the local application and send the user to the logout success page.</p> </li> <li> <p>The logout success page, <code>/cas-logout.jsp</code>, should instruct the user to click a link pointing to <code>/j_spring_cas_security_logout</code> in order to logout out of all applications.</p> </li> <li> <p>When the user clicks the link, the user is redirected to the CAS single logout URL (<a href="https://localhost:9443/cas/logout">https://localhost:9443/cas/logout</a>).</p> </li> <li> <p>On the CAS Server side, the CAS single logout URL then submits single logout requests to all the CAS Services. On the CAS Service side, JASIG’s <code>SingleSignOutFilter</code> processes the logout request by invaliditing the original session.</p> </li> </ul> </div> <div class="paragraph"> <p>The next step is to add the following to your web.xml</p> </div> <div class="listingblock"> <div class="content"> <pre style="" class="prettyprint xml language-xml prettyprinted"><code><span class="tag"><filter></span><span class="pln"> </span><span class="tag"><filter-name></span><span class="pln">characterEncodingFilter</span><span class="tag"></filter-name></span><span class="pln"> </span><span class="tag"><filter-class></span><span class="pln"> org.springframework.web.filter.CharacterEncodingFilter </span><span class="tag"></filter-class></span><span class="pln"> </span><span class="tag"><init-param></span><span class="pln"> </span><span class="tag"><param-name></span><span class="pln">encoding</span><span class="tag"></param-name></span><span class="pln"> </span><span class="tag"><param-value></span><span class="pln">UTF-8</span><span class="tag"></param-value></span><span class="pln"> </span><span class="tag"></init-param></span><span class="pln"> </span><span class="tag"></filter></span><span class="pln"> </span><span class="tag"><filter-mapping></span><span class="pln"> </span><span class="tag"><filter-name></span><span class="pln">characterEncodingFilter</span><span class="tag"></filter-name></span><span class="pln"> </span><span class="tag"><url-pattern></span><span class="pln">/*</span><span class="tag"></url-pattern></span><span class="pln"> </span><span class="tag"></filter-mapping></span><span class="pln"> </span><span class="tag"><listener></span><span class="pln"> </span><span class="tag"><listener-class></span><span class="pln"> org.jasig.cas.client.session.SingleSignOutHttpSessionListener </span><span class="tag"></listener-class></span><span class="pln"> </span><span class="tag"></listener></span></code></pre> </div> </div> <div class="paragraph"> <p>When using the SingleSignOutFilter you might encounter some encoding issues. Therefore it is recommended to add the <code>CharacterEncodingFilter</code> to ensure that the character encoding is correct when using the <code>SingleSignOutFilter</code>. Again, refer to JASIG’s documentation for details. The <code>SingleSignOutHttpSessionListener</code> ensures that when an <code>HttpSession</code> expires, the mapping used for single logout is removed.</p> </div> </div> <div class="sect3"> <h4 id="cas-pt-client"><a class="anchor" href="#cas-pt-client"></a>6.3.3. Authenticating to a Stateless Service with CAS</h4> <div class="paragraph"> <p>This section describes how to authenticate to a service using CAS. In other words, this section discusses how to setup a client that uses a service that authenticates with CAS. The next section describes how to setup a stateless service to Authenticate using CAS.</p> </div> <div class="sect4"> <h5 id="cas-pt-client-config"><a class="anchor" href="#cas-pt-client-config"></a>Configuring CAS to Obtain Proxy Granting Tickets</h5> <div class="paragraph"> <p>In order to authenticate to a stateless service, the application needs to obtain a proxy granting ticket (PGT). This section describes how to configure Spring Security to obtain a PGT building upon thencas-st[Service Ticket Authentication] configuration.</p> </div> <div class="paragraph"> <p>The first step is to include a <code>ProxyGrantingTicketStorage</code> in your Spring Security configuration. This is used to store PGT’s that are obtained by the <code>CasAuthenticationFilter</code> so that they can be used to obtain proxy tickets. An example configuration is shown below</p> </div> <div class="listingblock"> <div class="content"> <pre style="" class="prettyprint xml language-xml prettyprinted"><code><span class="com"><!-- NOTE: In a real application you should not use an in memory implementation. You will also want to ensure to clean up expired tickets by calling ProxyGrantingTicketStorage.cleanup() --></span><span class="pln"> </span><span class="tag"><bean</span><span class="pln"> </span><span class="atn">id</span><span class="pun">=</span><span class="atv">"pgtStorage"</span><span class="pln"> </span><span class="atn">class</span><span class="pun">=</span><span class="atv">"org.jasig.cas.client.proxy.ProxyGrantingTicketStorageImpl"</span><span class="tag">/></span></code></pre> </div> </div> <div class="paragraph"> <p>The next step is to update the <code>CasAuthenticationProvider</code> to be able to obtain proxy tickets. To do this replace the <code>Cas20ServiceTicketValidator</code> with a <code>Cas20ProxyTicketValidator</code>. The <code>proxyCallbackUrl</code> should be set to a URL that the application will receive PGT’s at. Last, the configuration should also reference the <code>ProxyGrantingTicketStorage</code> so it can use a PGT to obtain proxy tickets. You can find an example of the configuration changes that should be made below.</p> </div> <div class="listingblock"> <div class="content"> <pre style="" class="prettyprint xml language-xml prettyprinted"><code><span class="tag"><bean</span><span class="pln"> </span><span class="atn">id</span><span class="pun">=</span><span class="atv">"casAuthenticationProvider"</span><span class="pln"> </span><span class="atn">class</span><span class="pun">=</span><span class="atv">"org.springframework.security.cas.authentication.CasAuthenticationProvider"</span><span class="tag">></span><span class="pln"> ... </span><span class="tag"><property</span><span class="pln"> </span><span class="atn">name</span><span class="pun">=</span><span class="atv">"ticketValidator"</span><span class="tag">></span><span class="pln"> </span><span class="tag"><bean</span><span class="pln"> </span><span class="atn">class</span><span class="pun">=</span><span class="atv">"org.jasig.cas.client.validation.Cas20ProxyTicketValidator"</span><span class="tag">></span><span class="pln"> </span><span class="tag"><constructor-arg</span><span class="pln"> </span><span class="atn">value</span><span class="pun">=</span><span class="atv">"https://localhost:9443/cas"</span><span class="tag">/></span><span class="pln"> </span><span class="tag"><property</span><span class="pln"> </span><span class="atn">name</span><span class="pun">=</span><span class="atv">"proxyCallbackUrl"</span><span class="pln"> </span><span class="atn">value</span><span class="pun">=</span><span class="atv">"https://localhost:8443/cas-sample/j_spring_cas_security_proxyreceptor"</span><span class="tag">/></span><span class="pln"> </span><span class="tag"><property</span><span class="pln"> </span><span class="atn">name</span><span class="pun">=</span><span class="atv">"proxyGrantingTicketStorage"</span><span class="pln"> </span><span class="atn">ref</span><span class="pun">=</span><span class="atv">"pgtStorage"</span><span class="tag">/></span><span class="pln"> </span><span class="tag"></bean></span><span class="pln"> </span><span class="tag"></property></span><span class="pln"> </span><span class="tag"></bean></span></code></pre> </div> </div> <div class="paragraph"> <p>The last step is to update the <code>CasAuthenticationFilter</code> to accept PGT and to store them in the <code>ProxyGrantingTicketStorage</code>. It is important the the <code>proxyReceptorUrl</code> matches the <code>proxyCallbackUrl</code> of the <code>Cas20ProxyTicketValidator</code>. An example configuration is shown below.</p> </div> <div class="listingblock"> <div class="content"> <pre style="" class="prettyprint xml language-xml prettyprinted"><code><span class="pln"> </span><span class="tag"><bean</span><span class="pln"> </span><span class="atn">id</span><span class="pun">=</span><span class="atv">"casFilter"</span><span class="pln"> </span><span class="atn">class</span><span class="pun">=</span><span class="atv">"org.springframework.security.cas.web.CasAuthenticationFilter"</span><span class="tag">></span><span class="pln"> ... </span><span class="tag"><property</span><span class="pln"> </span><span class="atn">name</span><span class="pun">=</span><span class="atv">"proxyGrantingTicketStorage"</span><span class="pln"> </span><span class="atn">ref</span><span class="pun">=</span><span class="atv">"pgtStorage"</span><span class="tag">/></span><span class="pln"> </span><span class="tag"><property</span><span class="pln"> </span><span class="atn">name</span><span class="pun">=</span><span class="atv">"proxyReceptorUrl"</span><span class="pln"> </span><span class="atn">value</span><span class="pun">=</span><span class="atv">"/j_spring_cas_security_proxyreceptor"</span><span class="tag">/></span><span class="pln"> </span><span class="tag"></bean></span></code></pre> </div> </div> </div> <div class="sect4"> <h5 id="cas-pt-client-sample"><a class="anchor" href="#cas-pt-client-sample"></a>Calling a Stateless Service Using a Proxy Ticket</h5> <div class="paragraph"> <p>Now that Spring Security obtains PGTs, you can use them to create proxy tickets which can be used to authenticate to a stateless service. The <a href="#cas-sample">CAS sample application</a> contains a working example in the <code>ProxyTicketSampleServlet</code>. Example code can be found below:</p> </div> <div class="listingblock"> <div class="content"> <pre style="" class="prettyprint java language-java prettyprinted"><code><span class="kwd">protected</span><span class="pln"> </span><span class="kwd">void</span><span class="pln"> doGet</span><span class="pun">(</span><span class="typ">HttpServletRequest</span><span class="pln"> request</span><span class="pun">,</span><span class="pln"> </span><span class="typ">HttpServletResponse</span><span class="pln"> response</span><span class="pun">)</span><span class="pln"> </span><span class="kwd">throws</span><span class="pln"> </span><span class="typ">ServletException</span><span class="pun">,</span><span class="pln"> </span><span class="typ">IOException</span><span class="pln"> </span><span class="pun">{</span><span class="pln"> </span><span class="com">// NOTE: The CasAuthenticationToken can also be obtained using</span><span class="pln"> </span><span class="com">// SecurityContextHolder.getContext().getAuthentication()</span><span class="pln"> </span><span class="kwd">final</span><span class="pln"> </span><span class="typ">CasAuthenticationToken</span><span class="pln"> token </span><span class="pun">=</span><span class="pln"> </span><span class="pun">(</span><span class="typ">CasAuthenticationToken</span><span class="pun">)</span><span class="pln"> request</span><span class="pun">.</span><span class="pln">getUserPrincipal</span><span class="pun">();</span><span class="pln"> </span><span class="com">// proxyTicket could be reused to make calls to the CAS service even if the</span><span class="pln"> </span><span class="com">// target url differs</span><span class="pln"> </span><span class="kwd">final</span><span class="pln"> </span><span class="typ">String</span><span class="pln"> proxyTicket </span><span class="pun">=</span><span class="pln"> token</span><span class="pun">.</span><span class="pln">getAssertion</span><span class="pun">().</span><span class="pln">getPrincipal</span><span class="pun">().</span><span class="pln">getProxyTicketFor</span><span class="pun">(</span><span class="pln">targetUrl</span><span class="pun">);</span><span class="pln"> </span><span class="com">// Make a remote call using the proxy ticket</span><span class="pln"> </span><span class="kwd">final</span><span class="pln"> </span><span class="typ">String</span><span class="pln"> serviceUrl </span><span class="pun">=</span><span class="pln"> targetUrl</span><span class="pun">+</span><span class="str">"?ticket="</span><span class="pun">+</span><span class="typ">URLEncoder</span><span class="pun">.</span><span class="pln">encode</span><span class="pun">(</span><span class="pln">proxyTicket</span><span class="pun">,</span><span class="pln"> </span><span class="str">"UTF-8"</span><span class="pun">);</span><span class="pln"> </span><span class="typ">String</span><span class="pln"> proxyResponse </span><span class="pun">=</span><span class="pln"> </span><span class="typ">CommonUtils</span><span class="pun">.</span><span class="pln">getResponseFromServer</span><span class="pun">(</span><span class="pln">serviceUrl</span><span class="pun">,</span><span class="pln"> </span><span class="str">"UTF-8"</span><span class="pun">);</span><span class="pln"> </span><span class="pun">...</span><span class="pln"> </span><span class="pun">}</span></code></pre> </div> </div> </div> </div> <div class="sect3"> <h4 id="cas-pt"><a class="anchor" href="#cas-pt"></a>6.3.4. Proxy Ticket Authentication</h4> <div class="paragraph"> <p>The <code>CasAuthenticationProvider</code> distinguishes between stateful and stateless clients. A stateful client is considered any that submits to the <code>filterProcessUrl</code> of the <code>CasAuthenticationFilter</code>. A stateless client is any that presents an authentication request to <code>CasAuthenticationFilter</code> on a URL other than the <code>filterProcessUrl</code>.</p> </div> <div class="paragraph"> <p>Because remoting protocols have no way of presenting themselves within the context of an <code>HttpSession</code>, it isn’t possible to rely on the default practice of storing the security context in the session between requests. Furthermore, because the CAS server invalidates a ticket after it has been validated by the <code>TicketValidator</code>, presenting the same proxy ticket on subsequent requests will not work.</p> </div> <div class="paragraph"> <p>One obvious option is to not use CAS at all for remoting protocol clients. However, this would eliminate many of the desirable features of CAS. As a middle-ground, the <code>CasAuthenticationProvider</code> uses a <code>StatelessTicketCache</code>. This is used solely for stateless clients which use a principal equal to <code>CasAuthenticationFilter.CAS_STATELESS_IDENTIFIER</code>. What happens is the <code>CasAuthenticationProvider</code> will store the resulting <code>CasAuthenticationToken</code> in the <code>StatelessTicketCache</code>, keyed on the proxy ticket. Accordingly, remoting protocol clients can present the same proxy ticket and the <code>CasAuthenticationProvider</code> will not need to contact the CAS server for validation (aside from the first request). Once authenticated, the proxy ticket could be used for URLs other than the original target service.</p> </div> <div class="paragraph"> <p>This section builds upon the previous sections to accomodate proxy ticket authentication. The first step is to specify to authenticate all artifacts as shown below.</p> </div> <div class="listingblock"> <div class="content"> <pre style="" class="prettyprint xml language-xml prettyprinted"><code><span class="tag"><bean</span><span class="pln"> </span><span class="atn">id</span><span class="pun">=</span><span class="atv">"serviceProperties"</span><span class="pln"> </span><span class="atn">class</span><span class="pun">=</span><span class="atv">"org.springframework.security.cas.ServiceProperties"</span><span class="tag">></span><span class="pln"> ... </span><span class="tag"><property</span><span class="pln"> </span><span class="atn">name</span><span class="pun">=</span><span class="atv">"authenticateAllArtifacts"</span><span class="pln"> </span><span class="atn">value</span><span class="pun">=</span><span class="atv">"true"</span><span class="tag">/></span><span class="pln"> </span><span class="tag"></bean></span></code></pre> </div> </div> <div class="paragraph"> <p>The next step is to specify <code>serviceProperties</code> and the <code>authenticationDetailsSource</code> for the <code>CasAuthenticationFilter</code>. The <code>serviceProperties</code> property instructs the <code>CasAuthenticationFilter</code> to attempt to authenticate all artifacts instead of only ones present on the <code>filterProcessUrl</code>. The <code>ServiceAuthenticationDetailsSource</code> creates a <code>ServiceAuthenticationDetails</code> that ensures the current URL, based upon the <code>HttpServletRequest</code>, is used as the service URL when validating the ticket. The method for generating the service URL can be customized by injecting a custom <code>AuthenticationDetailsSource</code> that returns a custom <code>ServiceAuthenticationDetails</code>.</p> </div> <div class="listingblock"> <div class="content"> <pre style="" class="prettyprint xml language-xml prettyprinted"><code><span class="tag"><bean</span><span class="pln"> </span><span class="atn">id</span><span class="pun">=</span><span class="atv">"casFilter"</span><span class="pln"> </span><span class="atn">class</span><span class="pun">=</span><span class="atv">"org.springframework.security.cas.web.CasAuthenticationFilter"</span><span class="tag">></span><span class="pln"> ... </span><span class="tag"><property</span><span class="pln"> </span><span class="atn">name</span><span class="pun">=</span><span class="atv">"serviceProperties"</span><span class="pln"> </span><span class="atn">ref</span><span class="pun">=</span><span class="atv">"serviceProperties"</span><span class="tag">/></span><span class="pln"> </span><span class="tag"><property</span><span class="pln"> </span><span class="atn">name</span><span class="pun">=</span><span class="atv">"authenticationDetailsSource"</span><span class="tag">></span><span class="pln"> </span><span class="tag"><bean</span><span class="pln"> </span><span class="atn">class</span><span class="pun">=</span><span class="pln"> </span><span class="atv">"org.springframework.security.cas.web.authentication.ServiceAuthenticationDetailsSource"</span><span class="tag">></span><span class="pln"> </span><span class="tag"><constructor-arg</span><span class="pln"> </span><span class="atn">ref</span><span class="pun">=</span><span class="atv">"serviceProperties"</span><span class="tag">/></span><span class="pln"> </span><span class="tag"></bean></span><span class="pln"> </span><span class="tag"></property></span><span class="pln"> </span><span class="tag"></bean></span></code></pre> </div> </div> <div class="paragraph"> <p>You will also need to update the <code>CasAuthenticationProvider</code> to handle proxy tickets. To do this replace the <code>Cas20ServiceTicketValidator</code> with a <code>Cas20ProxyTicketValidator</code>. You will need to configure the <code>statelessTicketCache</code> and which proxies you want to accept. You can find an example of the updates required to accept all proxies below.</p> </div> <div class="listingblock"> <div class="content"> <pre style="" class="prettyprint xml language-xml prettyprinted"><code><span class="pln"> </span><span class="tag"><bean</span><span class="pln"> </span><span class="atn">id</span><span class="pun">=</span><span class="atv">"casAuthenticationProvider"</span><span class="pln"> </span><span class="atn">class</span><span class="pun">=</span><span class="atv">"org.springframework.security.cas.authentication.CasAuthenticationProvider"</span><span class="tag">></span><span class="pln"> ... </span><span class="tag"><property</span><span class="pln"> </span><span class="atn">name</span><span class="pun">=</span><span class="atv">"ticketValidator"</span><span class="tag">></span><span class="pln"> </span><span class="tag"><bean</span><span class="pln"> </span><span class="atn">class</span><span class="pun">=</span><span class="atv">"org.jasig.cas.client.validation.Cas20ProxyTicketValidator"</span><span class="tag">></span><span class="pln"> </span><span class="tag"><constructor-arg</span><span class="pln"> </span><span class="atn">value</span><span class="pun">=</span><span class="atv">"https://localhost:9443/cas"</span><span class="tag">/></span><span class="pln"> </span><span class="tag"><property</span><span class="pln"> </span><span class="atn">name</span><span class="pun">=</span><span class="atv">"acceptAnyProxy"</span><span class="pln"> </span><span class="atn">value</span><span class="pun">=</span><span class="atv">"true"</span><span class="tag">/></span><span class="pln"> </span><span class="tag"></bean></span><span class="pln"> </span><span class="tag"></property></span><span class="pln"> </span><span class="tag"><property</span><span class="pln"> </span><span class="atn">name</span><span class="pun">=</span><span class="atv">"statelessTicketCache"</span><span class="tag">></span><span class="pln"> </span><span class="tag"><bean</span><span class="pln"> </span><span class="atn">class</span><span class="pun">=</span><span class="atv">"org.springframework.security.cas.authentication.EhCacheBasedTicketCache"</span><span class="tag">></span><span class="pln"> </span><span class="tag"><property</span><span class="pln"> </span><span class="atn">name</span><span class="pun">=</span><span class="atv">"cache"</span><span class="tag">></span><span class="pln"> </span><span class="tag"><bean</span><span class="pln"> </span><span class="atn">class</span><span class="pun">=</span><span class="atv">"net.sf.ehcache.Cache"</span><span class="pln"> </span><span class="atn">init-method</span><span class="pun">=</span><span class="atv">"initialise"</span><span class="pln"> </span><span class="atn">destroy-method</span><span class="pun">=</span><span class="atv">"dispose"</span><span class="tag">></span><span class="pln"> </span><span class="tag"><constructor-arg</span><span class="pln"> </span><span class="atn">value</span><span class="pun">=</span><span class="atv">"casTickets"</span><span class="tag">/></span><span class="pln"> </span><span class="tag"><constructor-arg</span><span class="pln"> </span><span class="atn">value</span><span class="pun">=</span><span class="atv">"50"</span><span class="tag">/></span><span class="pln"> </span><span class="tag"><constructor-arg</span><span class="pln"> </span><span class="atn">value</span><span class="pun">=</span><span class="atv">"true"</span><span class="tag">/></span><span class="pln"> </span><span class="tag"><constructor-arg</span><span class="pln"> </span><span class="atn">value</span><span class="pun">=</span><span class="atv">"false"</span><span class="tag">/></span><span class="pln"> </span><span class="tag"><constructor-arg</span><span class="pln"> </span><span class="atn">value</span><span class="pun">=</span><span class="atv">"3600"</span><span class="tag">/></span><span class="pln"> </span><span class="tag"><constructor-arg</span><span class="pln"> </span><span class="atn">value</span><span class="pun">=</span><span class="atv">"900"</span><span class="tag">/></span><span class="pln"> </span><span class="tag"></bean></span><span class="pln"> </span><span class="tag"></property></span><span class="pln"> </span><span class="tag"></bean></span><span class="pln"> </span><span class="tag"></property></span><span class="pln"> </span><span class="tag"></bean></span></code></pre> </div> </div> </div> </div> </div> </div> <div class="sect1"> <h2 id="x509"><a class="anchor" href="#x509"></a>7. X.509 Authentication</h2> <div class="sectionbody"> <div class="sect2"> <h3 id="x509-overview"><a class="anchor" href="#x509-overview"></a>7.1. Overview</h3> <div class="paragraph"> <p>The most common use of X.509 certificate authentication is in verifying the identity of a server when using SSL, most commonly when using HTTPS from a browser. The browser will automatically check that the certificate presented by a server has been issued (ie digitally signed) by one of a list of trusted certificate authorities which it maintains.</p> </div> <div class="paragraph"> <p>You can also use SSL with "mutual authentication"; the server will then request a valid certificate from the client as part of the SSL handshake. The server will authenticate the client by checking that its certificate is signed by an acceptable authority. If a valid certificate has been provided, it can be obtained through the servlet API in an application. Spring Security X.509 module extracts the certificate using a filter. It maps the certificate to an application user and loads that user’s set of granted authorities for use with the standard Spring Security infrastructure.</p> </div> <div class="paragraph"> <p>You should be familiar with using certificates and setting up client authentication for your servlet container before attempting to use it with Spring Security. Most of the work is in creating and installing suitable certificates and keys. For example, if you’re using Tomcat then read the instructions here <a href="http://tomcat.apache.org/tomcat-6.0-doc/ssl-howto.html">http://tomcat.apache.org/tomcat-6.0-doc/ssl-howto.html</a>. It’s important that you get this working before trying it out with Spring Security</p> </div> </div> <div class="sect2"> <h3 id="adding-x-509-authentication-to-your-web-application"><a class="anchor" href="#adding-x-509-authentication-to-your-web-application"></a>7.2. Adding X.509 Authentication to Your Web Application</h3> <div class="paragraph"> <p>Enabling X.509 client authentication is very straightforward. Just add the <code><x509/></code> element to your http security namespace configuration.</p> </div> <div class="listingblock"> <div class="content"> <pre style="" class="prettyprint xml language-xml prettyprinted"><code><span class="tag"><http></span><span class="pln"> ... </span><span class="tag"><x509</span><span class="pln"> </span><span class="atn">subject-principal-regex</span><span class="pun">=</span><span class="atv">"CN=(.*?),"</span><span class="pln"> </span><span class="atn">user-service-ref</span><span class="pun">=</span><span class="atv">"userService"</span><span class="tag">/></span><span class="pln">; </span><span class="tag"></http></span></code></pre> </div> </div> <div class="paragraph"> <p>The element has two optional attributes:</p> </div> <div class="ulist"> <ul> <li> <p><code>subject-principal-regex</code>. The regular expression used to extract a username from the certificate’s subject name. The default value is shown above. This is the username which will be passed to the <code>UserDetailsService</code> to load the authorities for the user.</p> </li> <li> <p><code>user-service-ref</code>. This is the bean Id of the <code>UserDetailsService</code> to be used with X.509. It isn’t needed if there is only one defined in your application context.</p> </li> </ul> </div> <div class="paragraph"> <p>The <code>subject-principal-regex</code> should contain a single group. For example the default expression "CN=(.*?)," matches the common name field. So if the subject name in the certificate is "CN=Jimi Hendrix, OU=…", this will give a user name of "Jimi Hendrix". The matches are case insensitive. So "emailAddress=(.?)," will match "EMAILADDRESS=<a href="mailto:jimi@hendrix.org">jimi@hendrix.org<script cf-hash="f9e31" type="text/javascript"> /* <![CDATA[ */!function(){try{var t="currentScript"in document?document.currentScript:function(){for(var t=document.getElementsByTagName("script"),e=t.length;e--;)if(t[e].getAttribute("cf-hash"))return t[e]}();if(t&&t.previousSibling){var e,r,n,i,c=t.previousSibling,a=c.getAttribute("data-cfemail");if(a){for(e="",r=parseInt(a.substr(0,2),16),n=2;a.length-n;n+=2)i=parseInt(a.substr(n,2),16)^r,e+=String.fromCharCode(i);e=document.createTextNode(e),c.parentNode.replaceChild(e,c)}}}catch(u){}}();/* ]]> */</script></a>,CN=…" giving a user name "<a href="mailto:jimi@hendrix.org">jimi@hendrix.org<script cf-hash="f9e31" type="text/javascript"> /* <![CDATA[ */!function(){try{var t="currentScript"in document?document.currentScript:function(){for(var t=document.getElementsByTagName("script"),e=t.length;e--;)if(t[e].getAttribute("cf-hash"))return t[e]}();if(t&&t.previousSibling){var e,r,n,i,c=t.previousSibling,a=c.getAttribute("data-cfemail");if(a){for(e="",r=parseInt(a.substr(0,2),16),n=2;a.length-n;n+=2)i=parseInt(a.substr(n,2),16)^r,e+=String.fromCharCode(i);e=document.createTextNode(e),c.parentNode.replaceChild(e,c)}}}catch(u){}}();/* ]]> */</script></a>". If the client presents a certificate and a valid username is successfully extracted, then there should be a valid <code>Authentication</code> object in the security context. If no certificate is found, or no corresponding user could be found then the security context will remain empty. This means that you can easily use X.509 authentication with other options such as a form-based login.</p> </div> </div> <div class="sect2"> <h3 id="x509-ssl-config"><a class="anchor" href="#x509-ssl-config"></a>7.3. Setting up SSL in Tomcat</h3> <div class="paragraph"> <p>There are some pre-generated certificates in the <code>samples/certificate</code> directory in the Spring Security project. You can use these to enable SSL for testing if you don’t want to generate your own. The file <code>server.jks</code> contains the server certificate, private key and the issuing certificate authority certificate. There are also some client certificate files for the users from the sample applications. You can install these in your browser to enable SSL client authentication.</p> </div> <div class="paragraph"> <p>To run tomcat with SSL support, drop the <code>server.jks</code> file into the tomcat <code>conf</code> directory and add the following connector to the <code>server.xml</code> file</p> </div> <div class="listingblock"> <div class="content"> <pre style="" class="prettyprint xml language-xml prettyprinted"><code><span class="pln"> </span><span class="tag"><Connector</span><span class="pln"> </span><span class="atn">port</span><span class="pun">=</span><span class="atv">"8443"</span><span class="pln"> </span><span class="atn">protocol</span><span class="pun">=</span><span class="atv">"HTTP/1.1"</span><span class="pln"> </span><span class="atn">SSLEnabled</span><span class="pun">=</span><span class="atv">"true"</span><span class="pln"> </span><span class="atn">scheme</span><span class="pun">=</span><span class="atv">"https"</span><span class="pln"> </span><span class="atn">secure</span><span class="pun">=</span><span class="atv">"true"</span><span class="pln"> </span><span class="atn">clientAuth</span><span class="pun">=</span><span class="atv">"true"</span><span class="pln"> </span><span class="atn">sslProtocol</span><span class="pun">=</span><span class="atv">"TLS"</span><span class="pln"> </span><span class="atn">keystoreFile</span><span class="pun">=</span><span class="atv">"${catalina.home}/conf/server.jks"</span><span class="pln"> </span><span class="atn">keystoreType</span><span class="pun">=</span><span class="atv">"JKS"</span><span class="pln"> </span><span class="atn">keystorePass</span><span class="pun">=</span><span class="atv">"password"</span><span class="pln"> </span><span class="atn">truststoreFile</span><span class="pun">=</span><span class="atv">"${catalina.home}/conf/server.jks"</span><span class="pln"> </span><span class="atn">truststoreType</span><span class="pun">=</span><span class="atv">"JKS"</span><span class="pln"> </span><span class="atn">truststorePass</span><span class="pun">=</span><span class="atv">"password"</span><span class="pln"> </span><span class="tag">/></span></code></pre> </div> </div> <div class="paragraph"> <p><code>clientAuth</code> can also be set to <code>want</code> if you still want SSL connections to succeed even if the client doesn’t provide a certificate. Clients which don’t present a certificate won’t be able to access any objects secured by Spring Security unless you use a non-X.509 authentication mechanism, such as form authentication.</p> </div> </div> </div> </div> <div class="sect1"> <h2 id="runas"><a class="anchor" href="#runas"></a>8. Run-As Authentication Replacement</h2> <div class="sectionbody"> <div class="sect2"> <h3 id="runas-overview"><a class="anchor" href="#runas-overview"></a>8.1. Overview</h3> <div class="paragraph"> <p>The <code>AbstractSecurityInterceptor</code> is able to temporarily replace the <code>Authentication</code> object in the <code>SecurityContext</code> and <code>SecurityContextHolder</code> during the secure object callback phase. This only occurs if the original <code>Authentication</code> object was successfully processed by the <code>AuthenticationManager</code> and <code>AccessDecisionManager</code>. The <code>RunAsManager</code> will indicate the replacement <code>Authentication</code> object, if any, that should be used during the <code>SecurityInterceptorCallback</code>.</p> </div> <div class="paragraph"> <p>By temporarily replacing the <code>Authentication</code> object during the secure object callback phase, the secured invocation will be able to call other objects which require different authentication and authorization credentials. It will also be able to perform any internal security checks for specific <code>GrantedAuthority</code> objects. Because Spring Security provides a number of helper classes that automatically configure remoting protocols based on the contents of the <code>SecurityContextHolder</code>, these run-as replacements are particularly useful when calling remote web services</p> </div> </div> <div class="sect2"> <h3 id="runas-config"><a class="anchor" href="#runas-config"></a>8.2. Configuration</h3> <div class="paragraph"> <p>A <code>RunAsManager</code> interface is provided by Spring Security:</p> </div> <div class="listingblock"> <div class="content"> <pre style="" class="prettyprint java language-java prettyprinted"><code><span class="typ">Authentication</span><span class="pln"> buildRunAs</span><span class="pun">(</span><span class="typ">Authentication</span><span class="pln"> authentication</span><span class="pun">,</span><span class="pln"> </span><span class="typ">Object</span><span class="pln"> object</span><span class="pun">,</span><span class="pln"> </span><span class="typ">List</span><span class="pun"><</span><span class="typ">ConfigAttribute</span><span class="pun">></span><span class="pln"> config</span><span class="pun">);</span><span class="pln"> </span><span class="kwd">boolean</span><span class="pln"> supports</span><span class="pun">(</span><span class="typ">ConfigAttribute</span><span class="pln"> attribute</span><span class="pun">);</span><span class="pln"> </span><span class="kwd">boolean</span><span class="pln"> supports</span><span class="pun">(</span><span class="typ">Class</span><span class="pln"> clazz</span><span class="pun">);</span></code></pre> </div> </div> <div class="paragraph"> <p>The first method returns the <code>Authentication</code> object that should replace the existing <code>Authentication</code> object for the duration of the method invocation. If the method returns <code>null</code>, it indicates no replacement should be made. The second method is used by the <code>AbstractSecurityInterceptor</code> as part of its startup validation of configuration attributes. The <code>supports(Class)</code> method is called by a security interceptor implementation to ensure the configured <code>RunAsManager</code> supports the type of secure object that the security interceptor will present.</p> </div> <div class="paragraph"> <p>One concrete implementation of a <code>RunAsManager</code> is provided with Spring Security. The <code>RunAsManagerImpl</code> class returns a replacement <code>RunAsUserToken</code> if any <code>ConfigAttribute</code> starts with <code>RUN_AS_</code>. If any such <code>ConfigAttribute</code> is found, the replacement <code>RunAsUserToken</code> will contain the same principal, credentials and granted authorities as the original <code>Authentication</code> object, along with a new <code>GrantedAuthorityImpl</code> for each <code>RUN_AS_</code> <code>ConfigAttribute</code>. Each new <code>GrantedAuthorityImpl</code> will be prefixed with <code>ROLE_</code>, followed by the <code>RUN_AS</code> <code>ConfigAttribute</code>. For example, a <code>RUN_AS_SERVER</code> will result in the replacement <code>RunAsUserToken</code> containing a <code>ROLE_RUN_AS_SERVER</code> granted authority.</p> </div> <div class="paragraph"> <p>The replacement <code>RunAsUserToken</code> is just like any other <code>Authentication</code> object. It needs to be authenticated by the <code>AuthenticationManager</code>, probably via delegation to a suitable <code>AuthenticationProvider</code>. The <code>RunAsImplAuthenticationProvider</code> performs such authentication. It simply accepts as valid any <code>RunAsUserToken</code> presented.</p> </div> <div class="paragraph"> <p>To ensure malicious code does not create a <code>RunAsUserToken</code> and present it for guaranteed acceptance by the <code>RunAsImplAuthenticationProvider</code>, the hash of a key is stored in all generated tokens. The <code>RunAsManagerImpl</code> and <code>RunAsImplAuthenticationProvider</code> is created in the bean context with the same key:</p> </div> <div class="listingblock"> <div class="content"> <pre style="" class="prettyprint xml language-xml prettyprinted"><code><span class="pln"> </span><span class="tag"><bean</span><span class="pln"> </span><span class="atn">id</span><span class="pun">=</span><span class="atv">"runAsManager"</span><span class="pln"> </span><span class="atn">class</span><span class="pun">=</span><span class="atv">"org.springframework.security.access.intercept.RunAsManagerImpl"</span><span class="tag">></span><span class="pln"> </span><span class="tag"><property</span><span class="pln"> </span><span class="atn">name</span><span class="pun">=</span><span class="atv">"key"</span><span class="pln"> </span><span class="atn">value</span><span class="pun">=</span><span class="atv">"my_run_as_password"</span><span class="tag">/></span><span class="pln"> </span><span class="tag"></bean></span><span class="pln"> </span><span class="tag"><bean</span><span class="pln"> </span><span class="atn">id</span><span class="pun">=</span><span class="atv">"runAsAuthenticationProvider"</span><span class="pln"> </span><span class="atn">class</span><span class="pun">=</span><span class="atv">"org.springframework.security.access.intercept.RunAsImplAuthenticationProvider"</span><span class="tag">></span><span class="pln"> </span><span class="tag"><property</span><span class="pln"> </span><span class="atn">name</span><span class="pun">=</span><span class="atv">"key"</span><span class="pln"> </span><span class="atn">value</span><span class="pun">=</span><span class="atv">"my_run_as_password"</span><span class="tag">/></span><span class="pln"> </span><span class="tag"></bean></span></code></pre> </div> </div> <div class="paragraph"> <p>By using the same key, each <code>RunAsUserToken</code> can be validated it was created by an approved <code>RunAsManagerImpl</code>. The <code>RunAsUserToken</code> is immutable after creation for security reasons</p> </div> </div> </div> </div> <div class="sect1"> <h2 id="crypto"><a class="anchor" href="#crypto"></a>9. Spring Security Crypto Module</h2> <div class="sectionbody"> <div class="sect2"> <h3 id="spring-security-crypto-introduction"><a class="anchor" href="#spring-security-crypto-introduction"></a>9.1. Introduction</h3> <div class="paragraph"> <p>The Spring Security Crypto module provides support for symmetric encryption, key generation, and password encoding. The code is distributed as part of the core module but has no dependencies on any other Spring Security (or Spring) code.</p> </div> </div> <div class="sect2"> <h3 id="spring-security-crypto-encryption"><a class="anchor" href="#spring-security-crypto-encryption"></a>9.2. Encryptors</h3> <div class="paragraph"> <p>The Encryptors class provides factory methods for constructing symmetric encryptors. Using this class, you can create ByteEncryptors to encrypt data in raw byte[] form. You can also construct TextEncryptors to encrypt text strings. Encryptors are thread safe.</p> </div> <div class="sect3"> <h4 id="spring-security-crypto-encryption-bytes"><a class="anchor" href="#spring-security-crypto-encryption-bytes"></a>9.2.1. BytesEncryptor</h4> <div class="paragraph"> <p>Use the Encryptors.standard factory method to construct a "standard" BytesEncryptor:</p> </div> <div class="listingblock"> <div class="content"> <pre style="" class="prettyprint java language-java prettyprinted"><code><span class="typ">Encryptors</span><span class="pun">.</span><span class="pln">standard</span><span class="pun">(</span><span class="str">"password"</span><span class="pun">,</span><span class="pln"> </span><span class="str">"salt"</span><span class="pun">);</span></code></pre> </div> </div> <div class="paragraph"> <p>The "standard" encryption method is 256-bit AES using PKCS #5’s PBKDF2 (Password-Based Key Derivation Function #2). This method requires Java 6. The password used to generate the SecretKey should be kept in a secure place and not be shared. The salt is used to prevent dictionary attacks against the key in the event your encrypted data is compromised. A 16-byte random initialization vector is also applied so each encrypted message is unique.</p> </div> <div class="paragraph"> <p>The provided salt should be in hex-encoded String form, be random, and be at least 8 bytes in length. Such a salt may be generated using a KeyGenerator:</p> </div> <div class="listingblock"> <div class="content"> <pre style="" class="prettyprint java language-java prettyprinted"><code><span class="typ">String</span><span class="pln"> salt </span><span class="pun">=</span><span class="pln"> </span><span class="typ">KeyGenerators</span><span class="pun">.</span><span class="pln">string</span><span class="pun">().</span><span class="pln">generateKey</span><span class="pun">();</span><span class="pln"> </span><span class="com">// generates a random 8-byte salt that is then hex-encoded</span></code></pre> </div> </div> </div> <div class="sect3"> <h4 id="spring-security-crypto-encryption-text"><a class="anchor" href="#spring-security-crypto-encryption-text"></a>9.2.2. TextEncryptor</h4> <div class="paragraph"> <p>Use the Encryptors.text factory method to construct a standard TextEncryptor:</p> </div> <div class="listingblock"> <div class="content"> <pre style="" class="prettyprint java language-java prettyprinted"><code><span class="pln"> </span><span class="typ">Encryptors</span><span class="pun">.</span><span class="pln">text</span><span class="pun">(</span><span class="str">"password"</span><span class="pun">,</span><span class="pln"> </span><span class="str">"salt"</span><span class="pun">);</span></code></pre> </div> </div> <div class="paragraph"> <p>A TextEncryptor uses a standard BytesEncryptor to encrypt text data. Encrypted results are returned as hex-encoded strings for easy storage on the filesystem or in the database.</p> </div> <div class="paragraph"> <p>Use the Encryptors.queryableText factory method to construct a "queryable" TextEncryptor:</p> </div> <div class="listingblock"> <div class="content"> <pre style="" class="prettyprint java language-java prettyprinted"><code><span class="typ">Encryptors</span><span class="pun">.</span><span class="pln">queryableText</span><span class="pun">(</span><span class="str">"password"</span><span class="pun">,</span><span class="pln"> </span><span class="str">"salt"</span><span class="pun">);</span></code></pre> </div> </div> <div class="paragraph"> <p>The difference between a queryable TextEncryptor and a standard TextEncryptor has to do with initialization vector (iv) handling. The iv used in a queryable TextEncryptor#encrypt operation is shared, or constant, and is not randomly generated. This means the same text encrypted multiple times will always produce the same encryption result. This is less secure, but necessary for encrypted data that needs to be queried against. An example of queryable encrypted text would be an OAuth apiKey.</p> </div> </div> </div> <div class="sect2"> <h3 id="spring-security-crypto-keygenerators"><a class="anchor" href="#spring-security-crypto-keygenerators"></a>9.3. Key Generators</h3> <div class="paragraph"> <p>The KeyGenerators class provides a number of convenience factory methods for constructing different types of key generators. Using this class, you can create a BytesKeyGenerator to generate byte[] keys. You can also construct a StringKeyGenerator to generate string keys. KeyGenerators are thread safe.</p> </div> <div class="sect3"> <h4 id="byteskeygenerator"><a class="anchor" href="#byteskeygenerator"></a>9.3.1. BytesKeyGenerator</h4> <div class="paragraph"> <p>Use the KeyGenerators.secureRandom factory methods to generate a BytesKeyGenerator backed by a SecureRandom instance:</p> </div> <div class="listingblock"> <div class="content"> <pre style="" class="prettyprint java language-java prettyprinted"><code><span class="typ">KeyGenerator</span><span class="pln"> generator </span><span class="pun">=</span><span class="pln"> </span><span class="typ">KeyGenerators</span><span class="pun">.</span><span class="pln">secureRandom</span><span class="pun">();</span><span class="pln"> </span><span class="kwd">byte</span><span class="pun">[]</span><span class="pln"> key </span><span class="pun">=</span><span class="pln"> generator</span><span class="pun">.</span><span class="pln">generateKey</span><span class="pun">();</span></code></pre> </div> </div> <div class="paragraph"> <p>The default key length is 8 bytes. There is also a KeyGenerators.secureRandom variant that provides control over the key length:</p> </div> <div class="listingblock"> <div class="content"> <pre style="" class="prettyprint java language-java prettyprinted"><code><span class="typ">KeyGenerators</span><span class="pun">.</span><span class="pln">secureRandom</span><span class="pun">(</span><span class="lit">16</span><span class="pun">);</span></code></pre> </div> </div> <div class="paragraph"> <p>Use the KeyGenerators.shared factory method to construct a BytesKeyGenerator that always returns the same key on every invocation:</p> </div> <div class="listingblock"> <div class="content"> <pre style="" class="prettyprint java language-java prettyprinted"><code><span class="typ">KeyGenerators</span><span class="pun">.</span><span class="pln">shared</span><span class="pun">(</span><span class="lit">16</span><span class="pun">);</span></code></pre> </div> </div> </div> <div class="sect3"> <h4 id="stringkeygenerator"><a class="anchor" href="#stringkeygenerator"></a>9.3.2. StringKeyGenerator</h4> <div class="paragraph"> <p>Use the KeyGenerators.string factory method to construct a 8-byte, SecureRandom KeyGenerator that hex-encodes each key as a String:</p> </div> <div class="listingblock"> <div class="content"> <pre style="" class="prettyprint java language-java prettyprinted"><code><span class="typ">KeyGenerators</span><span class="pun">.</span><span class="pln">string</span><span class="pun">();</span></code></pre> </div> </div> </div> </div> <div class="sect2"> <h3 id="spring-security-crypto-passwordencoders"><a class="anchor" href="#spring-security-crypto-passwordencoders"></a>9.4. Password Encoding</h3> <div class="paragraph"> <p>The password package of the spring-security-crypto module provides support for encoding passwords. <code>PasswordEncoder</code> is the central service interface and has the following signature:</p> </div> <div class="listingblock"> <div class="content"> <pre style="" class="prettyprint java language-java prettyprinted"><code><span class="kwd">public</span><span class="pln"> </span><span class="kwd">interface</span><span class="pln"> </span><span class="typ">PasswordEncoder</span><span class="pln"> </span><span class="pun">{</span><span class="pln"> </span><span class="typ">String</span><span class="pln"> encode</span><span class="pun">(</span><span class="typ">String</span><span class="pln"> rawPassword</span><span class="pun">);</span><span class="pln"> </span><span class="kwd">boolean</span><span class="pln"> matches</span><span class="pun">(</span><span class="typ">String</span><span class="pln"> rawPassword</span><span class="pun">,</span><span class="pln"> </span><span class="typ">String</span><span class="pln"> encodedPassword</span><span class="pun">);</span><span class="pln"> </span><span class="pun">}</span></code></pre> </div> </div> <div class="paragraph"> <p>The matches method returns true if the rawPassword, once encoded, equals the encodedPassword. This method is designed to support password-based authentication schemes.</p> </div> <div class="paragraph"> <p>The <code>BCryptPasswordEncoder</code> implementation uses the widely supported "bcrypt" algorithm to hash the passwords. Bcrypt uses a random 16 byte salt value and is a deliberately slow algorithm, in order to hinder password crackers. The amount of work it does can be tuned using the "strength" parameter which takes values from 4 to 31. The higher the value, the more work has to be done to calculate the hash. The default value is 10. You can change this value in your deployed system without affecting existing passwords, as the value is also stored in the encoded hash.</p> </div> <div class="listingblock"> <div class="content"> <pre style="" class="prettyprint java language-java prettyprinted"><code><span class="pln"> </span><span class="com">// Create an encoder with strength 16</span><span class="pln"> </span><span class="typ">BCryptPasswordEncoder</span><span class="pln"> encoder </span><span class="pun">=</span><span class="pln"> </span><span class="kwd">new</span><span class="pln"> </span><span class="typ">BCryptPasswordEncoder</span><span class="pun">(</span><span class="lit">16</span><span class="pun">);</span><span class="pln"> </span><span class="typ">String</span><span class="pln"> result </span><span class="pun">=</span><span class="pln"> encoder</span><span class="pun">.</span><span class="pln">encode</span><span class="pun">(</span><span class="str">"myPassword"</span><span class="pun">);</span><span class="pln"> assertTrue</span><span class="pun">(</span><span class="pln">encoder</span><span class="pun">.</span><span class="pln">matches</span><span class="pun">(</span><span class="str">"myPassword"</span><span class="pun">,</span><span class="pln"> result</span><span class="pun">));</span></code></pre> </div> </div> </div> </div> </div> <div class="sect1"> <h2 id="concurrency"><a class="anchor" href="#concurrency"></a>10. Concurrency Support</h2> <div class="sectionbody"> <div class="paragraph"> <p>In most environments, Security is stored on a per <code>Thread</code> basis. This means that when work is done on a new <code>Thread</code>, the <code>SecurityContext</code> is lost. Spring Security provides some infrastructure to help make this much easier for users. Spring Security provides low level abstractions for working with Spring Security in multi threaded environments. In fact, this is what Spring Security builds on to integration with <a href="#servletapi-start-runnable">AsyncContext.start(Runnable)</a> and <a href="#mvc-async">Spring MVC Async Integration</a>.</p> </div> <div class="sect2"> <h3 id="delegatingsecuritycontextrunnable"><a class="anchor" href="#delegatingsecuritycontextrunnable"></a>10.1. DelegatingSecurityContextRunnable</h3> <div class="paragraph"> <p>One of the most fundamental building blocks within Spring Security’s concurrency support is the <code>DelegatingSecurityContextRunnable</code>. It wraps a delegate <code>Runnable</code> in order to initialize the <code>SecurityContextHolder</code> with a specified <code>SecurityContext</code> for the delegate. It then invokes the delegate Runnable ensuring to clear the <code>SecurityContextHolder</code> afterwards. The <code>DelegatingSecurityContextRunnable</code> looks something like this:</p> </div> <div class="listingblock"> <div class="content"> <pre style="" class="prettyprint java language-java prettyprinted"><code><span class="kwd">public</span><span class="pln"> </span><span class="kwd">void</span><span class="pln"> run</span><span class="pun">()</span><span class="pln"> </span><span class="pun">{</span><span class="pln"> </span><span class="kwd">try</span><span class="pln"> </span><span class="pun">{</span><span class="pln"> </span><span class="typ">SecurityContextHolder</span><span class="pun">.</span><span class="pln">setContext</span><span class="pun">(</span><span class="pln">securityContext</span><span class="pun">);</span><span class="pln"> delegate</span><span class="pun">.</span><span class="pln">run</span><span class="pun">();</span><span class="pln"> </span><span class="pun">}</span><span class="pln"> </span><span class="kwd">finally</span><span class="pln"> </span><span class="pun">{</span><span class="pln"> </span><span class="typ">SecurityContextHolder</span><span class="pun">.</span><span class="pln">clearContext</span><span class="pun">();</span><span class="pln"> </span><span class="pun">}</span><span class="pln"> </span><span class="pun">}</span></code></pre> </div> </div> <div class="paragraph"> <p>While very simple, it makes it seamless to transfer the SecurityContext from one Thread to another. This is important since, in most cases, the SecurityContextHolder acts on a per Thread basis. For example, you might have used Spring Security’s <a href="#nsa-global-method-security"><global-method-security></a> support to secure one of your services. You can now easily transfer the <code>SecurityContext</code> of the current <code>Thread</code> to the <code>Thread</code> that invokes the secured service. An example of how you might do this can be found below:</p> </div> <div class="listingblock"> <div class="content"> <pre style="" class="prettyprint java language-java prettyprinted"><code><span class="typ">Runnable</span><span class="pln"> originalRunnable </span><span class="pun">=</span><span class="pln"> </span><span class="kwd">new</span><span class="pln"> </span><span class="typ">Runnable</span><span class="pun">()</span><span class="pln"> </span><span class="pun">{</span><span class="pln"> </span><span class="kwd">public</span><span class="pln"> </span><span class="kwd">void</span><span class="pln"> run</span><span class="pun">()</span><span class="pln"> </span><span class="pun">{</span><span class="pln"> </span><span class="com">// invoke secured service</span><span class="pln"> </span><span class="pun">}</span><span class="pln"> </span><span class="pun">};</span><span class="pln"> </span><span class="typ">SecurityContext</span><span class="pln"> context </span><span class="pun">=</span><span class="pln"> </span><span class="typ">SecurityContextHolder</span><span class="pun">.</span><span class="pln">getContext</span><span class="pun">();</span><span class="pln"> </span><span class="typ">DelegatingSecurityContextRunnable</span><span class="pln"> wrappedRunnable </span><span class="pun">=</span><span class="pln"> </span><span class="kwd">new</span><span class="pln"> </span><span class="typ">DelegatingSecurityContextRunnable</span><span class="pun">(</span><span class="pln">originalRunnable</span><span class="pun">,</span><span class="pln"> context</span><span class="pun">);</span><span class="pln"> </span><span class="kwd">new</span><span class="pln"> </span><span class="typ">Thread</span><span class="pun">(</span><span class="pln">wrappedRunnable</span><span class="pun">).</span><span class="pln">start</span><span class="pun">();</span></code></pre> </div> </div> <div class="paragraph"> <p>The code above performs the following steps:</p> </div> <div class="ulist"> <ul> <li> <p>Creates a <code>Runnable</code> that will be invoking our secured service. Notice that it is not aware of Spring Security</p> </li> <li> <p>Obtains the <code>SecurityContext</code> that we wish to use from the <code>SecurityContextHolder</code> and initializes the <code>DelegatingSecurityContextRunnable</code></p> </li> <li> <p>Use the <code>DelegatingSecurityContextRunnable</code> to create a Thread</p> </li> <li> <p>Start the Thread we created</p> </li> </ul> </div> <div class="paragraph"> <p>Since it is quite common to create a <code>DelegatingSecurityContextRunnable</code> with the <code>SecurityContext</code> from the <code>SecurityContextHolder</code> there is a shortcut constructor for it. The following code is the same as the code above:</p> </div> <div class="listingblock"> <div class="content"> <pre style="" class="prettyprint java language-java prettyprinted"><code><span class="typ">Runnable</span><span class="pln"> originalRunnable </span><span class="pun">=</span><span class="pln"> </span><span class="kwd">new</span><span class="pln"> </span><span class="typ">Runnable</span><span class="pun">()</span><span class="pln"> </span><span class="pun">{</span><span class="pln"> </span><span class="kwd">public</span><span class="pln"> </span><span class="kwd">void</span><span class="pln"> run</span><span class="pun">()</span><span class="pln"> </span><span class="pun">{</span><span class="pln"> </span><span class="com">// invoke secured service</span><span class="pln"> </span><span class="pun">}</span><span class="pln"> </span><span class="pun">};</span><span class="pln"> </span><span class="typ">DelegatingSecurityContextRunnable</span><span class="pln"> wrappedRunnable </span><span class="pun">=</span><span class="pln"> </span><span class="kwd">new</span><span class="pln"> </span><span class="typ">DelegatingSecurityContextRunnable</span><span class="pun">(</span><span class="pln">originalRunnable</span><span class="pun">);</span><span class="pln"> </span><span class="kwd">new</span><span class="pln"> </span><span class="typ">Thread</span><span class="pun">(</span><span class="pln">wrappedRunnable</span><span class="pun">).</span><span class="pln">start</span><span class="pun">();</span></code></pre> </div> </div> <div class="paragraph"> <p>The code we have is simple to use, but it still requires knowledge that we are using Spring Security. In the next section we will take a look at how we can utilize <code>DelegatingSecurityContextExecutor</code> to hide the fact that we are using Spring Security.</p> </div> </div> <div class="sect2"> <h3 id="delegatingsecuritycontextexecutor"><a class="anchor" href="#delegatingsecuritycontextexecutor"></a>10.2. DelegatingSecurityContextExecutor</h3> <div class="paragraph"> <p>In the previous section we found that it was easy to use the <code>DelegatingSecurityContextRunnable</code>, but it was not ideal since we had to be aware of Spring Security in order to use it. Let’s take a look at how <code>DelegatingSecurityContextExecutor</code> can shield our code from any knowledge that we are using Spring Security.</p> </div> <div class="paragraph"> <p>The design of <code>DelegatingSecurityContextExecutor</code> is very similar to that of <code>DelegatingSecurityContextRunnable</code> except it accepts a delegate <code>Executor</code> instead of a delegate <code>Runnable</code>. You can see an example of how it might be used below:</p> </div> <div class="listingblock"> <div class="content"> <pre style="" class="prettyprint java language-java prettyprinted"><code><span class="typ">SecurityContext</span><span class="pln"> context </span><span class="pun">=</span><span class="pln"> </span><span class="typ">SecurityContextHolder</span><span class="pun">.</span><span class="pln">createEmptyContext</span><span class="pun">();</span><span class="pln"> </span><span class="typ">Authentication</span><span class="pln"> authentication </span><span class="pun">=</span><span class="pln"> </span><span class="kwd">new</span><span class="pln"> </span><span class="typ">UsernamePasswordAuthenticationToken</span><span class="pun">(</span><span class="str">"user"</span><span class="pun">,</span><span class="str">"doesnotmatter"</span><span class="pun">,</span><span class="pln"> </span><span class="typ">AuthorityUtils</span><span class="pun">.</span><span class="pln">createAuthorityList</span><span class="pun">(</span><span class="str">"ROLE_USER"</span><span class="pun">));</span><span class="pln"> context</span><span class="pun">.</span><span class="pln">setAuthentication</span><span class="pun">(</span><span class="pln">authentication</span><span class="pun">);</span><span class="pln"> </span><span class="typ">SimpleAsyncTaskExecutor</span><span class="pln"> delegateExecutor </span><span class="pun">=</span><span class="pln"> </span><span class="kwd">new</span><span class="pln"> </span><span class="typ">SimpleAsyncTaskExecutor</span><span class="pun">();</span><span class="pln"> </span><span class="typ">DelegatingSecurityContextExecutor</span><span class="pln"> executor </span><span class="pun">=</span><span class="pln"> </span><span class="kwd">new</span><span class="pln"> </span><span class="typ">DelegatingSecurityContextExecutor</span><span class="pun">(</span><span class="pln">delegateExecutor</span><span class="pun">,</span><span class="pln"> context</span><span class="pun">);</span><span class="pln"> </span><span class="typ">Runnable</span><span class="pln"> originalRunnable </span><span class="pun">=</span><span class="pln"> </span><span class="kwd">new</span><span class="pln"> </span><span class="typ">Runnable</span><span class="pun">()</span><span class="pln"> </span><span class="pun">{</span><span class="pln"> </span><span class="kwd">public</span><span class="pln"> </span><span class="kwd">void</span><span class="pln"> run</span><span class="pun">()</span><span class="pln"> </span><span class="pun">{</span><span class="pln"> </span><span class="com">// invoke secured service</span><span class="pln"> </span><span class="pun">}</span><span class="pln"> </span><span class="pun">};</span><span class="pln"> executor</span><span class="pun">.</span><span class="pln">execute</span><span class="pun">(</span><span class="pln">originalRunnable</span><span class="pun">);</span></code></pre> </div> </div> <div class="paragraph"> <p>The code performs the following steps:</p> </div> <div class="ulist"> <ul> <li> <p>Creates the <code>SecurityContext</code> to be used for our <code>DelegatingSecurityContextExecutor</code>. Note that in this example we simply create the <code>SecurityContext</code> by hand. However, it does not matter where or how we get the <code>SecurityContext</code> (i.e. we could obtain it from the <code>SecurityContextHolder</code> if we wanted).</p> </li> <li> <p>Creates a delegateExecutor that is in charge of executing submitted `Runnable`s</p> </li> <li> <p>Finally we create a <code>DelegatingSecurityContextExecutor</code> which is in charge of wrapping any Runnable that is passed into the execute method with a <code>DelegatingSecurityContextRunnable</code>. It then passes the wrapped Runnable to the delegateExecutor. In this instance, the same <code>SecurityContext</code> will be used for every Runnable submitted to our <code>DelegatingSecurityContextExecutor</code>. This is nice if we are running background tasks that need to be run by a user with elevated privileges.</p> </li> <li> <p>At this point you may be asking yourself "How does this shield my code of any knowledge of Spring Security?" Instead of creating the <code>SecurityContext</code> and the <code>DelegatingSecurityContextExecutor</code> in our own code, we can inject an already initialized instance of <code>DelegatingSecurityContextExecutor</code>.</p> </li> </ul> </div> <div class="listingblock"> <div class="content"> <pre style="" class="prettyprint java language-java prettyprinted"><code><span class="lit">@Autowired</span><span class="pln"> </span><span class="kwd">private</span><span class="pln"> </span><span class="typ">Executor</span><span class="pln"> executor</span><span class="pun">;</span><span class="pln"> </span><span class="com">// becomes an instance of our DelegatingSecurityContextExecutor</span><span class="pln"> </span><span class="kwd">public</span><span class="pln"> </span><span class="kwd">void</span><span class="pln"> submitRunnable</span><span class="pun">()</span><span class="pln"> </span><span class="pun">{</span><span class="pln"> </span><span class="typ">Runnable</span><span class="pln"> originalRunnable </span><span class="pun">=</span><span class="pln"> </span><span class="kwd">new</span><span class="pln"> </span><span class="typ">Runnable</span><span class="pun">()</span><span class="pln"> </span><span class="pun">{</span><span class="pln"> </span><span class="kwd">public</span><span class="pln"> </span><span class="kwd">void</span><span class="pln"> run</span><span class="pun">()</span><span class="pln"> </span><span class="pun">{</span><span class="pln"> </span><span class="com">// invoke secured service</span><span class="pln"> </span><span class="pun">}</span><span class="pln"> </span><span class="pun">};</span><span class="pln"> executor</span><span class="pun">.</span><span class="pln">execute</span><span class="pun">(</span><span class="pln">originalRunnable</span><span class="pun">);</span><span class="pln"> </span><span class="pun">}</span></code></pre> </div> </div> <div class="paragraph"> <p>Now our code is unaware that the <code>SecurityContext</code> is being propagated to the <code>Thread</code>, then the <code>originalRunnable</code> is executed, and then the <code>SecurityContextHolder</code> is cleared out. In this example, the same user is being used to execute each Thread. What if we wanted to use the user from <code>SecurityContextHolder</code> at the time we invoked <code>executor.execute(Runnable)</code> (i.e. the currently logged in user) to process <code>originalRunnable</code>? This can be done by removing the <code>SecurityContext</code> argument from our <code>DelegatingSecurityContextExecutor</code> constructor. For example:</p> </div> <div class="listingblock"> <div class="content"> <pre style="" class="prettyprint java language-java prettyprinted"><code><span class="typ">SimpleAsyncTaskExecutor</span><span class="pln"> delegateExecutor </span><span class="pun">=</span><span class="pln"> </span><span class="kwd">new</span><span class="pln"> </span><span class="typ">SimpleAsyncTaskExecutor</span><span class="pun">();</span><span class="pln"> </span><span class="typ">DelegatingSecurityContextExecutor</span><span class="pln"> executor </span><span class="pun">=</span><span class="pln"> </span><span class="kwd">new</span><span class="pln"> </span><span class="typ">DelegatingSecurityContextExecutor</span><span class="pun">(</span><span class="pln">delegateExecutor</span><span class="pun">);</span></code></pre> </div> </div> <div class="paragraph"> <p>Now anytime <code>executor.execute(Runnable)</code> is executed the <code>SecurityContext</code> is first obtained by the <code>SecurityContextHolder</code> and then that <code>SecurityContext</code> is used to create our <code>DelegatingSecurityContextRunnable</code>. This means that we are executing our <code>Runnable</code> with the same user that was used to invoke the <code>executor.execute(Runnable)</code> code.</p> </div> </div> <div class="sect2"> <h3 id="spring-security-concurrency-classes"><a class="anchor" href="#spring-security-concurrency-classes"></a>10.3. Spring Security Concurrency Classes</h3> <div class="paragraph"> <p>Refer to the Javadoc for additional integrations with both the Java concurrent APIs and the Spring Task abstractions. They are quite self explanatory once you understand the previous code.</p> </div> <div class="ulist"> <ul> <li> <p>DelegatingSecurityContextCallable</p> </li> <li> <p>DelegatingSecurityContextExecutor</p> </li> <li> <p>DelegatingSecurityContextExecutorService</p> </li> <li> <p>DelegatingSecurityContextRunnable</p> </li> <li> <p>DelegatingSecurityContextScheduledExecutorService</p> </li> <li> <p>DelegatingSecurityContextSchedulingTaskExecutor</p> </li> <li> <p>DelegatingSecurityContextAsyncTaskExecutor</p> </li> <li> <p>DelegatingSecurityContextTaskExecutor</p> </li> </ul> </div> </div> </div> </div> <div class="sect1"> <h2 id="mvc"><a class="anchor" href="#mvc"></a>11. Spring MVC Integration</h2> <div class="sectionbody"> <div class="paragraph"> <p>Spring Security provides a number of optional integrations with Spring MVC. This section covers the integration in further detail.</p> </div> <div class="sect2"> <h3 id="mvc-enablewebmvcsecurity"><a class="anchor" href="#mvc-enablewebmvcsecurity"></a>11.1. @EnableWebMvcSecurity</h3> <div class="paragraph"> <p>To enable Spring Security integration with Spring MVC add the <code>@EnableWebMvcSecurity</code> annotation to your configuration. A typical example will look something like this:</p> </div> <div class="listingblock"> <div class="content"> <pre style="" class="prettyprint java language-java prettyprinted"><code><span class="lit">@Configuration</span><span class="pln"> </span><span class="lit">@EnableWebMvcSecurity</span><span class="pln"> </span><span class="kwd">public</span><span class="pln"> </span><span class="kwd">class</span><span class="pln"> </span><span class="typ">SecurityConfig</span><span class="pln"> </span><span class="pun">{</span><span class="pln"> </span><span class="com">// ...</span><span class="pln"> </span><span class="pun">}</span></code></pre> </div> </div> </div> <div class="sect2"> <h3 id="mvc-authentication-principal"><a class="anchor" href="#mvc-authentication-principal"></a>11.2. @AuthenticationPrincipal</h3> <div class="paragraph"> <p>Spring Security provides <code>AuthenticationPrincipalArgumentResolver</code> which can automatically resolve the current <code>Authentication.getPrincipal()</code> for Spring MVC arguments. By using <a href="#mvc-enablewebmvcsecurity">@EnableWebMvcSecurity</a> you will automatically have this added to your Spring MVC configuration. If you use XML based configuraiton, you must add this yourself.</p> </div> <div class="paragraph"> <p>Once <code>AuthenticationPrincipalArgumentResolver</code> is properly configured, you can be entirely decoupled from Spring Security in your Spring MVC layer.</p> </div> <div class="paragraph"> <p>Consider a situation where a custom <code>UserDetailsService</code> that returns an <code>Object</code> that implements <code>UserDetails</code> and your own <code>CustomUser</code> <code>Object</code>. The <code>CustomUser</code> of the currently authenticated user could be accessed using the following code:</p> </div> <div class="listingblock"> <div class="content"> <pre style="" class="prettyprint java language-java prettyprinted"><code><span class="kwd">import</span><span class="pln"> org</span><span class="pun">.</span><span class="pln">springframework</span><span class="pun">.</span><span class="pln">security</span><span class="pun">.</span><span class="pln">web</span><span class="pun">.</span><span class="pln">bind</span><span class="pun">.</span><span class="pln">annotation</span><span class="pun">.</span><span class="typ">AuthenticationPrincipal</span><span class="pun">;</span><span class="pln"> </span><span class="com">// ...</span><span class="pln"> </span><span class="lit">@RequestMapping</span><span class="pun">(</span><span class="str">"/messages/inbox"</span><span class="pun">)</span><span class="pln"> </span><span class="kwd">public</span><span class="pln"> </span><span class="typ">ModelAndView</span><span class="pln"> findMessagesForUser</span><span class="pun">()</span><span class="pln"> </span><span class="pun">{</span><span class="pln"> </span><span class="typ">Authentication</span><span class="pln"> authentication </span><span class="pun">=</span><span class="pln"> </span><span class="typ">SecurityContextHolder</span><span class="pun">.</span><span class="pln">getContext</span><span class="pun">().</span><span class="pln">getAuthentication</span><span class="pun">();</span><span class="pln"> </span><span class="typ">CustomUser</span><span class="pln"> custom </span><span class="pun">=</span><span class="pln"> </span><span class="pun">(</span><span class="typ">CustomUser</span><span class="pun">)</span><span class="pln"> authentication </span><span class="pun">==</span><span class="pln"> </span><span class="kwd">null</span><span class="pln"> </span><span class="pun">?</span><span class="pln"> </span><span class="kwd">null</span><span class="pln"> </span><span class="pun">:</span><span class="pln"> authentication</span><span class="pun">.</span><span class="pln">getPrincipal</span><span class="pun">();</span><span class="pln"> </span><span class="com">// .. find messags for this user and return them ...</span><span class="pln"> </span><span class="pun">}</span></code></pre> </div> </div> <div class="paragraph"> <p>As of Spring Security 3.2 we can resolve the argument more directly by adding an annotation. For example:</p> </div> <div class="listingblock"> <div class="content"> <pre style="" class="prettyprint java language-java prettyprinted"><code><span class="lit">@RequestMapping</span><span class="pun">(</span><span class="str">"/messages/inbox"</span><span class="pun">)</span><span class="pln"> </span><span class="kwd">public</span><span class="pln"> </span><span class="typ">ModelAndView</span><span class="pln"> findMessagesForUser</span><span class="pun">(</span><span class="lit">@AuthenticationPrincipal</span><span class="pln"> </span><span class="typ">CustomUser</span><span class="pln"> customUser</span><span class="pun">)</span><span class="pln"> </span><span class="pun">{</span><span class="pln"> </span><span class="com">// .. find messags for this user and return them ...</span><span class="pln"> </span><span class="pun">}</span></code></pre> </div> </div> <div class="paragraph"> <p>We can further remove our dependency on Spring Security by making <code>@AuthenticationPrincipal</code> a meta annotation on our own annotation. Below we demonstrate how we could do this on an annotation named <code>@CurrentUser</code>.</p> </div> <div class="admonitionblock note"> <table> <tbody><tr> <td class="icon"> <i class="icon-note" title="Note"></i> </td> <td class="content"> It is important to realize that in order to remove the dependency on Spring Security, it is the consuming application that would create <code>@CurrentUser</code>. This step is not strictly required, but assists in isolating your dependency to Spring Security to a more central location. </td> </tr> </tbody></table> </div> <div class="listingblock"> <div class="content"> <pre style="" class="prettyprint java language-java prettyprinted"><code><span class="lit">@Target</span><span class="pun">({</span><span class="typ">ElementType</span><span class="pun">.</span><span class="pln">PARAMETER</span><span class="pun">,</span><span class="pln"> </span><span class="typ">ElementType</span><span class="pun">.</span><span class="pln">TYPE</span><span class="pun">})</span><span class="pln"> </span><span class="lit">@Retention</span><span class="pun">(</span><span class="typ">RetentionPolicy</span><span class="pun">.</span><span class="pln">RUNTIME</span><span class="pun">)</span><span class="pln"> </span><span class="lit">@Documented</span><span class="pln"> </span><span class="lit">@AuthenticationPrincipal</span><span class="pln"> </span><span class="kwd">public</span><span class="pln"> </span><span class="lit">@interface</span><span class="pln"> </span><span class="typ">CurrentUser</span><span class="pln"> </span><span class="pun">{}</span></code></pre> </div> </div> <div class="paragraph"> <p>Now that <code>@CurrentUser</code> has been specified, we can use it to signal to resolve our <code>CustomUser</code> of the currently authenticated user. We have also isolated our dependency on Spring Security to a single file.</p> </div> <div class="listingblock"> <div class="content"> <pre style="" class="prettyprint java language-java prettyprinted"><code><span class="lit">@RequestMapping</span><span class="pun">(</span><span class="str">"/messages/inbox"</span><span class="pun">)</span><span class="pln"> </span><span class="kwd">public</span><span class="pln"> </span><span class="typ">ModelAndView</span><span class="pln"> findMessagesForUser</span><span class="pun">(</span><span class="lit">@CurrentUser</span><span class="pln"> </span><span class="typ">CustomUser</span><span class="pln"> customUser</span><span class="pun">)</span><span class="pln"> </span><span class="pun">{</span><span class="pln"> </span><span class="com">// .. find messags for this user and return them ...</span><span class="pln"> </span><span class="pun">}</span></code></pre> </div> </div> </div> <div class="sect2"> <h3 id="mvc-async"><a class="anchor" href="#mvc-async"></a>11.3. Spring MVC Async Integration</h3> <div class="paragraph"> <p>Spring Web MVC 3.2+ has excellent support for <a href="http://docs.spring.io/spring/docs/3.2.x/spring-framework-reference/html/mvc.html#mvc-ann-async">Asynchronous Request Processing</a>. With no additional configuration, Spring Security will automatically setup the <code>SecurityContext</code> to the <code>Thread</code> that executes a <code>Callable</code> returned by your controllers. For example, the following method will automatically have its <code>Callable</code> executed with the <code>SecurityContext</code> that was available when the <code>Callable</code> was created:</p> </div> <div class="listingblock"> <div class="content"> <pre style="" class="prettyprint java language-java prettyprinted"><code><span class="lit">@RequestMapping</span><span class="pun">(</span><span class="pln">method</span><span class="pun">=</span><span class="typ">RequestMethod</span><span class="pun">.</span><span class="pln">POST</span><span class="pun">)</span><span class="pln"> </span><span class="kwd">public</span><span class="pln"> </span><span class="typ">Callable</span><span class="pun"><</span><span class="typ">String</span><span class="pun">></span><span class="pln"> processUpload</span><span class="pun">(</span><span class="kwd">final</span><span class="pln"> </span><span class="typ">MultipartFile</span><span class="pln"> file</span><span class="pun">)</span><span class="pln"> </span><span class="pun">{</span><span class="pln"> </span><span class="kwd">return</span><span class="pln"> </span><span class="kwd">new</span><span class="pln"> </span><span class="typ">Callable</span><span class="pun"><</span><span class="typ">String</span><span class="pun">>()</span><span class="pln"> </span><span class="pun">{</span><span class="pln"> </span><span class="kwd">public</span><span class="pln"> </span><span class="typ">Object</span><span class="pln"> call</span><span class="pun">()</span><span class="pln"> </span><span class="kwd">throws</span><span class="pln"> </span><span class="typ">Exception</span><span class="pln"> </span><span class="pun">{</span><span class="pln"> </span><span class="com">// ...</span><span class="pln"> </span><span class="kwd">return</span><span class="pln"> </span><span class="str">"someView"</span><span class="pun">;</span><span class="pln"> </span><span class="pun">}</span><span class="pln"> </span><span class="pun">};</span><span class="pln"> </span><span class="pun">}</span></code></pre> </div> </div> <div class="admonitionblock note"> <table> <tbody><tr> <td class="icon"> <i class="icon-note" title="Note"></i> </td> <td class="content"> <div class="title">Associating SecurityContext to Callable’s</div> <div class="paragraph"> <p>More technically speaking, Spring Security integrates with <code>WebAsyncManager</code>. The <code>SecurityContext</code> that is used to process the <code>Callable</code> is the <code>SecurityContext</code> that exists on the <code>SecurityContextHolder</code> at the time <code>startCallableProcessing</code> is invoked.</p> </div> </td> </tr> </tbody></table> </div> <div class="paragraph"> <p>There is no automatic integration with a <code>DeferredResult</code> that is returned by controllers. This is because <code>DeferredResult</code> is processed by the users and thus there is no way of automatically integrating with it. However, you can still use <a href="#concurrency-support">[concurrency-support]</a> to provide transparent integration with Spring Security.</p> </div> </div> <div class="sect2"> <h3 id="mvc-csrf"><a class="anchor" href="#mvc-csrf"></a>11.4. Spring MVC and CSRF Integration</h3> <div class="paragraph"> <p>Spring Security will automatically <a href="#csrf-include-csrf-token">include the CSRF Token</a> within forms that use the <a href="http://docs.spring.io/spring/docs/3.2.x/spring-framework-reference/html/view.html#view-jsp-formtaglib-formtag">Spring MVC form tag</a>. For example, the following JSP:</p> </div> <div class="listingblock"> <div class="content"> <pre style="" class="prettyprint xml language-xml prettyprinted"><code><span class="tag"><jsp:root</span><span class="pln"> </span><span class="atn">xmlns:jsp</span><span class="pun">=</span><span class="atv">"http://java.sun.com/JSP/Page"</span><span class="pln"> </span><span class="atn">xmlns:c</span><span class="pun">=</span><span class="atv">"http://java.sun.com/jsp/jstl/core"</span><span class="pln"> </span><span class="atn">xmlns:form</span><span class="pun">=</span><span class="atv">"http://www.springframework.org/tags/form"</span><span class="pln"> </span><span class="atn">version</span><span class="pun">=</span><span class="atv">"2.0"</span><span class="tag">></span><span class="pln"> </span><span class="tag"><jsp:directive.page</span><span class="pln"> </span><span class="atn">language</span><span class="pun">=</span><span class="atv">"java"</span><span class="pln"> </span><span class="atn">contentType</span><span class="pun">=</span><span class="atv">"text/html"</span><span class="pln"> </span><span class="tag">/></span><span class="pln"> </span><span class="tag"><html</span><span class="pln"> </span><span class="atn">xmlns</span><span class="pun">=</span><span class="atv">"http://www.w3.org/1999/xhtml"</span><span class="pln"> </span><span class="atn">lang</span><span class="pun">=</span><span class="atv">"en"</span><span class="pln"> </span><span class="atn">xml:lang</span><span class="pun">=</span><span class="atv">"en"</span><span class="tag">></span><span class="pln"> </span><span class="com"><!-- ... --></span><span class="pln"> </span><span class="tag"><c:url</span><span class="pln"> </span><span class="atn">var</span><span class="pun">=</span><span class="atv">"logoutUrl"</span><span class="pln"> </span><span class="atn">value</span><span class="pun">=</span><span class="atv">"/logout"</span><span class="tag">/></span><span class="pln"> </span><span class="tag"><form:form</span><span class="pln"> </span><span class="atn">action</span><span class="pun">=</span><span class="atv">"${logoutUrl}"</span><span class="pln"> </span><span class="atn">method</span><span class="pun">=</span><span class="atv">"post"</span><span class="tag">></span><span class="pln"> </span><span class="tag"><input</span><span class="pln"> </span><span class="atn">type</span><span class="pun">=</span><span class="atv">"submit"</span><span class="pln"> </span><span class="atn">value</span><span class="pun">=</span><span class="atv">"Log out"</span><span class="pln"> </span><span class="tag">/></span><span class="pln"> </span><span class="tag"><input</span><span class="pln"> </span><span class="atn">type</span><span class="pun">=</span><span class="atv">"hidden"</span><span class="pln"> </span><span class="atn">name</span><span class="pun">=</span><span class="atv">"${_csrf.parameterName}"</span><span class="pln"> </span><span class="atn">value</span><span class="pun">=</span><span class="atv">"${_csrf.token}"</span><span class="tag">/></span><span class="pln"> </span><span class="tag"></form:form></span><span class="pln"> </span><span class="com"><!-- ... --></span><span class="pln"> </span><span class="tag"></html></span><span class="pln"> </span><span class="tag"></jsp:root></span></code></pre> </div> </div> <div class="paragraph"> <p>Will output HTML that is similar to the following:</p> </div> <div class="listingblock"> <div class="content"> <pre style="" class="prettyprint xml language-xml prettyprinted"><code><span class="com"><!-- ... --></span><span class="pln"> </span><span class="tag"><form</span><span class="pln"> </span><span class="atn">action</span><span class="pun">=</span><span class="atv">"/context/logout"</span><span class="pln"> </span><span class="atn">method</span><span class="pun">=</span><span class="atv">"post"</span><span class="tag">></span><span class="pln"> </span><span class="tag"><input</span><span class="pln"> </span><span class="atn">type</span><span class="pun">=</span><span class="atv">"submit"</span><span class="pln"> </span><span class="atn">value</span><span class="pun">=</span><span class="atv">"Log out"</span><span class="tag">/></span><span class="pln"> </span><span class="tag"><input</span><span class="pln"> </span><span class="atn">type</span><span class="pun">=</span><span class="atv">"hidden"</span><span class="pln"> </span><span class="atn">name</span><span class="pun">=</span><span class="atv">"_csrf"</span><span class="pln"> </span><span class="atn">value</span><span class="pun">=</span><span class="atv">"f81d4fae-7dec-11d0-a765-00a0c91e6bf6"</span><span class="tag">/></span><span class="pln"> </span><span class="tag"></form></span><span class="pln"> </span><span class="com"><!-- ... --></span></code></pre> </div> </div> </div> </div> </div> <h1 id="appendix" class="sect0"><a class="anchor" href="#appendix"></a>Appendix</h1> <div class="sect1"> <h2 id="appendix-schema"><a class="anchor" href="#appendix-schema"></a>1. Security Database Schema</h2> <div class="sectionbody"> <div class="paragraph"> <p>There are various database schema used by the framework and this appendix provides a single reference point to them all. You only need to provide the tables for the areas of functonality you require.</p> </div> <div class="paragraph"> <p>DDL statements are given for the HSQLDB database. You can use these as a guideline for defining the schema for the database you are using.</p> </div> <div class="sect2"> <h3 id="user-schema"><a class="anchor" href="#user-schema"></a>1.1. User Schema</h3> <div class="paragraph"> <p>The standard JDBC implementation of the <code>UserDetailsService</code> (<code>JdbcDaoImpl</code>) requires tables to load the password, account status (enabled or disabled) and a list of authorities (roles) for the user. You will need to adjust this schema to match the database dialect you are using.</p> </div> <div class="listingblock"> <div class="content"> <pre style="" class="prettyprint prettyprinted"><code><span class="pln"> create table users</span><span class="pun">(</span><span class="pln"> username varchar_ignorecase</span><span class="pun">(</span><span class="lit">50</span><span class="pun">)</span><span class="pln"> </span><span class="kwd">not</span><span class="pln"> </span><span class="kwd">null</span><span class="pln"> primary key</span><span class="pun">,</span><span class="pln"> password varchar_ignorecase</span><span class="pun">(</span><span class="lit">50</span><span class="pun">)</span><span class="pln"> </span><span class="kwd">not</span><span class="pln"> </span><span class="kwd">null</span><span class="pun">,</span><span class="pln"> enabled </span><span class="kwd">boolean</span><span class="pln"> </span><span class="kwd">not</span><span class="pln"> </span><span class="kwd">null</span><span class="pln"> </span><span class="pun">);</span><span class="pln"> create table authorities </span><span class="pun">(</span><span class="pln"> username varchar_ignorecase</span><span class="pun">(</span><span class="lit">50</span><span class="pun">)</span><span class="pln"> </span><span class="kwd">not</span><span class="pln"> </span><span class="kwd">null</span><span class="pun">,</span><span class="pln"> authority varchar_ignorecase</span><span class="pun">(</span><span class="lit">50</span><span class="pun">)</span><span class="pln"> </span><span class="kwd">not</span><span class="pln"> </span><span class="kwd">null</span><span class="pun">,</span><span class="pln"> constraint fk_authorities_users foreign key</span><span class="pun">(</span><span class="pln">username</span><span class="pun">)</span><span class="pln"> references users</span><span class="pun">(</span><span class="pln">username</span><span class="pun">)</span><span class="pln"> </span><span class="pun">);</span><span class="pln"> create unique index ix_auth_username on authorities </span><span class="pun">(</span><span class="pln">username</span><span class="pun">,</span><span class="pln">authority</span><span class="pun">);</span></code></pre> </div> </div> <div class="sect3"> <h4 id="group-authorities"><a class="anchor" href="#group-authorities"></a>1.1.1. Group Authorities</h4> <div class="paragraph"> <p>Spring Security 2.0 introduced support for group authorities in <code>JdbcDaoImpl</code>. The table structure if groups are enabled is as follows. You will need to adjust this schema to match the database dialect you are using.</p> </div> <div class="listingblock"> <div class="content"> <pre style="" class="prettyprint prettyprinted"><code><span class="pln"> create table groups </span><span class="pun">(</span><span class="pln"> id bigint generated </span><span class="kwd">by</span><span class="pln"> </span><span class="kwd">default</span><span class="pln"> </span><span class="kwd">as</span><span class="pln"> identity</span><span class="pun">(</span><span class="pln">start </span><span class="kwd">with</span><span class="pln"> </span><span class="lit">0</span><span class="pun">)</span><span class="pln"> primary key</span><span class="pun">,</span><span class="pln"> group_name varchar_ignorecase</span><span class="pun">(</span><span class="lit">50</span><span class="pun">)</span><span class="pln"> </span><span class="kwd">not</span><span class="pln"> </span><span class="kwd">null</span><span class="pln"> </span><span class="pun">);</span><span class="pln"> create table group_authorities </span><span class="pun">(</span><span class="pln"> group_id bigint </span><span class="kwd">not</span><span class="pln"> </span><span class="kwd">null</span><span class="pun">,</span><span class="pln"> authority varchar</span><span class="pun">(</span><span class="lit">50</span><span class="pun">)</span><span class="pln"> </span><span class="kwd">not</span><span class="pln"> </span><span class="kwd">null</span><span class="pun">,</span><span class="pln"> constraint fk_group_authorities_group foreign key</span><span class="pun">(</span><span class="pln">group_id</span><span class="pun">)</span><span class="pln"> references groups</span><span class="pun">(</span><span class="pln">id</span><span class="pun">)</span><span class="pln"> </span><span class="pun">);</span><span class="pln"> create table group_members </span><span class="pun">(</span><span class="pln"> id bigint generated </span><span class="kwd">by</span><span class="pln"> </span><span class="kwd">default</span><span class="pln"> </span><span class="kwd">as</span><span class="pln"> identity</span><span class="pun">(</span><span class="pln">start </span><span class="kwd">with</span><span class="pln"> </span><span class="lit">0</span><span class="pun">)</span><span class="pln"> primary key</span><span class="pun">,</span><span class="pln"> username varchar</span><span class="pun">(</span><span class="lit">50</span><span class="pun">)</span><span class="pln"> </span><span class="kwd">not</span><span class="pln"> </span><span class="kwd">null</span><span class="pun">,</span><span class="pln"> group_id bigint </span><span class="kwd">not</span><span class="pln"> </span><span class="kwd">null</span><span class="pun">,</span><span class="pln"> constraint fk_group_members_group foreign key</span><span class="pun">(</span><span class="pln">group_id</span><span class="pun">)</span><span class="pln"> references groups</span><span class="pun">(</span><span class="pln">id</span><span class="pun">)</span><span class="pln"> </span><span class="pun">);</span></code></pre> </div> </div> <div class="paragraph"> <p>Remember that these tables are only required if you are using the provided JDBC <code>UserDetailsService</code> implementation. If you write your own or choose to implement <code>AuthenticationProvider</code> without a <code>UserDetailsService</code>, then you have complete freedom over how you store the data, as long as the interface contract is satisfied.</p> </div> </div> </div> <div class="sect2"> <h3 id="persistent-login-remember-me-schema"><a class="anchor" href="#persistent-login-remember-me-schema"></a>1.2. Persistent Login (Remember-Me) Schema</h3> <div class="paragraph"> <p>This table is used to store data used by the more secure <a href="#remember-me-persistent-token">persistent token</a> remember-me implementation. If you are using <code>JdbcTokenRepositoryImpl</code> either directly or through the namespace, then you will need this table. Remember to adjust this schema to match the database dialect you are using.</p> </div> <div class="listingblock"> <div class="content"> <pre style="" class="prettyprint prettyprinted"><code><span class="pln"> create table persistent_logins </span><span class="pun">(</span><span class="pln"> username varchar</span><span class="pun">(</span><span class="lit">64</span><span class="pun">)</span><span class="pln"> </span><span class="kwd">not</span><span class="pln"> </span><span class="kwd">null</span><span class="pun">,</span><span class="pln"> series varchar</span><span class="pun">(</span><span class="lit">64</span><span class="pun">)</span><span class="pln"> primary key</span><span class="pun">,</span><span class="pln"> token varchar</span><span class="pun">(</span><span class="lit">64</span><span class="pun">)</span><span class="pln"> </span><span class="kwd">not</span><span class="pln"> </span><span class="kwd">null</span><span class="pun">,</span><span class="pln"> last_used timestamp </span><span class="kwd">not</span><span class="pln"> </span><span class="kwd">null</span><span class="pln"> </span><span class="pun">);</span></code></pre> </div> </div> </div> <div class="sect2"> <h3 id="dbschema-acl"><a class="anchor" href="#dbschema-acl"></a>1.3. ACL Schema</h3> <div class="paragraph"> <p>There are four tables used by the Spring Security <a href="#domain-acls">ACL</a> implementation.</p> </div> <div class="olist arabic"> <ol class="arabic"> <li> <p><code>acl_sid</code> stores the security identities recognised by the ACL system. These can be unique principals or authorities which may apply to multiple principals.</p> </li> <li> <p><code>acl_class</code> defines the domain object types to which ACLs apply. The <code>class</code> column stores the Java class name of the object.</p> </li> <li> <p><code>acl_object_identity</code> stores the object identity definitions of specific domai objects.</p> </li> <li> <p><code>acl_entry</code> stores the ACL permissions which apply to a specific object identity and security identity.</p> </li> </ol> </div> <div class="paragraph"> <p>It is assumed that the database will auto-generate the primary keys for each of the identities. The <code>JdbcMutableAclService</code> has to be able to retrieve these when it has created a new row in the <code>acl_sid</code> or <code>acl_class</code> tables. It has two properties which define the SQL needed to retrieve these values <code>classIdentityQuery</code> and <code>sidIdentityQuery</code>. Both of these default to <code>call identity()</code></p> </div> <div class="paragraph"> <p>The ACL artifact JAR contains files for creating the ACL schema in HyperSQL (HSQLDB), PostgreSQL, MySQL/MariaDB, Microsoft SQL Server, and Oracle Database. These schemas are also demonstrated in the following sections.</p> </div> <div class="sect3"> <h4 id="hypersql"><a class="anchor" href="#hypersql"></a>1.3.1. HyperSQL</h4> <div class="paragraph"> <p>The default schema works with the embedded HSQLDB database that is used in unit tests within the framework.</p> </div> <div class="listingblock"> <div class="content"> <pre style="" class="prettyprint ddl language-ddl prettyprinted"><code><span class="pln"> create table acl_sid</span><span class="pun">(</span><span class="pln"> id bigint generated </span><span class="kwd">by</span><span class="pln"> </span><span class="kwd">default</span><span class="pln"> </span><span class="kwd">as</span><span class="pln"> identity</span><span class="pun">(</span><span class="pln">start </span><span class="kwd">with</span><span class="pln"> </span><span class="lit">100</span><span class="pun">)</span><span class="pln"> </span><span class="kwd">not</span><span class="pln"> </span><span class="kwd">null</span><span class="pln"> primary key</span><span class="pun">,</span><span class="pln"> principal </span><span class="kwd">boolean</span><span class="pln"> </span><span class="kwd">not</span><span class="pln"> </span><span class="kwd">null</span><span class="pun">,</span><span class="pln"> sid varchar_ignorecase</span><span class="pun">(</span><span class="lit">100</span><span class="pun">)</span><span class="pln"> </span><span class="kwd">not</span><span class="pln"> </span><span class="kwd">null</span><span class="pun">,</span><span class="pln"> constraint unique_uk_1 unique</span><span class="pun">(</span><span class="pln">sid</span><span class="pun">,</span><span class="pln">principal</span><span class="pun">)</span><span class="pln"> </span><span class="pun">);</span><span class="pln"> create table acl_class</span><span class="pun">(</span><span class="pln"> id bigint generated </span><span class="kwd">by</span><span class="pln"> </span><span class="kwd">default</span><span class="pln"> </span><span class="kwd">as</span><span class="pln"> identity</span><span class="pun">(</span><span class="pln">start </span><span class="kwd">with</span><span class="pln"> </span><span class="lit">100</span><span class="pun">)</span><span class="pln"> </span><span class="kwd">not</span><span class="pln"> </span><span class="kwd">null</span><span class="pln"> primary key</span><span class="pun">,</span><span class="pln"> </span><span class="kwd">class</span><span class="pln"> varchar_ignorecase</span><span class="pun">(</span><span class="lit">100</span><span class="pun">)</span><span class="pln"> </span><span class="kwd">not</span><span class="pln"> </span><span class="kwd">null</span><span class="pun">,</span><span class="pln"> constraint unique_uk_2 unique</span><span class="pun">(</span><span class="kwd">class</span><span class="pun">)</span><span class="pln"> </span><span class="pun">);</span><span class="pln"> create table acl_object_identity</span><span class="pun">(</span><span class="pln"> id bigint generated </span><span class="kwd">by</span><span class="pln"> </span><span class="kwd">default</span><span class="pln"> </span><span class="kwd">as</span><span class="pln"> identity</span><span class="pun">(</span><span class="pln">start </span><span class="kwd">with</span><span class="pln"> </span><span class="lit">100</span><span class="pun">)</span><span class="pln"> </span><span class="kwd">not</span><span class="pln"> </span><span class="kwd">null</span><span class="pln"> primary key</span><span class="pun">,</span><span class="pln"> object_id_class bigint </span><span class="kwd">not</span><span class="pln"> </span><span class="kwd">null</span><span class="pun">,</span><span class="pln"> object_id_identity bigint </span><span class="kwd">not</span><span class="pln"> </span><span class="kwd">null</span><span class="pun">,</span><span class="pln"> parent_object bigint</span><span class="pun">,</span><span class="pln"> owner_sid bigint</span><span class="pun">,</span><span class="pln"> entries_inheriting </span><span class="kwd">boolean</span><span class="pln"> </span><span class="kwd">not</span><span class="pln"> </span><span class="kwd">null</span><span class="pun">,</span><span class="pln"> constraint unique_uk_3 unique</span><span class="pun">(</span><span class="pln">object_id_class</span><span class="pun">,</span><span class="pln">object_id_identity</span><span class="pun">),</span><span class="pln"> constraint foreign_fk_1 foreign key</span><span class="pun">(</span><span class="pln">parent_object</span><span class="pun">)</span><span class="pln">references acl_object_identity</span><span class="pun">(</span><span class="pln">id</span><span class="pun">),</span><span class="pln"> constraint foreign_fk_2 foreign key</span><span class="pun">(</span><span class="pln">object_id_class</span><span class="pun">)</span><span class="pln">references acl_class</span><span class="pun">(</span><span class="pln">id</span><span class="pun">),</span><span class="pln"> constraint foreign_fk_3 foreign key</span><span class="pun">(</span><span class="pln">owner_sid</span><span class="pun">)</span><span class="pln">references acl_sid</span><span class="pun">(</span><span class="pln">id</span><span class="pun">)</span><span class="pln"> </span><span class="pun">);</span><span class="pln"> create table acl_entry</span><span class="pun">(</span><span class="pln"> id bigint generated </span><span class="kwd">by</span><span class="pln"> </span><span class="kwd">default</span><span class="pln"> </span><span class="kwd">as</span><span class="pln"> identity</span><span class="pun">(</span><span class="pln">start </span><span class="kwd">with</span><span class="pln"> </span><span class="lit">100</span><span class="pun">)</span><span class="pln"> </span><span class="kwd">not</span><span class="pln"> </span><span class="kwd">null</span><span class="pln"> primary key</span><span class="pun">,</span><span class="pln"> acl_object_identity bigint </span><span class="kwd">not</span><span class="pln"> </span><span class="kwd">null</span><span class="pun">,</span><span class="pln"> ace_order </span><span class="kwd">int</span><span class="pln"> </span><span class="kwd">not</span><span class="pln"> </span><span class="kwd">null</span><span class="pun">,</span><span class="pln"> sid bigint </span><span class="kwd">not</span><span class="pln"> </span><span class="kwd">null</span><span class="pun">,</span><span class="pln"> mask integer </span><span class="kwd">not</span><span class="pln"> </span><span class="kwd">null</span><span class="pun">,</span><span class="pln"> granting </span><span class="kwd">boolean</span><span class="pln"> </span><span class="kwd">not</span><span class="pln"> </span><span class="kwd">null</span><span class="pun">,</span><span class="pln"> audit_success </span><span class="kwd">boolean</span><span class="pln"> </span><span class="kwd">not</span><span class="pln"> </span><span class="kwd">null</span><span class="pun">,</span><span class="pln"> audit_failure </span><span class="kwd">boolean</span><span class="pln"> </span><span class="kwd">not</span><span class="pln"> </span><span class="kwd">null</span><span class="pun">,</span><span class="pln"> constraint unique_uk_4 unique</span><span class="pun">(</span><span class="pln">acl_object_identity</span><span class="pun">,</span><span class="pln">ace_order</span><span class="pun">),</span><span class="pln"> constraint foreign_fk_4 foreign key</span><span class="pun">(</span><span class="pln">acl_object_identity</span><span class="pun">)</span><span class="pln"> references acl_object_identity</span><span class="pun">(</span><span class="pln">id</span><span class="pun">),</span><span class="pln"> constraint foreign_fk_5 foreign key</span><span class="pun">(</span><span class="pln">sid</span><span class="pun">)</span><span class="pln"> references acl_sid</span><span class="pun">(</span><span class="pln">id</span><span class="pun">)</span><span class="pln"> </span><span class="pun">);</span></code></pre> </div> </div> </div> <div class="sect3"> <h4 id="postgresql"><a class="anchor" href="#postgresql"></a>1.3.2. PostgreSQL</h4> <div class="listingblock"> <div class="content"> <pre style="" class="prettyprint ddl language-ddl prettyprinted"><code><span class="pln">create table acl_sid</span><span class="pun">(</span><span class="pln"> id bigserial </span><span class="kwd">not</span><span class="pln"> </span><span class="kwd">null</span><span class="pln"> primary key</span><span class="pun">,</span><span class="pln"> principal </span><span class="kwd">boolean</span><span class="pln"> </span><span class="kwd">not</span><span class="pln"> </span><span class="kwd">null</span><span class="pun">,</span><span class="pln"> sid varchar</span><span class="pun">(</span><span class="lit">100</span><span class="pun">)</span><span class="pln"> </span><span class="kwd">not</span><span class="pln"> </span><span class="kwd">null</span><span class="pun">,</span><span class="pln"> constraint unique_uk_1 unique</span><span class="pun">(</span><span class="pln">sid</span><span class="pun">,</span><span class="pln">principal</span><span class="pun">)</span><span class="pln"> </span><span class="pun">);</span><span class="pln"> create table acl_class</span><span class="pun">(</span><span class="pln"> id bigserial </span><span class="kwd">not</span><span class="pln"> </span><span class="kwd">null</span><span class="pln"> primary key</span><span class="pun">,</span><span class="pln"> </span><span class="kwd">class</span><span class="pln"> varchar</span><span class="pun">(</span><span class="lit">100</span><span class="pun">)</span><span class="pln"> </span><span class="kwd">not</span><span class="pln"> </span><span class="kwd">null</span><span class="pun">,</span><span class="pln"> constraint unique_uk_2 unique</span><span class="pun">(</span><span class="kwd">class</span><span class="pun">)</span><span class="pln"> </span><span class="pun">);</span><span class="pln"> create table acl_object_identity</span><span class="pun">(</span><span class="pln"> id bigserial primary key</span><span class="pun">,</span><span class="pln"> object_id_class bigint </span><span class="kwd">not</span><span class="pln"> </span><span class="kwd">null</span><span class="pun">,</span><span class="pln"> object_id_identity bigint </span><span class="kwd">not</span><span class="pln"> </span><span class="kwd">null</span><span class="pun">,</span><span class="pln"> parent_object bigint</span><span class="pun">,</span><span class="pln"> owner_sid bigint</span><span class="pun">,</span><span class="pln"> entries_inheriting </span><span class="kwd">boolean</span><span class="pln"> </span><span class="kwd">not</span><span class="pln"> </span><span class="kwd">null</span><span class="pun">,</span><span class="pln"> constraint unique_uk_3 unique</span><span class="pun">(</span><span class="pln">object_id_class</span><span class="pun">,</span><span class="pln">object_id_identity</span><span class="pun">),</span><span class="pln"> constraint foreign_fk_1 foreign key</span><span class="pun">(</span><span class="pln">parent_object</span><span class="pun">)</span><span class="pln">references acl_object_identity</span><span class="pun">(</span><span class="pln">id</span><span class="pun">),</span><span class="pln"> constraint foreign_fk_2 foreign key</span><span class="pun">(</span><span class="pln">object_id_class</span><span class="pun">)</span><span class="pln">references acl_class</span><span class="pun">(</span><span class="pln">id</span><span class="pun">),</span><span class="pln"> constraint foreign_fk_3 foreign key</span><span class="pun">(</span><span class="pln">owner_sid</span><span class="pun">)</span><span class="pln">references acl_sid</span><span class="pun">(</span><span class="pln">id</span><span class="pun">)</span><span class="pln"> </span><span class="pun">);</span><span class="pln"> create table acl_entry</span><span class="pun">(</span><span class="pln"> id bigserial primary key</span><span class="pun">,</span><span class="pln"> acl_object_identity bigint </span><span class="kwd">not</span><span class="pln"> </span><span class="kwd">null</span><span class="pun">,</span><span class="pln"> ace_order </span><span class="kwd">int</span><span class="pln"> </span><span class="kwd">not</span><span class="pln"> </span><span class="kwd">null</span><span class="pun">,</span><span class="pln"> sid bigint </span><span class="kwd">not</span><span class="pln"> </span><span class="kwd">null</span><span class="pun">,</span><span class="pln"> mask integer </span><span class="kwd">not</span><span class="pln"> </span><span class="kwd">null</span><span class="pun">,</span><span class="pln"> granting </span><span class="kwd">boolean</span><span class="pln"> </span><span class="kwd">not</span><span class="pln"> </span><span class="kwd">null</span><span class="pun">,</span><span class="pln"> audit_success </span><span class="kwd">boolean</span><span class="pln"> </span><span class="kwd">not</span><span class="pln"> </span><span class="kwd">null</span><span class="pun">,</span><span class="pln"> audit_failure </span><span class="kwd">boolean</span><span class="pln"> </span><span class="kwd">not</span><span class="pln"> </span><span class="kwd">null</span><span class="pun">,</span><span class="pln"> constraint unique_uk_4 unique</span><span class="pun">(</span><span class="pln">acl_object_identity</span><span class="pun">,</span><span class="pln">ace_order</span><span class="pun">),</span><span class="pln"> constraint foreign_fk_4 foreign key</span><span class="pun">(</span><span class="pln">acl_object_identity</span><span class="pun">)</span><span class="pln"> references acl_object_identity</span><span class="pun">(</span><span class="pln">id</span><span class="pun">),</span><span class="pln"> constraint foreign_fk_5 foreign key</span><span class="pun">(</span><span class="pln">sid</span><span class="pun">)</span><span class="pln"> references acl_sid</span><span class="pun">(</span><span class="pln">id</span><span class="pun">)</span><span class="pln"> </span><span class="pun">);</span></code></pre> </div> </div> <div class="paragraph"> <p>You will have to set the <code>classIdentityQuery</code> and <code>sidIdentityQuery</code> properties of <code>JdbcMutableAclService</code> to the following values, respectively:</p> </div> <div class="ulist"> <ul> <li> <p><code>select currval(pg_get_serial_sequence('acl_class', 'id'))</code></p> </li> <li> <p><code>select currval(pg_get_serial_sequence('acl_sid', 'id'))</code></p> </li> </ul> </div> </div> <div class="sect3"> <h4 id="mysql-and-mariadb"><a class="anchor" href="#mysql-and-mariadb"></a>1.3.3. MySQL and MariaDB</h4> <div class="listingblock"> <div class="content"> <pre style="" class="prettyprint ddl language-ddl prettyprinted"><code><span class="pln">CREATE TABLE acl_sid </span><span class="pun">(</span><span class="pln"> id BIGINT UNSIGNED NOT NULL AUTO_INCREMENT PRIMARY KEY</span><span class="pun">,</span><span class="pln"> principal BOOLEAN NOT NULL</span><span class="pun">,</span><span class="pln"> sid VARCHAR</span><span class="pun">(</span><span class="lit">100</span><span class="pun">)</span><span class="pln"> NOT NULL</span><span class="pun">,</span><span class="pln"> UNIQUE KEY unique_acl_sid </span><span class="pun">(</span><span class="pln">sid</span><span class="pun">,</span><span class="pln"> principal</span><span class="pun">)</span><span class="pln"> </span><span class="pun">)</span><span class="pln"> ENGINE</span><span class="pun">=</span><span class="typ">InnoDB</span><span class="pun">;</span><span class="pln"> CREATE TABLE acl_class </span><span class="pun">(</span><span class="pln"> id BIGINT UNSIGNED NOT NULL AUTO_INCREMENT PRIMARY KEY</span><span class="pun">,</span><span class="pln"> </span><span class="kwd">class</span><span class="pln"> VARCHAR</span><span class="pun">(</span><span class="lit">100</span><span class="pun">)</span><span class="pln"> NOT NULL</span><span class="pun">,</span><span class="pln"> UNIQUE KEY uk_acl_class </span><span class="pun">(</span><span class="kwd">class</span><span class="pun">)</span><span class="pln"> </span><span class="pun">)</span><span class="pln"> ENGINE</span><span class="pun">=</span><span class="typ">InnoDB</span><span class="pun">;</span><span class="pln"> CREATE TABLE acl_object_identity </span><span class="pun">(</span><span class="pln"> id BIGINT UNSIGNED NOT NULL AUTO_INCREMENT PRIMARY KEY</span><span class="pun">,</span><span class="pln"> object_id_class BIGINT UNSIGNED NOT NULL</span><span class="pun">,</span><span class="pln"> object_id_identity BIGINT NOT NULL</span><span class="pun">,</span><span class="pln"> parent_object BIGINT UNSIGNED</span><span class="pun">,</span><span class="pln"> owner_sid BIGINT UNSIGNED</span><span class="pun">,</span><span class="pln"> entries_inheriting BOOLEAN NOT NULL</span><span class="pun">,</span><span class="pln"> UNIQUE KEY uk_acl_object_identity </span><span class="pun">(</span><span class="pln">object_id_class</span><span class="pun">,</span><span class="pln"> object_id_identity</span><span class="pun">),</span><span class="pln"> CONSTRAINT fk_acl_object_identity_parent FOREIGN KEY </span><span class="pun">(</span><span class="pln">parent_object</span><span class="pun">)</span><span class="pln"> REFERENCES acl_object_identity </span><span class="pun">(</span><span class="pln">id</span><span class="pun">),</span><span class="pln"> CONSTRAINT fk_acl_object_identity_class FOREIGN KEY </span><span class="pun">(</span><span class="pln">object_id_class</span><span class="pun">)</span><span class="pln"> REFERENCES acl_class </span><span class="pun">(</span><span class="pln">id</span><span class="pun">),</span><span class="pln"> CONSTRAINT fk_acl_object_identity_owner FOREIGN KEY </span><span class="pun">(</span><span class="pln">owner_sid</span><span class="pun">)</span><span class="pln"> REFERENCES acl_sid </span><span class="pun">(</span><span class="pln">id</span><span class="pun">)</span><span class="pln"> </span><span class="pun">)</span><span class="pln"> ENGINE</span><span class="pun">=</span><span class="typ">InnoDB</span><span class="pun">;</span><span class="pln"> CREATE TABLE acl_entry </span><span class="pun">(</span><span class="pln"> id BIGINT UNSIGNED NOT NULL AUTO_INCREMENT PRIMARY KEY</span><span class="pun">,</span><span class="pln"> acl_object_identity BIGINT UNSIGNED NOT NULL</span><span class="pun">,</span><span class="pln"> ace_order INTEGER NOT NULL</span><span class="pun">,</span><span class="pln"> sid BIGINT UNSIGNED NOT NULL</span><span class="pun">,</span><span class="pln"> mask INTEGER UNSIGNED NOT NULL</span><span class="pun">,</span><span class="pln"> granting BOOLEAN NOT NULL</span><span class="pun">,</span><span class="pln"> audit_success BOOLEAN NOT NULL</span><span class="pun">,</span><span class="pln"> audit_failure BOOLEAN NOT NULL</span><span class="pun">,</span><span class="pln"> UNIQUE KEY unique_acl_entry </span><span class="pun">(</span><span class="pln">acl_object_identity</span><span class="pun">,</span><span class="pln"> ace_order</span><span class="pun">),</span><span class="pln"> CONSTRAINT fk_acl_entry_object FOREIGN KEY </span><span class="pun">(</span><span class="pln">acl_object_identity</span><span class="pun">)</span><span class="pln"> REFERENCES acl_object_identity </span><span class="pun">(</span><span class="pln">id</span><span class="pun">),</span><span class="pln"> CONSTRAINT fk_acl_entry_acl FOREIGN KEY </span><span class="pun">(</span><span class="pln">sid</span><span class="pun">)</span><span class="pln"> REFERENCES acl_sid </span><span class="pun">(</span><span class="pln">id</span><span class="pun">)</span><span class="pln"> </span><span class="pun">)</span><span class="pln"> ENGINE</span><span class="pun">=</span><span class="typ">InnoDB</span><span class="pun">;</span></code></pre> </div> </div> </div> <div class="sect3"> <h4 id="microsoft-sql-server"><a class="anchor" href="#microsoft-sql-server"></a>1.3.4. Microsoft SQL Server</h4> <div class="listingblock"> <div class="content"> <pre style="" class="prettyprint ddl language-ddl prettyprinted"><code><span class="pln">CREATE TABLE acl_sid </span><span class="pun">(</span><span class="pln"> id BIGINT NOT NULL IDENTITY PRIMARY KEY</span><span class="pun">,</span><span class="pln"> principal BIT NOT NULL</span><span class="pun">,</span><span class="pln"> sid VARCHAR</span><span class="pun">(</span><span class="lit">100</span><span class="pun">)</span><span class="pln"> NOT NULL</span><span class="pun">,</span><span class="pln"> CONSTRAINT unique_acl_sid UNIQUE </span><span class="pun">(</span><span class="pln">sid</span><span class="pun">,</span><span class="pln"> principal</span><span class="pun">)</span><span class="pln"> </span><span class="pun">);</span><span class="pln"> CREATE TABLE acl_class </span><span class="pun">(</span><span class="pln"> id BIGINT NOT NULL IDENTITY PRIMARY KEY</span><span class="pun">,</span><span class="pln"> </span><span class="kwd">class</span><span class="pln"> VARCHAR</span><span class="pun">(</span><span class="lit">100</span><span class="pun">)</span><span class="pln"> NOT NULL</span><span class="pun">,</span><span class="pln"> CONSTRAINT uk_acl_class UNIQUE </span><span class="pun">(</span><span class="kwd">class</span><span class="pun">)</span><span class="pln"> </span><span class="pun">);</span><span class="pln"> CREATE TABLE acl_object_identity </span><span class="pun">(</span><span class="pln"> id BIGINT NOT NULL IDENTITY PRIMARY KEY</span><span class="pun">,</span><span class="pln"> object_id_class BIGINT NOT NULL</span><span class="pun">,</span><span class="pln"> object_id_identity BIGINT NOT NULL</span><span class="pun">,</span><span class="pln"> parent_object BIGINT</span><span class="pun">,</span><span class="pln"> owner_sid BIGINT</span><span class="pun">,</span><span class="pln"> entries_inheriting BIT NOT NULL</span><span class="pun">,</span><span class="pln"> CONSTRAINT uk_acl_object_identity UNIQUE </span><span class="pun">(</span><span class="pln">object_id_class</span><span class="pun">,</span><span class="pln"> object_id_identity</span><span class="pun">),</span><span class="pln"> CONSTRAINT fk_acl_object_identity_parent FOREIGN KEY </span><span class="pun">(</span><span class="pln">parent_object</span><span class="pun">)</span><span class="pln"> REFERENCES acl_object_identity </span><span class="pun">(</span><span class="pln">id</span><span class="pun">),</span><span class="pln"> CONSTRAINT fk_acl_object_identity_class FOREIGN KEY </span><span class="pun">(</span><span class="pln">object_id_class</span><span class="pun">)</span><span class="pln"> REFERENCES acl_class </span><span class="pun">(</span><span class="pln">id</span><span class="pun">),</span><span class="pln"> CONSTRAINT fk_acl_object_identity_owner FOREIGN KEY </span><span class="pun">(</span><span class="pln">owner_sid</span><span class="pun">)</span><span class="pln"> REFERENCES acl_sid </span><span class="pun">(</span><span class="pln">id</span><span class="pun">)</span><span class="pln"> </span><span class="pun">);</span><span class="pln"> CREATE TABLE acl_entry </span><span class="pun">(</span><span class="pln"> id BIGINT NOT NULL IDENTITY PRIMARY KEY</span><span class="pun">,</span><span class="pln"> acl_object_identity BIGINT NOT NULL</span><span class="pun">,</span><span class="pln"> ace_order INTEGER NOT NULL</span><span class="pun">,</span><span class="pln"> sid BIGINT NOT NULL</span><span class="pun">,</span><span class="pln"> mask INTEGER NOT NULL</span><span class="pun">,</span><span class="pln"> granting BIT NOT NULL</span><span class="pun">,</span><span class="pln"> audit_success BIT NOT NULL</span><span class="pun">,</span><span class="pln"> audit_failure BIT NOT NULL</span><span class="pun">,</span><span class="pln"> CONSTRAINT unique_acl_entry UNIQUE </span><span class="pun">(</span><span class="pln">acl_object_identity</span><span class="pun">,</span><span class="pln"> ace_order</span><span class="pun">),</span><span class="pln"> CONSTRAINT fk_acl_entry_object FOREIGN KEY </span><span class="pun">(</span><span class="pln">acl_object_identity</span><span class="pun">)</span><span class="pln"> REFERENCES acl_object_identity </span><span class="pun">(</span><span class="pln">id</span><span class="pun">),</span><span class="pln"> CONSTRAINT fk_acl_entry_acl FOREIGN KEY </span><span class="pun">(</span><span class="pln">sid</span><span class="pun">)</span><span class="pln"> REFERENCES acl_sid </span><span class="pun">(</span><span class="pln">id</span><span class="pun">)</span><span class="pln"> </span><span class="pun">);</span></code></pre> </div> </div> </div> <div class="sect3"> <h4 id="oracle-database"><a class="anchor" href="#oracle-database"></a>1.3.5. Oracle Database</h4> <div class="listingblock"> <div class="content"> <pre style="" class="prettyprint ddl language-ddl prettyprinted"><code><span class="pln">CREATE TABLE acl_sid </span><span class="pun">(</span><span class="pln"> id NUMBER</span><span class="pun">(</span><span class="lit">38</span><span class="pun">)</span><span class="pln"> NOT NULL PRIMARY KEY</span><span class="pun">,</span><span class="pln"> principal NUMBER</span><span class="pun">(</span><span class="lit">1</span><span class="pun">)</span><span class="pln"> NOT NULL CHECK </span><span class="pun">(</span><span class="pln">principal </span><span class="kwd">in</span><span class="pln"> </span><span class="pun">(</span><span class="lit">0</span><span class="pun">,</span><span class="pln"> </span><span class="lit">1</span><span class="pun">)),</span><span class="pln"> sid NVARCHAR2</span><span class="pun">(</span><span class="lit">100</span><span class="pun">)</span><span class="pln"> NOT NULL</span><span class="pun">,</span><span class="pln"> CONSTRAINT unique_acl_sid UNIQUE </span><span class="pun">(</span><span class="pln">sid</span><span class="pun">,</span><span class="pln"> principal</span><span class="pun">)</span><span class="pln"> </span><span class="pun">);</span><span class="pln"> CREATE SEQUENCE acl_sid_sequence START WITH </span><span class="lit">1</span><span class="pln"> INCREMENT BY </span><span class="lit">1</span><span class="pln"> NOMAXVALUE</span><span class="pun">;</span><span class="pln"> CREATE OR REPLACE TRIGGER acl_sid_id_trigger BEFORE INSERT ON acl_sid FOR EACH ROW </span><span class="kwd">BEGIN</span><span class="pln"> SELECT acl_sid_sequence</span><span class="pun">.</span><span class="pln">nextval INTO </span><span class="pun">:</span><span class="kwd">new</span><span class="pun">.</span><span class="pln">id FROM dual</span><span class="pun">;</span><span class="pln"> </span><span class="kwd">END</span><span class="pun">;</span><span class="pln"> CREATE TABLE acl_class </span><span class="pun">(</span><span class="pln"> id NUMBER</span><span class="pun">(</span><span class="lit">38</span><span class="pun">)</span><span class="pln"> NOT NULL PRIMARY KEY</span><span class="pun">,</span><span class="pln"> </span><span class="kwd">class</span><span class="pln"> NVARCHAR2</span><span class="pun">(</span><span class="lit">100</span><span class="pun">)</span><span class="pln"> NOT NULL</span><span class="pun">,</span><span class="pln"> CONSTRAINT uk_acl_class UNIQUE </span><span class="pun">(</span><span class="kwd">class</span><span class="pun">)</span><span class="pln"> </span><span class="pun">);</span><span class="pln"> CREATE SEQUENCE acl_class_sequence START WITH </span><span class="lit">1</span><span class="pln"> INCREMENT BY </span><span class="lit">1</span><span class="pln"> NOMAXVALUE</span><span class="pun">;</span><span class="pln"> CREATE OR REPLACE TRIGGER acl_class_id_trigger BEFORE INSERT ON acl_class FOR EACH ROW </span><span class="kwd">BEGIN</span><span class="pln"> SELECT acl_class_sequence</span><span class="pun">.</span><span class="pln">nextval INTO </span><span class="pun">:</span><span class="kwd">new</span><span class="pun">.</span><span class="pln">id FROM dual</span><span class="pun">;</span><span class="pln"> </span><span class="kwd">END</span><span class="pun">;</span><span class="pln"> CREATE TABLE acl_object_identity </span><span class="pun">(</span><span class="pln"> id NUMBER</span><span class="pun">(</span><span class="lit">38</span><span class="pun">)</span><span class="pln"> NOT NULL PRIMARY KEY</span><span class="pun">,</span><span class="pln"> object_id_class NUMBER</span><span class="pun">(</span><span class="lit">38</span><span class="pun">)</span><span class="pln"> NOT NULL</span><span class="pun">,</span><span class="pln"> object_id_identity NUMBER</span><span class="pun">(</span><span class="lit">38</span><span class="pun">)</span><span class="pln"> NOT NULL</span><span class="pun">,</span><span class="pln"> parent_object NUMBER</span><span class="pun">(</span><span class="lit">38</span><span class="pun">),</span><span class="pln"> owner_sid NUMBER</span><span class="pun">(</span><span class="lit">38</span><span class="pun">),</span><span class="pln"> entries_inheriting NUMBER</span><span class="pun">(</span><span class="lit">1</span><span class="pun">)</span><span class="pln"> NOT NULL CHECK </span><span class="pun">(</span><span class="pln">entries_inheriting </span><span class="kwd">in</span><span class="pln"> </span><span class="pun">(</span><span class="lit">0</span><span class="pun">,</span><span class="pln"> </span><span class="lit">1</span><span class="pun">)),</span><span class="pln"> CONSTRAINT uk_acl_object_identity UNIQUE </span><span class="pun">(</span><span class="pln">object_id_class</span><span class="pun">,</span><span class="pln"> object_id_identity</span><span class="pun">),</span><span class="pln"> CONSTRAINT fk_acl_object_identity_parent FOREIGN KEY </span><span class="pun">(</span><span class="pln">parent_object</span><span class="pun">)</span><span class="pln"> REFERENCES acl_object_identity </span><span class="pun">(</span><span class="pln">id</span><span class="pun">),</span><span class="pln"> CONSTRAINT fk_acl_object_identity_class FOREIGN KEY </span><span class="pun">(</span><span class="pln">object_id_class</span><span class="pun">)</span><span class="pln"> REFERENCES acl_class </span><span class="pun">(</span><span class="pln">id</span><span class="pun">),</span><span class="pln"> CONSTRAINT fk_acl_object_identity_owner FOREIGN KEY </span><span class="pun">(</span><span class="pln">owner_sid</span><span class="pun">)</span><span class="pln"> REFERENCES acl_sid </span><span class="pun">(</span><span class="pln">id</span><span class="pun">)</span><span class="pln"> </span><span class="pun">);</span><span class="pln"> CREATE SEQUENCE acl_object_identity_sequence START WITH </span><span class="lit">1</span><span class="pln"> INCREMENT BY </span><span class="lit">1</span><span class="pln"> NOMAXVALUE</span><span class="pun">;</span><span class="pln"> CREATE OR REPLACE TRIGGER acl_object_identity_id_trigger BEFORE INSERT ON acl_object_identity FOR EACH ROW </span><span class="kwd">BEGIN</span><span class="pln"> SELECT acl_object_identity_sequence</span><span class="pun">.</span><span class="pln">nextval INTO </span><span class="pun">:</span><span class="kwd">new</span><span class="pun">.</span><span class="pln">id FROM dual</span><span class="pun">;</span><span class="pln"> </span><span class="kwd">END</span><span class="pun">;</span><span class="pln"> CREATE TABLE acl_entry </span><span class="pun">(</span><span class="pln"> id NUMBER</span><span class="pun">(</span><span class="lit">38</span><span class="pun">)</span><span class="pln"> NOT NULL PRIMARY KEY</span><span class="pun">,</span><span class="pln"> acl_object_identity NUMBER</span><span class="pun">(</span><span class="lit">38</span><span class="pun">)</span><span class="pln"> NOT NULL</span><span class="pun">,</span><span class="pln"> ace_order INTEGER NOT NULL</span><span class="pun">,</span><span class="pln"> sid NUMBER</span><span class="pun">(</span><span class="lit">38</span><span class="pun">)</span><span class="pln"> NOT NULL</span><span class="pun">,</span><span class="pln"> mask INTEGER NOT NULL</span><span class="pun">,</span><span class="pln"> granting NUMBER</span><span class="pun">(</span><span class="lit">1</span><span class="pun">)</span><span class="pln"> NOT NULL CHECK </span><span class="pun">(</span><span class="pln">granting </span><span class="kwd">in</span><span class="pln"> </span><span class="pun">(</span><span class="lit">0</span><span class="pun">,</span><span class="pln"> </span><span class="lit">1</span><span class="pun">)),</span><span class="pln"> audit_success NUMBER</span><span class="pun">(</span><span class="lit">1</span><span class="pun">)</span><span class="pln"> NOT NULL CHECK </span><span class="pun">(</span><span class="pln">audit_success </span><span class="kwd">in</span><span class="pln"> </span><span class="pun">(</span><span class="lit">0</span><span class="pun">,</span><span class="pln"> </span><span class="lit">1</span><span class="pun">)),</span><span class="pln"> audit_failure NUMBER</span><span class="pun">(</span><span class="lit">1</span><span class="pun">)</span><span class="pln"> NOT NULL CHECK </span><span class="pun">(</span><span class="pln">audit_failure </span><span class="kwd">in</span><span class="pln"> </span><span class="pun">(</span><span class="lit">0</span><span class="pun">,</span><span class="pln"> </span><span class="lit">1</span><span class="pun">)),</span><span class="pln"> CONSTRAINT unique_acl_entry UNIQUE </span><span class="pun">(</span><span class="pln">acl_object_identity</span><span class="pun">,</span><span class="pln"> ace_order</span><span class="pun">),</span><span class="pln"> CONSTRAINT fk_acl_entry_object FOREIGN KEY </span><span class="pun">(</span><span class="pln">acl_object_identity</span><span class="pun">)</span><span class="pln"> REFERENCES acl_object_identity </span><span class="pun">(</span><span class="pln">id</span><span class="pun">),</span><span class="pln"> CONSTRAINT fk_acl_entry_acl FOREIGN KEY </span><span class="pun">(</span><span class="pln">sid</span><span class="pun">)</span><span class="pln"> REFERENCES acl_sid </span><span class="pun">(</span><span class="pln">id</span><span class="pun">)</span><span class="pln"> </span><span class="pun">);</span><span class="pln"> CREATE SEQUENCE acl_entry_sequence START WITH </span><span class="lit">1</span><span class="pln"> INCREMENT BY </span><span class="lit">1</span><span class="pln"> NOMAXVALUE</span><span class="pun">;</span><span class="pln"> CREATE OR REPLACE TRIGGER acl_entry_id_trigger BEFORE INSERT ON acl_entry FOR EACH ROW </span><span class="kwd">BEGIN</span><span class="pln"> SELECT acl_entry_sequence</span><span class="pun">.</span><span class="pln">nextval INTO </span><span class="pun">:</span><span class="kwd">new</span><span class="pun">.</span><span class="pln">id FROM dual</span><span class="pun">;</span><span class="pln"> </span><span class="kwd">END</span><span class="pun">;</span></code></pre> </div> </div> </div> </div> </div> </div> <div class="sect1"> <h2 id="appendix-namespace"><a class="anchor" href="#appendix-namespace"></a>2. The Security Namespace</h2> <div class="sectionbody"> <div class="paragraph"> <p>This appendix provides a reference to the elements available in the security namespace and information on the underlying beans they create (a knowledge of the individual classes and how they work together is assumed - you can find more information in the project Javadoc and elsewhere in this document). If you haven’t used the namespace before, please read the <a href="#ns-config">introductory chapter</a> on namespace configuration, as this is intended as a supplement to the information there. Using a good quality XML editor while editing a configuration based on the schema is recommended as this will provide contextual information on which elements and attributes are available as well as comments explaining their purpose. The namespace is written in <a href="http://www.relaxng.org/">RELAX NG</a> Compact format and later converted into an XSD schema. If you are familiar with this format, you may wish to examine the <a href="https://fisheye.springsource.org/browse/spring-security/config/src/main/resources/org/springframework/security/config/spring-security-3.2.rnc">schema file</a> directly.</p> </div> <div class="sect2"> <h3 id="nsa-web"><a class="anchor" href="#nsa-web"></a>2.1. Web Application Security</h3> <div class="sect3"> <h4 id="nsa-debug"><a class="anchor" href="#nsa-debug"></a>2.1.1. <debug></h4> <div class="paragraph"> <p>Enables Spring Security debugging infrastructure. This will provide human-readable (multi-line) debugging information to monitor requests coming into the security filters. This may include sensitive information, such as request parameters or headers, and should only be used in a development environment.</p> </div> </div> <div class="sect3"> <h4 id="nsa-http"><a class="anchor" href="#nsa-http"></a>2.1.2. <http></h4> <div class="paragraph"> <p>If you use an <code><http></code> element within your application, a <code>FilterChainProxy</code> bean named "springSecurityFilterChain" is created and the configuration within the element is used to build a filter chain within <code>FilterChainProxy</code>. As of Spring Security 3.1, additional <code>http</code> elements can be used to add extra filter chains <span class="footnote">[<a id="_footnoteref_24" class="footnote" href="#_footnote_24" title="View footnote.">24</a>]</span>. Some core filters are always created in a filter chain and others will be added to the stack depending on the attributes and child elements which are present. The positions of the standard filters are fixed (see <a href="#filter-stack">the filter order table</a> in the namespace introduction), removing a common source of errors with previous versions of the framework when users had to configure the filter chain explicitly in the <code>FilterChainProxy</code> bean. You can, of course, still do this if you need full control of the configuration.</p> </div> <div class="paragraph"> <p>All filters which require a reference to the <code>AuthenticationManager</code> will be automatically injected with the internal instance created by the namespace configuration (see the <a href="#ns-auth-manager">introductory chapter</a> for more on the <code>AuthenticationManager</code>).</p> </div> <div class="paragraph"> <p>Each <code><http></code> namespace block always creates an <code>SecurityContextPersistenceFilter</code>, an <code>ExceptionTranslationFilter</code> and a <code>FilterSecurityInterceptor</code>. These are fixed and cannot be replaced with alternatives.</p> </div> <div class="sect4"> <h5 id="nsa-http-attributes"><a class="anchor" href="#nsa-http-attributes"></a><http> Attributes</h5> <div class="paragraph"> <p>The attributes on the <code><http></code> element control some of the properties on the core filters.</p> </div> <div id="nsa-http-access-decision-manager-ref" class="ulist"> <ul> <li> <p><strong>access-decision-manager-ref</strong> Optional attribute specifying the ID of the <code>AccessDecisionManager</code> implementation which should be used for authorizing HTTP requests. By default an <code>AffirmativeBased</code> implementation is used for with a <code>RoleVoter</code> and an <code>AuthenticatedVoter</code>.</p> </li> </ul> </div> <div id="nsa-http-access-denied-page" class="ulist"> <ul> <li> <p><strong>access-denied-page</strong> Deprecated in favour of the <a href="#nsa-access-denied-handler">access-denied-handler</a> child element.</p> </li> </ul> </div> <div id="nsa-http-authentication-manager-ref" class="ulist"> <ul> <li> <p><strong>authentication-manager-ref</strong> A reference to the <code>AuthenticationManager</code> used for the <code>FilterChain</code> created by this http element.</p> </li> </ul> </div> <div id="nsa-http-auto-config" class="ulist"> <ul> <li> <p><strong>auto-config</strong> Automatically registers a login form, BASIC authentication, logout services. If set to "true", all of these capabilities are added (although you can still customize the configuration of each by providing the respective element). If unspecified, defaults to "false". Use of this attribute is not recommended. Use explicit configuration elements instead to avoid confusion.</p> </li> </ul> </div> <div id="nsa-http-create-session" class="ulist"> <ul> <li> <p><strong>create-session</strong> Controls the eagerness with which an HTTP session is created by Spring Security classes. Options include:</p> <div class="ulist"> <ul> <li> <p><code>always</code> - Spring Security will proactively create a session if one does not exist.</p> </li> <li> <p><code>ifRequired</code> - Spring Security will only create a session only if one is required (default value).</p> </li> <li> <p><code>never</code> - Spring Security will never create a session, but will make use of one if the application does.</p> </li> <li> <p><code>stateless</code> - Spring Security will not create a session and ignore the session for obtaining a Spring <code>Authentication</code>.</p> </li> </ul> </div> </li> </ul> </div> <div id="nsa-http-disable-url-rewriting" class="ulist"> <ul> <li> <p><strong>disable-url-rewriting</strong> Prevents session IDs from being appended to URLs in the application. Clients must use cookies if this attribute is set to <code>true</code>. The default is <code>false</code>.</p> </li> </ul> </div> <div id="nsa-http-entry-point-ref" class="ulist"> <ul> <li> <p><strong>entry-point-ref</strong> Normally the <code>AuthenticationEntryPoint</code> used will be set depending on which authentication mechanisms have been configured. This attribute allows this behaviour to be overridden by defining a customized <code>AuthenticationEntryPoint</code> bean which will start the authentication process.</p> </li> </ul> </div> <div id="nsa-http-jaas-api-provision" class="ulist"> <ul> <li> <p><strong>jaas-api-provision</strong> If available, runs the request as the <code>Subject</code> acquired from the <code>JaasAuthenticationToken</code> which is implemented by adding a <code>JaasApiIntegrationFilter</code> bean to the stack. Defaults to <code>false</code>.</p> </li> </ul> </div> <div id="nsa-http-name" class="ulist"> <ul> <li> <p><strong>name</strong> A bean identifier, used for referring to the bean elsewhere in the context.</p> </li> </ul> </div> <div id="nsa-http-once-per-request" class="ulist"> <ul> <li> <p><strong>once-per-request</strong> Corresponds to the <code>observeOncePerRequest</code> property of <code>FilterSecurityInterceptor</code>. Defaults to <code>true</code>.</p> </li> </ul> </div> <div id="nsa-http-path-type" class="ulist"> <ul> <li> <p><strong>path-type</strong> Deprecated in favor of <a href="#nsa-http-request-matcher">request-matcher</a>.</p> </li> </ul> </div> <div id="nsa-http-pattern" class="ulist"> <ul> <li> <p><strong>pattern</strong> Defining a pattern for the <a href="#nsa-http">http</a> element controls the requests which will be filtered through the list of filters which it defines. The interpretation is dependent on the configured <a href="#nsa-http-request-matcher">request-matcher</a>. If no pattern is defined, all requests will be matched, so the most specific patterns should be declared first.</p> </li> </ul> </div> <div id="nsa-http-realm" class="ulist"> <ul> <li> <p><strong>realm</strong> Sets the realm name used for basic authentication (if enabled). Corresponds to the <code>realmName</code> property on <code>BasicAuthenticationEntryPoint</code>.</p> </li> </ul> </div> <div id="nsa-http-request-matcher" class="ulist"> <ul> <li> <p><strong>request-matcher</strong> Defines the <code>RequestMatcher</code> strategy used in the <code>FilterChainProxy</code> and the beans created by the <code>intercept-url</code> to match incoming requests. Options are currently <code>ant</code>, <code>regex</code> and <code>ciRegex</code>, for ant, regular-expression and case-insensitive regular-expression repsectively. A separate instance is created for each<a href="#nsa-intercept-url">intercept-url</a> element using its <a href="#nsa-intercept-url-pattern">pattern</a> and <a href="#nsa-intercept-url-method">method</a> attributes. Ant paths are matched using an <code>AntPathRequestMatcher</code> and regular expressions are matched using a <code>RegexRequestMatcher</code>. See the Javadoc for these classes for more details on exactly how the matching is preformed. Ant paths are the default strategy.</p> </li> </ul> </div> <div id="nsa-http-request-matcher-ref" class="ulist"> <ul> <li> <p><strong>request-matcher-ref</strong> A referenece to a bean that implements <code>RequestMatcher</code> that will determine if this <code>FilterChain</code> should be used. This is a more powerful alternative to <a href="#nsa-http-pattern">pattern</a>.</p> </li> </ul> </div> <div id="nsa-http-security" class="ulist"> <ul> <li> <p><strong>security</strong> A request pattern can be mapped to an empty filter chain, by setting this attribute to <code>none</code>. No security will be applied and none of Spring Security’s features will be available.</p> </li> </ul> </div> <div id="nsa-http-security-context-repository-ref" class="ulist"> <ul> <li> <p><strong>security-context-repository-ref</strong> Allows injection of a custom <code>SecurityContextRepository</code> into the <code>SecurityContextPersistenceFilter</code>.</p> </li> </ul> </div> <div id="nsa-http-servlet-api-provision" class="ulist"> <ul> <li> <p><strong>servlet-api-provision</strong> Provides versions of <code>HttpServletRequest</code> security methods such as <code>isUserInRole()</code> and <code>getPrincipal()</code> which are implemented by adding a <code>SecurityContextHolderAwareRequestFilter</code> bean to the stack. Defaults to <code>true</code>.</p> </li> </ul> </div> <div id="nsa-http-use-expressions" class="ulist"> <ul> <li> <p><strong>use-expressions</strong> Enables EL-expressions in the <code>access</code> attribute, as described in the chapter on <a href="#el-access-web">expression-based access-control</a>.</p> </li> </ul> </div> </div> <div class="sect4"> <h5 id="nsa-http-children"><a class="anchor" href="#nsa-http-children"></a>Child Elements of <http></h5> <div class="ulist"> <ul> <li> <p><a href="#nsa-access-denied-handler">access-denied-handler</a></p> </li> <li> <p><a href="#nsa-anonymous">anonymous</a></p> </li> <li> <p><a href="#nsa-csrf">csrf</a></p> </li> <li> <p><a href="#nsa-custom-filter">custom-filter</a></p> </li> <li> <p><a href="#nsa-expression-handler">expression-handler</a></p> </li> <li> <p><a href="#nsa-form-login">form-login</a></p> </li> <li> <p><a href="#nsa-headers">headers</a></p> </li> <li> <p><a href="#nsa-http-basic">http-basic</a></p> </li> <li> <p><a href="#nsa-intercept-url">intercept-url</a></p> </li> <li> <p><a href="#nsa-jee">jee</a></p> </li> <li> <p><a href="#nsa-logout">logout</a></p> </li> <li> <p><a href="#nsa-openid-login">openid-login</a></p> </li> <li> <p><a href="#nsa-port-mappings">port-mappings</a></p> </li> <li> <p><a href="#nsa-remember-me">remember-me</a></p> </li> <li> <p><a href="#nsa-request-cache">request-cache</a></p> </li> <li> <p><a href="#nsa-session-management">session-management</a></p> </li> <li> <p><a href="#nsa-x509">x509</a></p> </li> </ul> </div> </div> </div> <div class="sect3"> <h4 id="nsa-access-denied-handler"><a class="anchor" href="#nsa-access-denied-handler"></a>2.1.3. <access-denied-handler></h4> <div class="paragraph"> <p>This element allows you to set the <code>errorPage</code> property for the default <code>AccessDeniedHandler</code> used by the <code>ExceptionTranslationFilter</code>, using the <a href="#nsa-access-denied-handler-error-page">error-page</a> attribute, or to supply your own implementation using the<a href="#nsa-access-denied-handler-ref">ref</a> attribute. This is discussed in more detail in the section on the <a href="#access-denied-handler">ExceptionTranslationFilter</a>.</p> </div> <div class="sect4"> <h5 id="nsa-access-denied-handler-parents"><a class="anchor" href="#nsa-access-denied-handler-parents"></a>Parent Elements of <access-denied-handler></h5> <div class="ulist"> <ul> <li> <p><a href="#nsa-http">http</a></p> </li> </ul> </div> </div> <div class="sect4"> <h5 id="nsa-access-denied-handler-attributes"><a class="anchor" href="#nsa-access-denied-handler-attributes"></a><access-denied-handler> Attributes</h5> <div id="nsa-access-denied-handler-error-page" class="ulist"> <ul> <li> <p><strong>error-page</strong> The access denied page that an authenticated user will be redirected to if they request a page which they don’t have the authority to access.</p> </li> </ul> </div> <div id="nsa-access-denied-handler-ref" class="ulist"> <ul> <li> <p><strong>ref</strong> Defines a reference to a Spring bean of type `AccessDeniedHandler `.</p> </li> </ul> </div> </div> </div> <div class="sect3"> <h4 id="nsa-headers"><a class="anchor" href="#nsa-headers"></a>2.1.4. <headers></h4> <div class="paragraph"> <p>This element allows for configuring additional (security) headers to be send with the response. It enables easy configuration for several headers and also allows for setting custom headers through the <a href="#nsa-header">header</a> element. Additional information, can be found in the <a href="#headers">Security Headers</a> section of the reference.</p> </div> <div class="ulist"> <ul> <li> <p><code>Cache-Control</code>, <code>Pragma</code>, and <code>Expires</code> - Can be set using the <a href="#nsa-cache-control">cache-control</a> element. This ensures that the browser does not cache your secured pages.</p> </li> <li> <p><code>Strict-Transport-Security</code> - Can be set using the <a href="#nsa-hsts">hsts</a> element. This ensures that the browser automatically requests HTTPS for future requests.</p> </li> <li> <p><code>X-Frame-Options</code> - Can be set using the <a href="#nsa-frame-options">frame-options</a> element. The <a href="http://en.wikipedia.org/wiki/Clickjacking#X-Frame-Options">X-Frame-Options </a> header can be used to prevent clickjacking attacks.</p> </li> <li> <p><code>X-XSS-Protection</code> - Can be set using the <a href="#nsa-xss-protection">xss-protection</a> element. The <a href="http://en.wikipedia.org/wiki/Cross-site_scripting">X-XSS-Protection </a> header can be used by browser to do basic control.</p> </li> <li> <p><code>X-Content-Type-Options</code> - Can be set using the <a href="#nsa-content-type-options">content-type-options</a> element. The <a href="http://blogs.msdn.com/b/ie/archive/2008/09/02/ie8-security-part-vi-beta-2-update.aspx">X-Content-Type-Options</a> header prevents Internet Explorer from MIME-sniffing a response away from the declared content-type. This also applies to Google Chrome, when downloading extensions.</p> </li> </ul> </div> <div class="sect4"> <h5 id="nsa-headers-parents"><a class="anchor" href="#nsa-headers-parents"></a>Parent Elements of <headers></h5> <div class="ulist"> <ul> <li> <p><a href="#nsa-http">http</a></p> </li> </ul> </div> </div> <div class="sect4"> <h5 id="nsa-headers-children"><a class="anchor" href="#nsa-headers-children"></a>Child Elements of <headers></h5> <div class="ulist"> <ul> <li> <p><a href="#nsa-cache-control">cache-control</a></p> </li> <li> <p><a href="#nsa-content-type-options">content-type-options</a></p> </li> <li> <p><a href="#nsa-frame-options">frame-options</a></p> </li> <li> <p><a href="#nsa-header">header</a></p> </li> <li> <p><a href="#nsa-hsts">hsts</a></p> </li> <li> <p><a href="#nsa-xss-protection">xss-protection</a></p> </li> </ul> </div> </div> </div> <div class="sect3"> <h4 id="nsa-cache-control"><a class="anchor" href="#nsa-cache-control"></a>2.1.5. <cache-control></h4> <div class="paragraph"> <p>Adds <code>Cache-Control</code>, <code>Pragma</code>, and <code>Expires</code> headers to ensure that the browser does not cache your secured pages.</p> </div> <div class="sect4"> <h5 id="nsa-cache-control-parents"><a class="anchor" href="#nsa-cache-control-parents"></a>Parent Elements of <cache-control></h5> <div class="ulist"> <ul> <li> <p><a href="#nsa-headers">headers</a></p> </li> </ul> </div> </div> </div> <div class="sect3"> <h4 id="nsa-hsts"><a class="anchor" href="#nsa-hsts"></a>2.1.6. <hsts></h4> <div class="paragraph"> <p>When enabled adds the <a href="http://tools.ietf.org/html/rfc6797">Strict-Transport-Security</a> header to the response for any secure request. This allows the server to instruct browsers to automatically use HTTPS for future requests.</p> </div> <div class="sect4"> <h5 id="nsa-hsts-attributes"><a class="anchor" href="#nsa-hsts-attributes"></a><hsts> Attributes</h5> <div id="nsa-hsts-include-subdomains" class="ulist"> <ul> <li> <p><strong>include-sub-domains</strong> Specifies if subdomains should be included. Default true.</p> </li> </ul> </div> <div id="nsa-hsts-max-age-seconds" class="ulist"> <ul> <li> <p><strong>max-age-seconds</strong> Specifies the maximum ammount of time the host should be considered a Known HSTS Host. Default one year.</p> </li> </ul> </div> <div id="nsa-hsts-request-matcher-ref" class="ulist"> <ul> <li> <p><strong>request-matcher-ref</strong> The RequestMatcher instance to be used to determine if the header should be set. Default is if HttpServletRequest.isSecure() is true.</p> </li> </ul> </div> </div> <div class="sect4"> <h5 id="nsa-hsts-parents"><a class="anchor" href="#nsa-hsts-parents"></a>Parent Elements of <hsts></h5> <div class="ulist"> <ul> <li> <p><a href="#nsa-headers">headers</a></p> </li> </ul> </div> </div> </div> <div class="sect3"> <h4 id="nsa-frame-options"><a class="anchor" href="#nsa-frame-options"></a>2.1.7. <frame-options></h4> <div class="paragraph"> <p>When enabled adds the <a href="http://tools.ietf.org/html/draft-ietf-websec-x-frame-options">X-Frame-Options header</a> to the response, this allows newer browsers to do some security checks and prevent <a href="http://en.wikipedia.org/wiki/Clickjacking">clickjacking</a> attacks.</p> </div> <div class="sect4"> <h5 id="nsa-frame-options-attributes"><a class="anchor" href="#nsa-frame-options-attributes"></a><frame-options> Attributes</h5> <div id="nsa-frame-options-policy" class="ulist"> <ul> <li> <p><strong>policy</strong></p> <div class="ulist"> <ul> <li> <p><code>DENY</code> The page cannot be displayed in a frame, regardless of the site attempting to do so. This is the default when frame-options-policy is specified.</p> </li> <li> <p><code>SAMEORIGIN</code> The page can only be displayed in a frame on the same origin as the page itself</p> </li> <li> <p><code>ALLOW-FROM</code> <a href="#nsa-frame-options-origin">origin</a> The page can only be displayed in a frame on the specified origin.</p> </li> </ul> </div> <div class="paragraph"> <p>In other words, if you specify DENY, not only will attempts to load the page in a frame fail when loaded from other sites, attempts to do so will fail when loaded from the same site. On the other hand, if you specify SAMEORIGIN, you can still use the page in a frame as long as the site including it in a frame it is the same as the one serving the page.</p> </div> </li> </ul> </div> <div id="nsa-frame-options-strategy" class="ulist"> <ul> <li> <p><strong>strategy</strong> Select the <code>AllowFromStrategy</code> to use when using the ALLOW-FROM policy.</p> <div class="ulist"> <ul> <li> <p><code>static</code> Use a single static ALLOW-FROM value. The value can be set through the <a href="#nsa-frame-options-value">value</a> attribute.</p> </li> <li> <p><code>regexp</code> Use a regelur expression to validate incoming requests and if they are allowed. The regular expression can be set through the <a href="#nsa-frame-options-value">value</a> attribute. The request parameter used to retrieve the value to validate can be specified using the <a href="#nsa-frame-options-from-parameter">from-parameter</a>.</p> </li> <li> <p><code>whitelist</code> A comma-seperated list containing the allowed domains. The comma-seperated list can be set through the <a href="#nsa-frame-options-value">value</a> attribute. The request parameter used to retrieve the value to validate can be specified using the <a href="#nsa-frame-options-from-parameter">from-parameter</a>.</p> </li> </ul> </div> </li> </ul> </div> <div id="nsa-frame-options-ref" class="ulist"> <ul> <li> <p><strong>ref</strong> Instead of using one of the predefined strategies it is also possible to use a custom <code>AllowFromStrategy</code>. The reference to this bean can be specified through this ref attribute.</p> </li> </ul> </div> <div id="nsa-frame-options-value" class="ulist"> <ul> <li> <p><strong>value</strong> The value to use when ALLOW-FROM is used a <a href="#nsa-frame-options-strategy">strategy</a>.</p> </li> </ul> </div> <div id="nsa-frame-options-from-parameter" class="ulist"> <ul> <li> <p><strong>from-parameter</strong> Specify the name of the request parameter to use when using regexp or whitelist for the ALLOW-FROM strategy.</p> </li> </ul> </div> </div> <div class="sect4"> <h5 id="nsa-frame-options-parents"><a class="anchor" href="#nsa-frame-options-parents"></a>Parent Elements of <frame-options></h5> <div class="ulist"> <ul> <li> <p><a href="#nsa-headers">headers</a></p> </li> </ul> </div> </div> </div> <div class="sect3"> <h4 id="nsa-xss-protection"><a class="anchor" href="#nsa-xss-protection"></a>2.1.8. <xss-protection></h4> <div class="paragraph"> <p>Adds the <a href="http://blogs.msdn.com/b/ie/archive/2008/07/02/ie8-security-part-iv-the-xss-filter.aspx">X-XSS-Protection header</a> to the response to assist in protecting against <a href="http://en.wikipedia.org/wiki/Cross-site_scripting#Non-Persistent">reflected / Type-1 Cross-Site Scripting (XSS)</a> attacks. This is in no-way a full protection to XSS attacks!</p> </div> <div class="sect4"> <h5 id="nsa-xss-protection-attributes"><a class="anchor" href="#nsa-xss-protection-attributes"></a><xss-protection> Attributes</h5> <div id="nsa-xss-protection-enabled" class="ulist"> <ul> <li> <p><strong>xss-protection-enabled</strong> Enable or Disable <a href="http://en.wikipedia.org/wiki/Cross-site_scripting#Non-Persistent">reflected / Type-1 Cross-Site Scripting (XSS)</a> protection.</p> </li> </ul> </div> <div id="nsa-xss-protection-block" class="ulist"> <ul> <li> <p><strong>xss-protection-block</strong> When true and xss-protection-enabled is true, adds mode=block to the header. This indicates to the browser that the page should not be loaded at all. When false and xss-protection-enabled is true, the page will still be rendered when an reflected attack is detected but the response will be modified to protect against the attack. Note that there are sometimes ways of bypassing this mode which can often times make blocking the page more desirable.</p> </li> </ul> </div> </div> <div class="sect4"> <h5 id="nsa-xss-protection-parents"><a class="anchor" href="#nsa-xss-protection-parents"></a>Parent Elements of <xss-protection></h5> <div class="ulist"> <ul> <li> <p><a href="#nsa-headers">headers</a></p> </li> </ul> </div> </div> </div> <div class="sect3"> <h4 id="nsa-content-type-options"><a class="anchor" href="#nsa-content-type-options"></a>2.1.9. <content-type-options></h4> <div class="paragraph"> <p>Add the X-Content-Type-Options header with the value of nosniff to the response. This <a href="http://blogs.msdn.com/b/ie/archive/2008/09/02/ie8-security-part-vi-beta-2-update.aspx">disables MIME-sniffing</a> for IE8+ and Chrome extensions.</p> </div> <div class="sect4"> <h5 id="nsa-content-type-options-parents"><a class="anchor" href="#nsa-content-type-options-parents"></a>Parent Elements of <content-type-options></h5> <div class="ulist"> <ul> <li> <p><a href="#nsa-headers">headers</a></p> </li> </ul> </div> </div> </div> <div class="sect3"> <h4 id="nsa-header"><a class="anchor" href="#nsa-header"></a>2.1.10. <header></h4> <div class="paragraph"> <p>Add additional headers to the response, both the name and value need to be specified.</p> </div> <div class="sect4"> <h5 id="nsa-header-attributes"><a class="anchor" href="#nsa-header-attributes"></a><header-attributes> Attributes</h5> <div id="nsa-header-name" class="ulist"> <ul> <li> <p><strong>header-name</strong> The <code>name</code> of the header.</p> </li> </ul> </div> <div id="nsa-header-value" class="ulist"> <ul> <li> <p><strong>value</strong> The <code>value</code> of the header to add.</p> </li> </ul> </div> <div id="nsa-header-ref" class="ulist"> <ul> <li> <p><strong>ref</strong> Reference to a custom implementation of the <code>HeaderWriter</code> interface.</p> </li> </ul> </div> </div> <div class="sect4"> <h5 id="nsa-header-parents"><a class="anchor" href="#nsa-header-parents"></a>Parent Elements of <header></h5> <div class="ulist"> <ul> <li> <p><a href="#nsa-headers">headers</a></p> </li> </ul> </div> </div> </div> <div class="sect3"> <h4 id="nsa-anonymous"><a class="anchor" href="#nsa-anonymous"></a>2.1.11. <anonymous></h4> <div class="paragraph"> <p>Adds an <code>AnonymousAuthenticationFilter</code> to the stack and an <code>AnonymousAuthenticationProvider</code>. Required if you are using the <code>IS_AUTHENTICATED_ANONYMOUSLY</code> attribute.</p> </div> <div class="sect4"> <h5 id="nsa-anonymous-parents"><a class="anchor" href="#nsa-anonymous-parents"></a>Parent Elements of <anonymous></h5> <div class="ulist"> <ul> <li> <p><a href="#nsa-http">http</a></p> </li> </ul> </div> </div> <div class="sect4"> <h5 id="nsa-anonymous-attributes"><a class="anchor" href="#nsa-anonymous-attributes"></a><anonymous> Attributes</h5> <div id="nsa-anonymous-enabled" class="ulist"> <ul> <li> <p><strong>enabled</strong> With the default namespace setup, the anonymous "authentication" facility is automatically enabled. You can disable it using this property.</p> </li> </ul> </div> <div id="nsa-anonymous-granted-authority" class="ulist"> <ul> <li> <p><strong>granted-authority</strong> The granted authority that should be assigned to the anonymous request. Commonly this is used to assign the anonymous request particular roles, which can subsequently be used in authorization decisions. If unset, defaults to <code>ROLE_ANONYMOUS</code>.</p> </li> </ul> </div> <div id="nsa-anonymous-key" class="ulist"> <ul> <li> <p><strong>key</strong> The key shared between the provider and filter. This generally does not need to be set. If unset, it will default to a secure randomly generated value. This means setting this value can improve startup time when using the anonymous functionality since secure random values can take a while to be generated.</p> </li> </ul> </div> <div id="nsa-anonymous-username" class="ulist"> <ul> <li> <p><strong>username</strong> The username that should be assigned to the anonymous request. This allows the principal to be identified, which may be important for logging and auditing. if unset, defaults to <code>anonymousUser</code>.</p> </li> </ul> </div> </div> </div> <div class="sect3"> <h4 id="nsa-csrf"><a class="anchor" href="#nsa-csrf"></a>2.1.12. <csrf></h4> <div class="paragraph"> <p>This element will add <a href="http://en.wikipedia.org/wiki/Cross-site_request_forgery">Cross Site Request Forger (CSRF)</a> protection to the application. It also updates the default RequestCache to only replay "GET" requests upon successful authentication. Additional information can be found in the <a href="#csrf">Cross Site Request Forgery (CSRF)</a> section of the reference.</p> </div> <div class="sect4"> <h5 id="nsa-csrf-parents"><a class="anchor" href="#nsa-csrf-parents"></a>Parent Elements of <csrf></h5> <div class="ulist"> <ul> <li> <p><a href="#nsa-http">http</a></p> </li> </ul> </div> </div> <div class="sect4"> <h5 id="nsa-csrf-attributes"><a class="anchor" href="#nsa-csrf-attributes"></a><csrf> Attributes</h5> <div id="nsa-csrf-token-repository-ref" class="ulist"> <ul> <li> <p><strong>token-repository-ref</strong> The CsrfTokenRepository to use. The default is <code>HttpSessionCsrfTokenRepository</code>.</p> </li> </ul> </div> <div id="nsa-csrf-request-matcher-ref" class="ulist"> <ul> <li> <p><strong>request-matcher-ref</strong> The RequestMatcher instance to be used to determine if CSRF should be applied. Default is any HTTP method except "GET", "TRACE", "HEAD", "OPTIONS".</p> </li> </ul> </div> </div> </div> <div class="sect3"> <h4 id="nsa-custom-filter"><a class="anchor" href="#nsa-custom-filter"></a>2.1.13. <custom-filter></h4> <div class="paragraph"> <p>This element is used to add a filter to the filter chain. It doesn’t create any additional beans but is used to select a bean of type <code>javax.servlet.Filter</code> which is already defined in the application context and add that at a particular position in the filter chain maintained by Spring Security. Full details can be found in the <a href="#ns-custom-filters">namespace chapter</a>.</p> </div> <div class="sect4"> <h5 id="nsa-custom-filter-parents"><a class="anchor" href="#nsa-custom-filter-parents"></a>Parent Elements of <custom-filter></h5> <div class="ulist"> <ul> <li> <p><a href="#nsa-http">http</a></p> </li> </ul> </div> </div> <div class="sect4"> <h5 id="nsa-custom-filter-attributes"><a class="anchor" href="#nsa-custom-filter-attributes"></a><custom-filter> Attributes</h5> <div id="nsa-custom-filter-after" class="ulist"> <ul> <li> <p><strong>after</strong> The filter immediately after which the custom-filter should be placed in the chain. This feature will only be needed by advanced users who wish to mix their own filters into the security filter chain and have some knowledge of the standard Spring Security filters. The filter names map to specific Spring Security implementation filters.</p> </li> </ul> </div> <div id="nsa-custom-filter-before" class="ulist"> <ul> <li> <p><strong>before</strong> The filter immediately before which the custom-filter should be placed in the chain</p> </li> </ul> </div> <div id="nsa-custom-filter-position" class="ulist"> <ul> <li> <p><strong>position</strong> The explicit position at which the custom-filter should be placed in the chain. Use if you are replacing a standard filter.</p> </li> </ul> </div> <div id="nsa-custom-filter-ref" class="ulist"> <ul> <li> <p><strong>ref</strong> Defines a reference to a Spring bean that implements <code>Filter</code>.</p> </li> </ul> </div> </div> </div> <div class="sect3"> <h4 id="nsa-expression-handler"><a class="anchor" href="#nsa-expression-handler"></a>2.1.14. <expression-handler></h4> <div class="paragraph"> <p>Defines the <code>SecurityExpressionHandler</code> instance which will be used if expression-based access-control is enabled. A default implementation (with no ACL support) will be used if not supplied.</p> </div> <div class="sect4"> <h5 id="nsa-expression-handler-parents"><a class="anchor" href="#nsa-expression-handler-parents"></a>Parent Elements of <expression-handler></h5> <div class="ulist"> <ul> <li> <p><a href="#nsa-global-method-security">global-method-security</a></p> </li> <li> <p><a href="#nsa-http">http</a></p> </li> </ul> </div> </div> <div class="sect4"> <h5 id="nsa-expression-handler-attributes"><a class="anchor" href="#nsa-expression-handler-attributes"></a><expression-handler> Attributes</h5> <div id="nsa-expression-handler-ref" class="ulist"> <ul> <li> <p><strong>ref</strong> Defines a reference to a Spring bean that implements <code>SecurityExpressionHandler</code>.</p> </li> </ul> </div> </div> </div> <div class="sect3"> <h4 id="nsa-form-login"><a class="anchor" href="#nsa-form-login"></a>2.1.15. <form-login></h4> <div class="paragraph"> <p>Used to add an <code>UsernamePasswordAuthenticationFilter</code> to the filter stack and an <code>LoginUrlAuthenticationEntryPoint</code> to the application context to provide authentication on demand. This will always take precedence over other namespace-created entry points. If no attributes are supplied, a login page will be generated automatically at the URL "/spring_security_login" <span class="footnote">[<a id="_footnoteref_25" class="footnote" href="#_footnote_25" title="View footnote.">25</a>]</span> The behaviour can be customized using the <a href="#nsa-form-login-attributes"><code><form-login></code> Attributes</a>.</p> </div> <div class="sect4"> <h5 id="nsa-form-login-parents"><a class="anchor" href="#nsa-form-login-parents"></a>Parent Elements of <form-login></h5> <div class="ulist"> <ul> <li> <p><a href="#nsa-http">http</a></p> </li> </ul> </div> </div> <div class="sect4"> <h5 id="nsa-form-login-attributes"><a class="anchor" href="#nsa-form-login-attributes"></a><form-login> Attributes</h5> <div id="nsa-form-login-always-use-default-target" class="ulist"> <ul> <li> <p><strong>always-use-default-target</strong> If set to <code>true</code>, the user will always start at the value given by <a href="#nsa-form-login-default-target-url">default-target-url</a>, regardless of how they arrived at the login page. Maps to the <code>alwaysUseDefaultTargetUrl</code> property of <code>UsernamePasswordAuthenticationFilter</code>. Default value is <code>false</code>.</p> </li> </ul> </div> <div id="nsa-form-login-authentication-details-source-ref" class="ulist"> <ul> <li> <p><strong>authentication-details-source-ref</strong> Reference to an <code>AuthenticationDetailsSource</code> which will be used by the authentication filter</p> </li> </ul> </div> <div id="nsa-form-login-authentication-failure-handler-ref" class="ulist"> <ul> <li> <p><strong>authentication-failure-handler-ref</strong> Can be used as an alternative to <a href="#nsa-form-login-authentication-failure-url">authentication-failure-url</a>, giving you full control over the navigation flow after an authentication failure. The value should be he name of an <code>AuthenticationFailureHandler</code> bean in the application context.</p> </li> </ul> </div> <div id="nsa-form-login-authentication-failure-url" class="ulist"> <ul> <li> <p><strong>authentication-failure-url</strong> Maps to the <code>authenticationFailureUrl</code> property of <code>UsernamePasswordAuthenticationFilter</code>. Defines the URL the browser will be redirected to on login failure. Defaults to <code>/spring_security_login?login_error</code>, which will be automatically handled by the automatic login page generator, re-rendering the login page with an error message.</p> </li> </ul> </div> <div id="nsa-form-login-authentication-success-handler-ref" class="ulist"> <ul> <li> <p><strong>authentication-success-handler-ref</strong> This can be used as an alternative to <a href="#nsa-form-login-default-target-url">default-target-url</a> and <a href="#nsa-form-login-always-use-default-target">always-use-default-target</a>, giving you full control over the navigation flow after a successful authentication. The value should be the name of an <code>AuthenticationSuccessHandler</code> bean in the application context. By default, an implementation of <code>SavedRequestAwareAuthenticationSuccessHandler</code> is used and injected with the <a href="#nsa-form-login-default-target-url">default-target-url</a>.</p> </li> </ul> </div> <div id="nsa-form-login-default-target-url" class="ulist"> <ul> <li> <p><strong>default-target-url</strong> Maps to the <code>defaultTargetUrl</code> property of <code>UsernamePasswordAuthenticationFilter</code>. If not set, the default value is "/" (the application root). A user will be taken to this URL after logging in, provided they were not asked to login while attempting to access a secured resource, when they will be taken to the originally requested URL.</p> </li> </ul> </div> <div id="nsa-form-login-login-page" class="ulist"> <ul> <li> <p><strong>login-page</strong> The URL that should be used to render the login page. Maps to the <code>loginFormUrl</code> property of the <code>LoginUrlAuthenticationEntryPoint</code>. Defaults to "/spring_security_login".</p> </li> </ul> </div> <div id="nsa-form-login-login-processing-url" class="ulist"> <ul> <li> <p><strong>login-processing-url</strong> Maps to the <code>filterProcessesUrl</code> property of <code>UsernamePasswordAuthenticationFilter</code>. The default value is "/j_spring_security_check".</p> </li> </ul> </div> <div id="nsa-form-login-password-parameter" class="ulist"> <ul> <li> <p><strong>password-parameter</strong> The name of the request parameter which contains the password. Defaults to "j_password".</p> </li> </ul> </div> <div id="nsa-form-login-username-parameter" class="ulist"> <ul> <li> <p><strong>username-parameter</strong> The name of the request parameter which contains the username. Defaults to "j_username".</p> </li> </ul> </div> </div> </div> <div class="sect3"> <h4 id="nsa-http-basic"><a class="anchor" href="#nsa-http-basic"></a>2.1.16. <http-basic></h4> <div class="paragraph"> <p>Adds a <code>BasicAuthenticationFilter</code> and <code>BasicAuthenticationEntryPoint</code> to the configuration. The latter will only be used as the configuration entry point if form-based login is not enabled.</p> </div> <div class="sect4"> <h5 id="nsa-http-basic-parents"><a class="anchor" href="#nsa-http-basic-parents"></a>Parent Elements of <http-basic></h5> <div class="ulist"> <ul> <li> <p><a href="#nsa-http">http</a></p> </li> </ul> </div> </div> <div class="sect4"> <h5 id="nsa-http-basic-attributes"><a class="anchor" href="#nsa-http-basic-attributes"></a><http-basic> Attributes</h5> <div id="nsa-http-basic-authentication-details-source-ref" class="ulist"> <ul> <li> <p><strong>authentication-details-source-ref</strong> Reference to an <code>AuthenticationDetailsSource</code> which will be used by the authentication filter</p> </li> </ul> </div> <div id="nsa-http-basic-entry-point-ref" class="ulist"> <ul> <li> <p><strong>entry-point-ref</strong> Sets the <code>AuthenticationEntryPoint</code> which is used by the <code>BasicAuthenticationFilter</code>.</p> </li> </ul> </div> </div> </div> <div class="sect3"> <h4 id="nsa-http-firewall"><a class="anchor" href="#nsa-http-firewall"></a>2.1.17. <http-firewall> Element</h4> <div class="paragraph"> <p>This is a top-level element which can be used to inject a custom implementation of <code>HttpFirewall</code> into the <code>FilterChainProxy</code> created by the namespace. The default implementation should be suitable for most applications.</p> </div> <div class="sect4"> <h5 id="nsa-http-firewall-attributes"><a class="anchor" href="#nsa-http-firewall-attributes"></a><http-firewall> Attributes</h5> <div id="nsa-http-firewall-ref" class="ulist"> <ul> <li> <p><strong>ref</strong> Defines a reference to a Spring bean that implements <code>HttpFirewall</code>.</p> </li> </ul> </div> </div> </div> <div class="sect3"> <h4 id="nsa-intercept-url"><a class="anchor" href="#nsa-intercept-url"></a>2.1.18. <intercept-url></h4> <div class="paragraph"> <p>This element is used to define the set of URL patterns that the application is interested in and to configure how they should be handled. It is used to construct the <code>FilterInvocationSecurityMetadataSource</code> used by the <code>FilterSecurityInterceptor</code>. It is also responsible for configuring a <code>ChannelProcessingFilter</code> if particular URLs need to be accessed by HTTPS, for example. When matching the specified patterns against an incoming request, the matching is done in the order in which the elements are declared. So the most specific matches patterns should come first and the most general should come last.</p> </div> <div class="sect4"> <h5 id="nsa-intercept-url-parents"><a class="anchor" href="#nsa-intercept-url-parents"></a>Parent Elements of <intercept-url></h5> <div class="ulist"> <ul> <li> <p><a href="#nsa-filter-invocation-definition-source">filter-invocation-definition-source</a></p> </li> <li> <p><a href="#nsa-filter-security-metadata-source">filter-security-metadata-source</a></p> </li> <li> <p><a href="#nsa-http">http</a></p> </li> </ul> </div> </div> <div class="sect4"> <h5 id="nsa-intercept-url-attributes"><a class="anchor" href="#nsa-intercept-url-attributes"></a><intercept-url> Attributes</h5> <div id="nsa-intercept-url-access" class="ulist"> <ul> <li> <p><strong>access</strong> Lists the access attributes which will be stored in the <code>FilterInvocationSecurityMetadataSource</code> for the defined URL pattern/method combination. This should be a comma-separated list of the security configuration attributes (such as role names).</p> </li> </ul> </div> <div id="nsa-intercept-url-filters" class="ulist"> <ul> <li> <p><strong>filters</strong> Can only take the value "none". This will cause any matching request to bypass the Spring Security filter chain entirely. None of the rest of the <code><http></code> configuration will have any effect on the request and there will be no security context available for its duration. Access to secured methods during the request will fail.</p> </li> </ul> </div> <div id="nsa-intercept-url-method" class="ulist"> <ul> <li> <p><strong>method</strong> The HTTP Method which will be used in combination with the pattern to match an incoming request. If omitted, any method will match. If an identical pattern is specified with and without a method, the method-specific match will take precedence.</p> </li> </ul> </div> <div id="nsa-intercept-url-pattern" class="ulist"> <ul> <li> <p><strong>pattern</strong> The pattern which defines the URL path. The content will depend on the <code>request-matcher</code> attribute from the containing http element, so will default to ant path syntax.</p> </li> </ul> </div> <div id="nsa-intercept-url-requires-channel" class="ulist"> <ul> <li> <p><strong>requires-channel</strong> Can be "http" or "https" depending on whether a particular URL pattern should be accessed over HTTP or HTTPS respectively. Alternatively the value "any" can be used when there is no preference. If this attribute is present on any <code><intercept-url></code> element, then a <code>ChannelProcessingFilter</code> will be added to the filter stack and its additional dependencies added to the application context.</p> </li> </ul> </div> <div class="paragraph"> <p>If a <code><port-mappings></code> configuration is added, this will be used to by the <code>SecureChannelProcessor</code> and <code>InsecureChannelProcessor</code> beans to determine the ports used for redirecting to HTTP/HTTPS.</p> </div> </div> </div> <div class="sect3"> <h4 id="nsa-jee"><a class="anchor" href="#nsa-jee"></a>2.1.19. <jee></h4> <div class="paragraph"> <p>Adds a J2eePreAuthenticatedProcessingFilter to the filter chain to provide integration with container authentication.</p> </div> <div class="sect4"> <h5 id="nsa-jee-parents"><a class="anchor" href="#nsa-jee-parents"></a>Parent Elements of <jee></h5> <div class="ulist"> <ul> <li> <p><a href="#nsa-http">http</a></p> </li> </ul> </div> </div> <div class="sect4"> <h5 id="nsa-jee-attributes"><a class="anchor" href="#nsa-jee-attributes"></a><jee> Attributes</h5> <div id="nsa-jee-mappable-roles" class="ulist"> <ul> <li> <p><strong>mappable-roles</strong> A comma-separate list of roles to look for in the incoming HttpServletRequest.</p> </li> </ul> </div> <div id="nsa-jee-user-service-ref" class="ulist"> <ul> <li> <p><strong>user-service-ref</strong> A reference to a user-service (or UserDetailsService bean) Id</p> </li> </ul> </div> </div> </div> <div class="sect3"> <h4 id="nsa-logout"><a class="anchor" href="#nsa-logout"></a>2.1.20. <logout></h4> <div class="paragraph"> <p>Adds a <code>LogoutFilter</code> to the filter stack. This is configured with a <code>SecurityContextLogoutHandler</code>.</p> </div> <div class="sect4"> <h5 id="nsa-logout-parents"><a class="anchor" href="#nsa-logout-parents"></a>Parent Elements of <logout></h5> <div class="ulist"> <ul> <li> <p><a href="#nsa-http">http</a></p> </li> </ul> </div> </div> <div class="sect4"> <h5 id="nsa-logout-attributes"><a class="anchor" href="#nsa-logout-attributes"></a><logout> Attributes</h5> <div id="nsa-logout-delete-cookies" class="ulist"> <ul> <li> <p><strong>delete-cookies</strong> A comma-separated list of the names of cookies which should be deleted when the user logs out.</p> </li> </ul> </div> <div id="nsa-logout-invalidate-session" class="ulist"> <ul> <li> <p><strong>invalidate-session</strong> Maps to the <code>invalidateHttpSession</code> of the <code>SecurityContextLogoutHandler</code>. Defaults to "true", so the session will be invalidated on logout.</p> </li> </ul> </div> <div id="nsa-logout-logout-success-url" class="ulist"> <ul> <li> <p><strong>logout-success-url</strong> The destination URL which the user will be taken to after logging out. Defaults to "/".</p> <div class="paragraph"> <p>Setting this attribute will inject the <code>SessionManagementFilter</code> with a <code>SimpleRedirectInvalidSessionStrategy</code> configured with the attribute value. When an invalid session ID is submitted, the strategy will be invoked, redirecting to the configured URL.</p> </div> </li> </ul> </div> <div id="nsa-logout-logout-url" class="ulist"> <ul> <li> <p><strong>logout-url</strong> The URL which will cause a logout (i.e. which will be processed by the filter). Defaults to "/j_spring_security_logout".</p> </li> </ul> </div> <div id="nsa-logout-success-handler-ref" class="ulist"> <ul> <li> <p><strong>success-handler-ref</strong> May be used to supply an instance of <code>LogoutSuccessHandler</code> which will be invoked to control the navigation after logging out.</p> </li> </ul> </div> </div> </div> <div class="sect3"> <h4 id="nsa-openid-login"><a class="anchor" href="#nsa-openid-login"></a>2.1.21. <openid-login></h4> <div class="paragraph"> <p>Similar to <code><form-login></code> and has the same attributes. The default value for <code>login-processing-url</code> is "/j_spring_openid_security_check". An <code>OpenIDAuthenticationFilter</code> and <code>OpenIDAuthenticationProvider</code> will be registered. The latter requires a reference to a <code>UserDetailsService</code>. Again, this can be specified by <code>id</code>, using the <code>user-service-ref</code> attribute, or will be located automatically in the application context.</p> </div> <div class="sect4"> <h5 id="nsa-openid-login-parents"><a class="anchor" href="#nsa-openid-login-parents"></a>Parent Elements of <openid-login></h5> <div class="ulist"> <ul> <li> <p><a href="#nsa-http">http</a></p> </li> </ul> </div> </div> <div class="sect4"> <h5 id="nsa-openid-login-attributes"><a class="anchor" href="#nsa-openid-login-attributes"></a><openid-login> Attributes</h5> <div id="nsa-openid-login-always-use-default-target" class="ulist"> <ul> <li> <p><strong>always-use-default-target</strong> Whether the user should always be redirected to the default-target-url after login.</p> </li> </ul> </div> <div id="nsa-openid-login-authentication-details-source-ref" class="ulist"> <ul> <li> <p><strong>authentication-details-source-ref</strong> Reference to an AuthenticationDetailsSource which will be used by the authentication filter</p> </li> </ul> </div> <div id="nsa-openid-login-authentication-failure-handler-ref" class="ulist"> <ul> <li> <p><strong>authentication-failure-handler-ref</strong> Reference to an AuthenticationFailureHandler bean which should be used to handle a failed authentication request. Should not be used in combination with authentication-failure-url as the implementation should always deal with navigation to the subsequent destination</p> </li> </ul> </div> <div id="nsa-openid-login-authentication-failure-url" class="ulist"> <ul> <li> <p><strong>authentication-failure-url</strong> The URL for the login failure page. If no login failure URL is specified, Spring Security will automatically create a failure login URL at /spring_security_login?login_error and a corresponding filter to render that login failure URL when requested.</p> </li> </ul> </div> <div id="nsa-openid-login-authentication-success-handler-ref" class="ulist"> <ul> <li> <p><strong>authentication-success-handler-ref</strong> Reference to an AuthenticationSuccessHandler bean which should be used to handle a successful authentication request. Should not be used in combination with <a href="#nsa-openid-login-default-target-url">default-target-url</a> (or <a href="#nsa-openid-login-always-use-default-target">always-use-default-target</a>) as the implementation should always deal with navigation to the subsequent destination</p> </li> </ul> </div> <div id="nsa-openid-login-default-target-url" class="ulist"> <ul> <li> <p><strong>default-target-url</strong> The URL that will be redirected to after successful authentication, if the user’s previous action could not be resumed. This generally happens if the user visits a login page without having first requested a secured operation that triggers authentication. If unspecified, defaults to the root of the application.</p> </li> </ul> </div> <div id="nsa-openid-login-login-page" class="ulist"> <ul> <li> <p><strong>login-page</strong> The URL for the login page. If no login URL is specified, Spring Security will automatically create a login URL at /spring_security_login and a corresponding filter to render that login URL when requested.</p> </li> </ul> </div> <div id="nsa-openid-login-login-processing-url" class="ulist"> <ul> <li> <p><strong>login-processing-url</strong> The URL that the login form is posted to. If unspecified, it defaults to /j_spring_security_check.</p> </li> </ul> </div> <div id="nsa-openid-login-password-parameter" class="ulist"> <ul> <li> <p><strong>password-parameter</strong> The name of the request parameter which contains the password. Defaults to "j_password".</p> </li> </ul> </div> <div id="nsa-openid-login-user-service-ref" class="ulist"> <ul> <li> <p><strong>user-service-ref</strong> A reference to a user-service (or UserDetailsService bean) Id</p> </li> </ul> </div> <div id="nsa-openid-login-username-parameter" class="ulist"> <ul> <li> <p><strong>username-parameter</strong> The name of the request parameter which contains the username. Defaults to "j_username".</p> </li> </ul> </div> </div> <div class="sect4"> <h5 id="nsa-openid-login-children"><a class="anchor" href="#nsa-openid-login-children"></a>Child Elements of <openid-login></h5> <div class="ulist"> <ul> <li> <p><a href="#nsa-attribute-exchange">attribute-exchange</a></p> </li> </ul> </div> </div> </div> <div class="sect3"> <h4 id="nsa-attribute-exchange"><a class="anchor" href="#nsa-attribute-exchange"></a>2.1.22. <attribute-exchange></h4> <div class="paragraph"> <p>The <code>attribute-exchange</code> element defines the list of attributes which should be requested from the identity provider. An example can be found in the <a href="#ns-openid">OpenID Support</a> section of the namespace configuration chapter. More than one can be used, in which case each must have an <code>identifier-match</code> attribute, containing a regular expression which is matched against the supplied OpenID identifier. This allows different attribute lists to be fetched from different providers (Google, Yahoo etc).</p> </div> <div class="sect4"> <h5 id="nsa-attribute-exchange-parents"><a class="anchor" href="#nsa-attribute-exchange-parents"></a>Parent Elements of <attribute-exchange></h5> <div class="ulist"> <ul> <li> <p><a href="#nsa-openid-login">openid-login</a></p> </li> </ul> </div> </div> <div class="sect4"> <h5 id="nsa-attribute-exchange-attributes"><a class="anchor" href="#nsa-attribute-exchange-attributes"></a><attribute-exchange> Attributes</h5> <div id="nsa-attribute-exchange-identifier-match" class="ulist"> <ul> <li> <p><strong>identifier-match</strong> A regular expression which will be compared against the claimed identity, when deciding which attribute-exchange configuration to use during authentication.</p> </li> </ul> </div> </div> <div class="sect4"> <h5 id="nsa-attribute-exchange-children"><a class="anchor" href="#nsa-attribute-exchange-children"></a>Child Elements of <attribute-exchange></h5> <div class="ulist"> <ul> <li> <p><a href="#nsa-openid-attribute">openid-attribute</a></p> </li> </ul> </div> </div> </div> <div class="sect3"> <h4 id="nsa-openid-attribute"><a class="anchor" href="#nsa-openid-attribute"></a>2.1.23. <openid-attribute></h4> <div class="paragraph"> <p>Attributes used when making an OpenID AX <a href="http://openid.net/specs/openid-attribute-exchange-1_0.html#fetch_request"> Fetch Request</a></p> </div> <div class="sect4"> <h5 id="nsa-openid-attribute-parents"><a class="anchor" href="#nsa-openid-attribute-parents"></a>Parent Elements of <openid-attribute></h5> <div class="ulist"> <ul> <li> <p><a href="#nsa-attribute-exchange">attribute-exchange</a></p> </li> </ul> </div> </div> <div class="sect4"> <h5 id="nsa-openid-attribute-attributes"><a class="anchor" href="#nsa-openid-attribute-attributes"></a><openid-attribute> Attributes</h5> <div id="nsa-openid-attribute-count" class="ulist"> <ul> <li> <p><strong>count</strong> Specifies the number of attributes that you wish to get back. For example, return 3 emails. The default value is 1.</p> </li> </ul> </div> <div id="nsa-openid-attribute-name" class="ulist"> <ul> <li> <p><strong>name</strong> Specifies the name of the attribute that you wish to get back. For example, email.</p> </li> </ul> </div> <div id="nsa-openid-attribute-required" class="ulist"> <ul> <li> <p><strong>required</strong> Specifies if this attribute is required to the OP, but does not error out if the OP does not return the attribute. Default is false.</p> </li> </ul> </div> <div id="nsa-openid-attribute-type" class="ulist"> <ul> <li> <p><strong>type</strong> Specifies the attribute type. For example, <a href="http://axschema.org/contact/email">http://axschema.org/contact/email</a>. See your OP’s documentation for valid attribute types.</p> </li> </ul> </div> </div> </div> <div class="sect3"> <h4 id="nsa-port-mappings"><a class="anchor" href="#nsa-port-mappings"></a>2.1.24. <port-mappings></h4> <div class="paragraph"> <p>By default, an instance of <code>PortMapperImpl</code> will be added to the configuration for use in redirecting to secure and insecure URLs. This element can optionally be used to override the default mappings which that class defines. Each child <code><port-mapping></code> element defines a pair of HTTP:HTTPS ports. The default mappings are 80:443 and 8080:8443. An example of overriding these can be found in the <a href="#ns-requires-channel">namespace introduction</a>.</p> </div> <div class="sect4"> <h5 id="nsa-port-mappings-parents"><a class="anchor" href="#nsa-port-mappings-parents"></a>Parent Elements of <port-mappings></h5> <div class="ulist"> <ul> <li> <p><a href="#nsa-http">http</a></p> </li> </ul> </div> </div> <div class="sect4"> <h5 id="nsa-port-mappings-children"><a class="anchor" href="#nsa-port-mappings-children"></a>Child Elements of <port-mappings></h5> <div class="ulist"> <ul> <li> <p><a href="#nsa-port-mapping">port-mapping</a></p> </li> </ul> </div> </div> </div> <div class="sect3"> <h4 id="nsa-port-mapping"><a class="anchor" href="#nsa-port-mapping"></a>2.1.25. <port-mapping></h4> <div class="paragraph"> <p>Provides a method to map http ports to https ports when forcing a redirect.</p> </div> <div class="sect4"> <h5 id="nsa-port-mapping-parents"><a class="anchor" href="#nsa-port-mapping-parents"></a>Parent Elements of <port-mapping></h5> <div class="ulist"> <ul> <li> <p><a href="#nsa-port-mappings">port-mappings</a></p> </li> </ul> </div> </div> <div class="sect4"> <h5 id="nsa-port-mapping-attributes"><a class="anchor" href="#nsa-port-mapping-attributes"></a><port-mapping> Attributes</h5> <div id="nsa-port-mapping-http" class="ulist"> <ul> <li> <p><strong>http</strong> The http port to use.</p> </li> </ul> </div> <div id="nsa-port-mapping-https" class="ulist"> <ul> <li> <p><strong>https</strong> The https port to use.</p> </li> </ul> </div> </div> </div> <div class="sect3"> <h4 id="nsa-remember-me"><a class="anchor" href="#nsa-remember-me"></a>2.1.26. <remember-me></h4> <div class="paragraph"> <p>Adds the <code>RememberMeAuthenticationFilter</code> to the stack. This in turn will be configured with either a <code>TokenBasedRememberMeServices</code>, a <code>PersistentTokenBasedRememberMeServices</code> or a user-specified bean implementing <code>RememberMeServices</code> depending on the attribute settings.</p> </div> <div class="sect4"> <h5 id="nsa-remember-me-parents"><a class="anchor" href="#nsa-remember-me-parents"></a>Parent Elements of <remember-me></h5> <div class="ulist"> <ul> <li> <p><a href="#nsa-http">http</a></p> </li> </ul> </div> </div> <div class="sect4"> <h5 id="nsa-remember-me-attributes"><a class="anchor" href="#nsa-remember-me-attributes"></a><remember-me> Attributes</h5> <div id="nsa-remember-me-authentication-success-handler-ref" class="ulist"> <ul> <li> <p><strong>authentication-success-handler-ref</strong> Sets the <code>authenticationSuccessHandler</code> property on the <code>RememberMeAuthenticationFilter</code> if custom navigation is required. The value should be the name of a <code>AuthenticationSuccessHandler</code> bean in the application context.</p> </li> </ul> </div> <div id="nsa-remember-me-data-source-ref" class="ulist"> <ul> <li> <p><strong>data-source-ref</strong> A reference to a <code>DataSource</code> bean. If this is set, <code>PersistentTokenBasedRememberMeServices</code> will be used and configured with a <code>JdbcTokenRepositoryImpl</code> instance.</p> </li> </ul> </div> <div id="nsa-remember-me-remember-me-parameter" class="ulist"> <ul> <li> <p><strong>remember-me-parameter</strong> The name of the request parameter which toggles remember-me authentication. Defaults to "_spring_security_remember_me". Maps to the "parameter" property of <code>AbstractRememberMeServices</code>.</p> </li> </ul> </div> <div id="nsa-remember-me-key" class="ulist"> <ul> <li> <p><strong>key</strong> Maps to the "key" property of <code>AbstractRememberMeServices</code>. Should be set to a unique value to ensure that remember-me cookies are only valid within the one application <span class="footnote">[<a id="_footnoteref_26" class="footnote" href="#_footnote_26" title="View footnote.">26</a>]</span>. If this is not set a secure random value will be generated. Since generating secure random values can take a while, setting this value explicitly can help improve startup times when using the remember me functionality.</p> </li> </ul> </div> <div id="nsa-remember-me-services-alias" class="ulist"> <ul> <li> <p><strong>services-alias</strong> Exports the internally defined <code>RememberMeServices</code> as a bean alias, allowing it to be used by other beans in the application context.</p> </li> </ul> </div> <div id="nsa-remember-me-services-ref" class="ulist"> <ul> <li> <p><strong>services-ref</strong> Allows complete control of the <code>RememberMeServices</code> implementation that will be used by the filter. The value should be the <code>id</code> of a bean in the application context which implements this interface. Should also implement <code>LogoutHandler</code> if a logout filter is in use.</p> </li> </ul> </div> <div id="nsa-remember-me-token-repository-ref" class="ulist"> <ul> <li> <p><strong>token-repository-ref</strong> Configures a <code>PersistentTokenBasedRememberMeServices</code> but allows the use of a custom <code>PersistentTokenRepository</code> bean.</p> </li> </ul> </div> <div id="nsa-remember-me-token-validity-seconds" class="ulist"> <ul> <li> <p><strong>token-validity-seconds</strong> Maps to the <code>tokenValiditySeconds</code> property of <code>AbstractRememberMeServices</code>. Specifies the period in seconds for which the remember-me cookie should be valid. By default it will be valid for 14 days.</p> </li> </ul> </div> <div id="nsa-remember-me-use-secure-cookie" class="ulist"> <ul> <li> <p><strong>use-secure-cookie</strong> It is recommended that remember-me cookies are only submitted over HTTPS and thus should be flagged as "secure". By default, a secure cookie will be used if the connection over which the login request is made is secure (as it should be). If you set this property to <code>false</code>, secure cookies will not be used. Setting it to <code>true</code> will always set the secure flag on the cookie. This attribute maps to the <code>useSecureCookie</code> property of <code>AbstractRememberMeServices</code>.</p> </li> </ul> </div> <div id="nsa-remember-me-user-service-ref" class="ulist"> <ul> <li> <p><strong>user-service-ref</strong> The remember-me services implementations require access to a <code>UserDetailsService</code>, so there has to be one defined in the application context. If there is only one, it will be selected and used automatically by the namespace configuration. If there are multiple instances, you can specify a bean <code>id</code> explicitly using this attribute.</p> </li> </ul> </div> </div> </div> <div class="sect3"> <h4 id="nsa-request-cache"><a class="anchor" href="#nsa-request-cache"></a>2.1.27. <request-cache> Element</h4> <div class="paragraph"> <p>Sets the <code>RequestCache</code> instance which will be used by the <code>ExceptionTranslationFilter</code> to store request information before invoking an <code>AuthenticationEntryPoint</code>.</p> </div> <div class="sect4"> <h5 id="nsa-request-cache-parents"><a class="anchor" href="#nsa-request-cache-parents"></a>Parent Elements of <request-cache></h5> <div class="ulist"> <ul> <li> <p><a href="#nsa-http">http</a></p> </li> </ul> </div> </div> <div class="sect4"> <h5 id="nsa-request-cache-attributes"><a class="anchor" href="#nsa-request-cache-attributes"></a><request-cache> Attributes</h5> <div id="nsa-request-cache-ref" class="ulist"> <ul> <li> <p><strong>ref</strong> Defines a reference to a Spring bean that is a <code>RequestCache</code>.</p> </li> </ul> </div> </div> </div> <div class="sect3"> <h4 id="nsa-session-management"><a class="anchor" href="#nsa-session-management"></a>2.1.28. <session-management></h4> <div class="paragraph"> <p>Session-management related functionality is implemented by the addition of a <code>SessionManagementFilter</code> to the filter stack.</p> </div> <div class="sect4"> <h5 id="nsa-session-management-parents"><a class="anchor" href="#nsa-session-management-parents"></a>Parent Elements of <session-management></h5> <div class="ulist"> <ul> <li> <p><a href="#nsa-http">http</a></p> </li> </ul> </div> </div> <div class="sect4"> <h5 id="nsa-session-management-attributes"><a class="anchor" href="#nsa-session-management-attributes"></a><session-management> Attributes</h5> <div id="nsa-session-management-invalid-session-url" class="ulist"> <ul> <li> <p><strong>invalid-session-url</strong> Setting this attribute will inject the <code>SessionManagementFilter</code> with a <code>SimpleRedirectInvalidSessionStrategy</code> configured with the attribute value. When an invalid session ID is submitted, the strategy will be invoked, redirecting to the configured URL.</p> </li> </ul> </div> <div id="nsa-session-management-session-authentication-error-url" class="ulist"> <ul> <li> <p><strong>session-authentication-error-url</strong> Defines the URL of the error page which should be shown when the SessionAuthenticationStrategy raises an exception. If not set, an unauthorized (401) error code will be returned to the client. Note that this attribute doesn’t apply if the error occurs during a form-based login, where the URL for authentication failure will take precedence.</p> </li> </ul> </div> <div id="nsa-session-management-session-authentication-strategy-ref" class="ulist"> <ul> <li> <p><strong>session-authentication-strategy-ref</strong> Allows injection of the SessionAuthenticationStrategy instance used by the SessionManagementFilter</p> </li> </ul> </div> <div id="nsa-session-management-session-fixation-protection" class="ulist"> <ul> <li> <p><strong>session-fixation-protection</strong> Indicates how session fixation protection will be applied when a user authenticates. If set to "none", no protection will be applied. "newSession" will create a new empty session, with only Spring Security-related attributes migrated. "migrateSession" will create a new session and copy all session attributes to the new session. In Servlet 3.1 (Java EE 7) and newer containers, specifying "changeSessionId" will keep the existing session and use the container-supplied session fixation protection (HttpServletRequest#changeSessionId()). Defaults to "changeSessionId" in Servlet 3.1 and newer containers, "migrateSession" in older containers. Throws an exception if "changeSessionId" is used in older containers.</p> <div class="paragraph"> <p>If session fixation protection is enabled, the <code>SessionManagementFilter</code> is injected with an appropriately configured <code>DefaultSessionAuthenticationStrategy</code>. See the Javadoc for this class for more details.</p> </div> </li> </ul> </div> </div> <div class="sect4"> <h5 id="nsa-session-management-children"><a class="anchor" href="#nsa-session-management-children"></a>Child Elements of <session-management></h5> <div class="ulist"> <ul> <li> <p><a href="#nsa-concurrency-control">concurrency-control</a></p> </li> </ul> </div> </div> </div> <div class="sect3"> <h4 id="nsa-concurrency-control"><a class="anchor" href="#nsa-concurrency-control"></a>2.1.29. <concurrency-control></h4> <div class="paragraph"> <p>Adds support for concurrent session control, allowing limits to be placed on the number of active sessions a user can have. A <code>ConcurrentSessionFilter</code> will be created, and a <code>ConcurrentSessionControlAuthenticationStrategy</code> will be used with the <code>SessionManagementFilter</code>. If a <code>form-login</code> element has been declared, the strategy object will also be injected into the created authentication filter. An instance of <code>SessionRegistry</code> (a <code>SessionRegistryImpl</code> instance unless the user wishes to use a custom bean) will be created for use by the strategy.</p> </div> <div class="sect4"> <h5 id="nsa-concurrency-control-parents"><a class="anchor" href="#nsa-concurrency-control-parents"></a>Parent Elements of <concurrency-control></h5> <div class="ulist"> <ul> <li> <p><a href="#nsa-session-management">session-management</a></p> </li> </ul> </div> </div> <div class="sect4"> <h5 id="nsa-concurrency-control-attributes"><a class="anchor" href="#nsa-concurrency-control-attributes"></a><concurrency-control> Attributes</h5> <div id="nsa-concurrency-control-error-if-maximum-exceeded" class="ulist"> <ul> <li> <p><strong>error-if-maximum-exceeded</strong> If set to "true" a <code>SessionAuthenticationException</code> will be raised when a user attempts to exceed the maximum allowed number of sessions. The default behaviour is to expire the original session.</p> </li> </ul> </div> <div id="nsa-concurrency-control-expired-url" class="ulist"> <ul> <li> <p><strong>expired-url</strong> The URL a user will be redirected to if they attempt to use a session which has been "expired" by the concurrent session controller because the user has exceeded the number of allowed sessions and has logged in again elsewhere. Should be set unless <code>exception-if-maximum-exceeded</code> is set. If no value is supplied, an expiry message will just be written directly back to the response.</p> </li> </ul> </div> <div id="nsa-concurrency-control-max-sessions" class="ulist"> <ul> <li> <p><strong>max-sessions</strong> Maps to the <code>maximumSessions</code> property of <code>ConcurrentSessionControlAuthenticationStrategy</code>.</p> </li> </ul> </div> <div id="nsa-concurrency-control-session-registry-alias" class="ulist"> <ul> <li> <p><strong>session-registry-alias</strong> It can also be useful to have a reference to the internal session registry for use in your own beans or an admin interface. You can expose the internal bean using the <code>session-registry-alias</code> attribute, giving it a name that you can use elsewhere in your configuration.</p> </li> </ul> </div> <div id="nsa-concurrency-control-session-registry-ref" class="ulist"> <ul> <li> <p><strong>session-registry-ref</strong> The user can supply their own <code>SessionRegistry</code> implementation using the <code>session-registry-ref</code> attribute. The other concurrent session control beans will be wired up to use it.</p> </li> </ul> </div> </div> </div> <div class="sect3"> <h4 id="nsa-x509"><a class="anchor" href="#nsa-x509"></a>2.1.30. <x509></h4> <div class="paragraph"> <p>Adds support for X.509 authentication. An <code>X509AuthenticationFilter</code> will be added to the stack and an <code>Http403ForbiddenEntryPoint</code> bean will be created. The latter will only be used if no other authentication mechanisms are in use (its only functionality is to return an HTTP 403 error code). A <code>PreAuthenticatedAuthenticationProvider</code> will also be created which delegates the loading of user authorities to a <code>UserDetailsService</code>.</p> </div> <div class="sect4"> <h5 id="nsa-x509-parents"><a class="anchor" href="#nsa-x509-parents"></a>Parent Elements of <x509></h5> <div class="ulist"> <ul> <li> <p><a href="#nsa-http">http</a></p> </li> </ul> </div> </div> <div class="sect4"> <h5 id="nsa-x509-attributes"><a class="anchor" href="#nsa-x509-attributes"></a><x509> Attributes</h5> <div id="nsa-x509-authentication-details-source-ref" class="ulist"> <ul> <li> <p><strong>authentication-details-source-ref</strong> A reference to an <code>AuthenticationDetailsSource</code></p> </li> </ul> </div> <div id="nsa-x509-subject-principal-regex" class="ulist"> <ul> <li> <p><strong>subject-principal-regex</strong> Defines a regular expression which will be used to extract the username from the certificate (for use with the <code>UserDetailsService</code>).</p> </li> </ul> </div> <div id="nsa-x509-user-service-ref" class="ulist"> <ul> <li> <p><strong>user-service-ref</strong> Allows a specific <code>UserDetailsService</code> to be used with X.509 in the case where multiple instances are configured. If not set, an attempt will be made to locate a suitable instance automatically and use that.</p> </li> </ul> </div> </div> </div> <div class="sect3"> <h4 id="nsa-filter-chain-map"><a class="anchor" href="#nsa-filter-chain-map"></a>2.1.31. <filter-chain-map></h4> <div class="paragraph"> <p>Used to explicitly configure a FilterChainProxy instance with a FilterChainMap</p> </div> <div class="sect4"> <h5 id="nsa-filter-chain-map-attributes"><a class="anchor" href="#nsa-filter-chain-map-attributes"></a><filter-chain-map> Attributes</h5> <div id="nsa-filter-chain-map-path-type" class="ulist"> <ul> <li> <p><strong>path-type</strong> Superseded by the <a href="#nsa-filter-chain-map-request-matcher">request-matcher</a> attribute</p> </li> </ul> </div> <div id="nsa-filter-chain-map-request-matcher" class="ulist"> <ul> <li> <p><strong>request-matcher</strong> Supersedes the <em>path-type</em> attribute. Defines the strategy use for matching incoming requests. Currently the options are <em>ant</em> (for ant path patterns), <em>regex</em> for regular expressions and <em>ciRegex</em> for case-insensitive regular expressions.</p> </li> </ul> </div> </div> <div class="sect4"> <h5 id="nsa-filter-chain-map-children"><a class="anchor" href="#nsa-filter-chain-map-children"></a>Child Elements of <filter-chain-map></h5> <div class="ulist"> <ul> <li> <p><a href="#nsa-filter-chain">filter-chain</a></p> </li> </ul> </div> </div> </div> <div class="sect3"> <h4 id="nsa-filter-chain"><a class="anchor" href="#nsa-filter-chain"></a>2.1.32. <filter-chain></h4> <div class="paragraph"> <p>Used within to define a specific URL pattern and the list of filters which apply to the URLs matching that pattern. When multiple filter-chain elements are assembled in a list in order to configure a FilterChainProxy, the most specific patterns must be placed at the top of the list, with most general ones at the bottom.</p> </div> <div class="sect4"> <h5 id="nsa-filter-chain-parents"><a class="anchor" href="#nsa-filter-chain-parents"></a>Parent Elements of <filter-chain></h5> <div class="ulist"> <ul> <li> <p><a href="#nsa-filter-chain-map">filter-chain-map</a></p> </li> </ul> </div> </div> <div class="sect4"> <h5 id="nsa-filter-chain-attributes"><a class="anchor" href="#nsa-filter-chain-attributes"></a><filter-chain> Attributes</h5> <div id="nsa-filter-chain-filters" class="ulist"> <ul> <li> <p><strong>filters</strong> A comma separated list of references to Spring beans that implement <code>Filter</code>. The value "none" means that no <code>Filter</code>'s should be used for this <code>FilterChain</code>.</p> </li> </ul> </div> <div id="nsa-filter-chain-pattern" class="ulist"> <ul> <li> <p><strong>pattern</strong> A-pattern that creates RequestMatcher in combination with the <a href="#nsa-filter-chain-map-request-matcher">request-matcher</a></p> </li> </ul> </div> <div id="nsa-filter-chain-request-matcher-ref" class="ulist"> <ul> <li> <p><strong>request-matcher-ref</strong> A reference to a <code>RequestMatcher</code> that will be used to determine if the <code>Filter</code>'s from the <code>filters</code> attribute should be invoked.</p> </li> </ul> </div> </div> </div> <div class="sect3"> <h4 id="nsa-filter-invocation-definition-source"><a class="anchor" href="#nsa-filter-invocation-definition-source"></a>2.1.33. <filter-invocation-definition-source></h4> <div class="paragraph"> <p>Deprecated synonym for filter-security-metadata-source</p> </div> <div class="sect4"> <h5 id="nsa-filter-invocation-definition-source-attributes"><a class="anchor" href="#nsa-filter-invocation-definition-source-attributes"></a><filter-invocation-definition-source> Attributes</h5> <div id="nsa-filter-invocation-definition-source-id" class="ulist"> <ul> <li> <p><strong>id</strong> A bean identifier, used for referring to the bean elsewhere in the context.</p> </li> </ul> </div> <div id="nsa-filter-invocation-definition-source-lowercase-comparisons" class="ulist"> <ul> <li> <p><strong>lowercase-comparisons</strong> Compare after forcing to lowercase</p> </li> </ul> </div> <div id="nsa-filter-invocation-definition-source-path-type" class="ulist"> <ul> <li> <p><strong>path-type</strong> Superseded by <a href="#nsa-filter-invocation-definition-source-request-matcher">request-matcher</a></p> </li> </ul> </div> <div id="nsa-filter-invocation-definition-source-request-matcher" class="ulist"> <ul> <li> <p><strong>request-matcher</strong> Supersedes the <em>path-type</em> attribute. Defines the strategy use for matching incoming requests. Currently the options are <em>ant</em> (for ant path patterns), <em>regex</em> for regular expressions and <em>ciRegex</em> for case-insensitive regular expressions.</p> </li> </ul> </div> <div id="nsa-filter-invocation-definition-source-use-expressions" class="ulist"> <ul> <li> <p><strong>use-expressions</strong> Enables the use of expressions in the <em>access</em> attributes in <intercept-url> elements rather than the traditional list of configuration attributes. Defaults to <em>false</em>. If enabled, each attribute should contain a single boolean expression. If the expression evaluates to <em>true</em>, access will be granted.</p> </li> </ul> </div> </div> <div class="sect4"> <h5 id="nsa-filter-invocation-definition-source-children"><a class="anchor" href="#nsa-filter-invocation-definition-source-children"></a>Child Elements of <filter-invocation-definition-source></h5> <div class="ulist"> <ul> <li> <p><a href="#nsa-intercept-url">intercept-url</a></p> </li> </ul> </div> </div> </div> <div class="sect3"> <h4 id="nsa-filter-security-metadata-source"><a class="anchor" href="#nsa-filter-security-metadata-source"></a>2.1.34. <filter-security-metadata-source></h4> <div class="paragraph"> <p>Used to explicitly configure a FilterSecurityMetadataSource bean for use with a FilterSecurityInterceptor. Usually only needed if you are configuring a FilterChainProxy explicitly, rather than using the<http> element. The intercept-url elements used should only contain pattern, method and access attributes. Any others will result in a configuration error.</p> </div> <div class="sect4"> <h5 id="nsa-filter-security-metadata-source-attributes"><a class="anchor" href="#nsa-filter-security-metadata-source-attributes"></a><filter-security-metadata-source> Attributes</h5> <div id="nsa-filter-security-metadata-source-id" class="ulist"> <ul> <li> <p><strong>id</strong> A bean identifier, used for referring to the bean elsewhere in the context.</p> </li> </ul> </div> <div id="nsa-filter-security-metadata-source-lowercase-comparisons" class="ulist"> <ul> <li> <p><strong>lowercase-comparisons</strong> Compare after forcing to lower case</p> </li> </ul> </div> <div id="nsa-filter-security-metadata-source-path-type" class="ulist"> <ul> <li> <p><strong>path-type</strong> Superseded by <a href="#nsa-filter-security-metadata-source-request-matcher">request-matcher</a></p> </li> </ul> </div> <div id="nsa-filter-security-metadata-source-request-matcher" class="ulist"> <ul> <li> <p><strong>request-matcher</strong> Supersedes the <em>path-type</em> attribute. Defines the strategy use for matching incoming requests. Currently the options are <em>ant</em> (for ant path patterns), <em>regex</em> for regular expressions and <em>ciRegex</em> for case-insensitive regular expressions.</p> </li> </ul> </div> <div id="nsa-filter-security-metadata-source-use-expressions" class="ulist"> <ul> <li> <p><strong>use-expressions</strong> Enables the use of expressions in the <em>access</em> attributes in <intercept-url> elements rather than the traditional list of configuration attributes. Defaults to <em>false</em>. If enabled, each attribute should contain a single boolean expression. If the expression evaluates to <em>true</em>, access will be granted.</p> </li> </ul> </div> </div> <div class="sect4"> <h5 id="nsa-filter-security-metadata-source-children"><a class="anchor" href="#nsa-filter-security-metadata-source-children"></a>Child Elements of <filter-security-metadata-source></h5> <div class="ulist"> <ul> <li> <p><a href="#nsa-intercept-url">intercept-url</a></p> </li> </ul> </div> </div> </div> </div> <div class="sect2"> <h3 id="nsa-authentication"><a class="anchor" href="#nsa-authentication"></a>2.2. Authentication Services</h3> <div class="paragraph"> <p>Before Spring Security 3.0, an <code>AuthenticationManager</code> was automatically registered internally. Now you must register one explicitly using the <code><authentication-manager></code> element. This creates an instance of Spring Security’s <code>ProviderManager</code> class, which needs to be configured with a list of one or more <code>AuthenticationProvider</code> instances. These can either be created using syntax elements provided by the namespace, or they can be standard bean definitions, marked for addition to the list using the <code>authentication-provider</code> element.</p> </div> <div class="sect3"> <h4 id="nsa-authentication-manager"><a class="anchor" href="#nsa-authentication-manager"></a>2.2.1. <authentication-manager></h4> <div class="paragraph"> <p>Every Spring Security application which uses the namespace must have include this element somewhere. It is responsible for registering the <code>AuthenticationManager</code> which provides authentication services to the application. All elements which create <code>AuthenticationProvider</code> instances should be children of this element.</p> </div> <div class="sect4"> <h5 id="nsa-authentication-manager-attributes"><a class="anchor" href="#nsa-authentication-manager-attributes"></a><authentication-manager> Attributes</h5> <div id="nsa-authentication-manager-alias" class="ulist"> <ul> <li> <p><strong>alias</strong> This attribute allows you to define an alias name for the internal instance for use in your own configuration. Its use is described in the<a href="#ns-auth-manager">namespace introduction</a>.</p> </li> </ul> </div> <div id="nsa-authentication-manager-erase-credentials" class="ulist"> <ul> <li> <p><strong>erase-credentials</strong> If set to true, the AuthenticationManger will attempt to clear any credentials data in the returned Authentication object, once the user has been authenticated. Literally it maps to the <code>eraseCredentialsAfterAuthentication</code> property of the <code>ProviderManager</code>. This is discussed in the <a href="#core-services-erasing-credentials">Core Services</a> chapter.</p> </li> </ul> </div> <div id="nsa-authentication-manager-id" class="ulist"> <ul> <li> <p><strong>id</strong> This attribute allows you to define an id for the internal instance for use in your own configuration. It is the same a the alias element, but provides a more consistent experience with elements that use the id attribute.</p> </li> </ul> </div> </div> <div class="sect4"> <h5 id="nsa-authentication-manager-children"><a class="anchor" href="#nsa-authentication-manager-children"></a>Child Elements of <authentication-manager></h5> <div class="ulist"> <ul> <li> <p><a href="#nsa-authentication-provider">authentication-provider</a></p> </li> <li> <p><a href="#nsa-ldap-authentication-provider">ldap-authentication-provider</a></p> </li> </ul> </div> </div> </div> <div class="sect3"> <h4 id="nsa-authentication-provider"><a class="anchor" href="#nsa-authentication-provider"></a>2.2.2. <authentication-provider></h4> <div class="paragraph"> <p>Unless used with a <code>ref</code> attribute, this element is shorthand for configuring a <a href="#core-services-dao-provider">DaoAuthenticationProvider</a>. <code>DaoAuthenticationProvider</code> loads user information from a <code>UserDetailsService</code> and compares the username/password combination with the values supplied at login. The <code>UserDetailsService</code> instance can be defined either by using an available namespace element ( <code>jdbc-user-service</code> or by using the <code>user-service-ref</code> attribute to point to a bean defined elsewhere in the application context). You can find examples of these variations in the <a href="#ns-auth-providers">namespace introduction</a>.</p> </div> <div class="sect4"> <h5 id="nsa-authentication-provider-parents"><a class="anchor" href="#nsa-authentication-provider-parents"></a>Parent Elements of <authentication-provider></h5> <div class="ulist"> <ul> <li> <p><a href="#nsa-authentication-manager">authentication-manager</a></p> </li> </ul> </div> </div> <div class="sect4"> <h5 id="nsa-authentication-provider-attributes"><a class="anchor" href="#nsa-authentication-provider-attributes"></a><authentication-provider> Attributes</h5> <div id="nsa-authentication-provider-ref" class="ulist"> <ul> <li> <p><strong>ref</strong> Defines a reference to a Spring bean that implements `AuthenticationProvider `.</p> </li> </ul> </div> <div class="paragraph"> <p>If you have written your own <code>AuthenticationProvider</code> implementation (or want to configure one of Spring Security’s own implementations as a traditional bean for some reason, then you can use the following syntax to add it to the internal <code>ProviderManager</code>'s list:</p> </div> <div class="listingblock"> <div class="content"> <pre style="" class="prettyprint xml language-xml prettyprinted"><code><span class="pln"> </span><span class="tag"><security:authentication-manager></span><span class="pln"> </span><span class="tag"><security:authentication-provider</span><span class="pln"> </span><span class="atn">ref</span><span class="pun">=</span><span class="atv">"myAuthenticationProvider"</span><span class="pln"> </span><span class="tag">/></span><span class="pln"> </span><span class="tag"></security:authentication-manager></span><span class="pln"> </span><span class="tag"><bean</span><span class="pln"> </span><span class="atn">id</span><span class="pun">=</span><span class="atv">"myAuthenticationProvider"</span><span class="pln"> </span><span class="atn">class</span><span class="pun">=</span><span class="atv">"com.something.MyAuthenticationProvider"</span><span class="tag">/></span></code></pre> </div> </div> <div id="nsa-authentication-provider-user-service-ref" class="ulist"> <ul> <li> <p><strong>user-service-ref</strong> A reference to a bean that implements UserDetailsService that may be created using the standard bean element or the custom user-service element.</p> </li> </ul> </div> </div> <div class="sect4"> <h5 id="nsa-authentication-provider-children"><a class="anchor" href="#nsa-authentication-provider-children"></a>Child Elements of <authentication-provider></h5> <div class="ulist"> <ul> <li> <p><a href="#nsa-jdbc-user-service">jdbc-user-service</a></p> </li> <li> <p><a href="#nsa-ldap-user-service">ldap-user-service</a></p> </li> <li> <p><a href="#nsa-password-encoder">password-encoder</a></p> </li> <li> <p><a href="#nsa-user-service">user-service</a></p> </li> </ul> </div> </div> </div> <div class="sect3"> <h4 id="nsa-jdbc-user-service"><a class="anchor" href="#nsa-jdbc-user-service"></a>2.2.3. <jdbc-user-service></h4> <div class="paragraph"> <p>Causes creation of a JDBC-based UserDetailsService.</p> </div> <div class="sect4"> <h5 id="nsa-jdbc-user-service-attributes"><a class="anchor" href="#nsa-jdbc-user-service-attributes"></a><jdbc-user-service> Attributes</h5> <div id="nsa-jdbc-user-service-authorities-by-username-query" class="ulist"> <ul> <li> <p><strong>authorities-by-username-query</strong> An SQL statement to query for a user’s granted authorities given a username.</p> </li> </ul> </div> <div class="paragraph"> <p>The default is</p> </div> <div class="listingblock"> <div class="content"> <pre style="" class="prettyprint prettyprinted"><code><span class="kwd">select</span><span class="pln"> username</span><span class="pun">,</span><span class="pln"> authority </span><span class="kwd">from</span><span class="pln"> authorities </span><span class="kwd">where</span><span class="pln"> username </span><span class="pun">=</span><span class="pln"> </span><span class="pun">?</span></code></pre> </div> </div> <div id="nsa-jdbc-user-service-cache-ref" class="ulist"> <ul> <li> <p><strong>cache-ref</strong> Defines a reference to a cache for use with a UserDetailsService.</p> </li> </ul> </div> <div id="nsa-jdbc-user-service-data-source-ref" class="ulist"> <ul> <li> <p><strong>data-source-ref</strong> The bean ID of the DataSource which provides the required tables.</p> </li> </ul> </div> <div id="nsa-jdbc-user-service-group-authorities-by-username-query" class="ulist"> <ul> <li> <p><strong>group-authorities-by-username-query</strong> An SQL statement to query user’s group authorities given a username. The default is</p> <div class="listingblock"> <div class="content"> <pre style="" class="prettyprint prettyprinted"><code><span class="kwd">select</span><span class="pln"> g</span><span class="pun">.</span><span class="pln">id</span><span class="pun">,</span><span class="pln"> g</span><span class="pun">.</span><span class="pln">group_name</span><span class="pun">,</span><span class="pln"> ga</span><span class="pun">.</span><span class="pln">authority </span><span class="kwd">from</span><span class="pln"> groups g</span><span class="pun">,</span><span class="pln"> group_members gm</span><span class="pun">,</span><span class="pln"> group_authorities ga </span><span class="kwd">where</span><span class="pln"> gm</span><span class="pun">.</span><span class="pln">username </span><span class="pun">=</span><span class="pln"> </span><span class="pun">?</span><span class="pln"> </span><span class="kwd">and</span><span class="pln"> g</span><span class="pun">.</span><span class="pln">id </span><span class="pun">=</span><span class="pln"> ga</span><span class="pun">.</span><span class="pln">group_id </span><span class="kwd">and</span><span class="pln"> g</span><span class="pun">.</span><span class="pln">id </span><span class="pun">=</span><span class="pln"> gm</span><span class="pun">.</span><span class="pln">group_id</span></code></pre> </div> </div> </li> </ul> </div> <div id="nsa-jdbc-user-service-id" class="ulist"> <ul> <li> <p><strong>id</strong> A bean identifier, used for referring to the bean elsewhere in the context.</p> </li> </ul> </div> <div id="nsa-jdbc-user-service-role-prefix" class="ulist"> <ul> <li> <p><strong>role-prefix</strong> A non-empty string prefix that will be added to role strings loaded from persistent storage (default is "ROLE_"). Use the value "none" for no prefix in cases where the default is non-empty.</p> </li> </ul> </div> <div id="nsa-jdbc-user-service-users-by-username-query" class="ulist"> <ul> <li> <p><strong>users-by-username-query</strong> An SQL statement to query a username, password, and enabled status given a username. The default is</p> <div class="listingblock"> <div class="content"> <pre style="" class="prettyprint prettyprinted"><code><span class="kwd">select</span><span class="pln"> username</span><span class="pun">,</span><span class="pln"> password</span><span class="pun">,</span><span class="pln"> enabled </span><span class="kwd">from</span><span class="pln"> users </span><span class="kwd">where</span><span class="pln"> username </span><span class="pun">=</span><span class="pln"> </span><span class="pun">?</span></code></pre> </div> </div> </li> </ul> </div> </div> </div> <div class="sect3"> <h4 id="nsa-password-encoder"><a class="anchor" href="#nsa-password-encoder"></a>2.2.4. <password-encoder></h4> <div class="paragraph"> <p>Authentication providers can optionally be configured to use a password encoder as described in the <a href="#ns-password-encoder">namespace introduction</a>. This will result in the bean being injected with the appropriate <code>PasswordEncoder</code> instance, potentially with an accompanying <code>SaltSource</code> bean to provide salt values for hashing.</p> </div> <div class="sect4"> <h5 id="nsa-password-encoder-parents"><a class="anchor" href="#nsa-password-encoder-parents"></a>Parent Elements of <password-encoder></h5> <div class="ulist"> <ul> <li> <p><a href="#nsa-authentication-provider">authentication-provider</a></p> </li> <li> <p><a href="#nsa-password-compare">password-compare</a></p> </li> </ul> </div> </div> <div class="sect4"> <h5 id="nsa-password-encoder-attributes"><a class="anchor" href="#nsa-password-encoder-attributes"></a><password-encoder> Attributes</h5> <div id="nsa-password-encoder-base64" class="ulist"> <ul> <li> <p><strong>base64</strong> Whether a string should be base64 encoded</p> </li> </ul> </div> <div id="nsa-password-encoder-hash" class="ulist"> <ul> <li> <p><strong>hash</strong> Defines the hashing algorithm used on user passwords. We recommend strongly against using MD4, as it is a very weak hashing algorithm.</p> </li> </ul> </div> <div id="nsa-password-encoder-ref" class="ulist"> <ul> <li> <p><strong>ref</strong> Defines a reference to a Spring bean that implements `PasswordEncoder `.</p> </li> </ul> </div> </div> <div class="sect4"> <h5 id="nsa-password-encoder-children"><a class="anchor" href="#nsa-password-encoder-children"></a>Child Elements of <password-encoder></h5> <div class="ulist"> <ul> <li> <p><a href="#nsa-salt-source">salt-source</a></p> </li> </ul> </div> </div> </div> <div class="sect3"> <h4 id="nsa-salt-source"><a class="anchor" href="#nsa-salt-source"></a>2.2.5. <salt-source></h4> <div class="paragraph"> <p>Password salting strategy. A system-wide constant or a property from the UserDetails object can be used.</p> </div> <div class="sect4"> <h5 id="nsa-salt-source-parents"><a class="anchor" href="#nsa-salt-source-parents"></a>Parent Elements of <salt-source></h5> <div class="ulist"> <ul> <li> <p><a href="#nsa-password-encoder">password-encoder</a></p> </li> </ul> </div> </div> <div class="sect4"> <h5 id="nsa-salt-source-attributes"><a class="anchor" href="#nsa-salt-source-attributes"></a><salt-source> Attributes</h5> <div id="nsa-salt-source-ref" class="ulist"> <ul> <li> <p><strong>ref</strong> Defines a reference to a Spring bean Id.</p> </li> </ul> </div> <div id="nsa-salt-source-system-wide" class="ulist"> <ul> <li> <p><strong>system-wide</strong> A single value that will be used as the salt for a password encoder.</p> </li> </ul> </div> <div id="nsa-salt-source-user-property" class="ulist"> <ul> <li> <p><strong>user-property</strong> A property of the UserDetails object which will be used as salt by a password encoder. Typically something like "username" might be used.</p> </li> </ul> </div> </div> </div> <div class="sect3"> <h4 id="nsa-user-service"><a class="anchor" href="#nsa-user-service"></a>2.2.6. <user-service></h4> <div class="paragraph"> <p>Creates an in-memory UserDetailsService from a properties file or a list of "user" child elements. Usernames are converted to lower-case internally to allow for case-insensitive lookups, so this should not be used if case-sensitivity is required.</p> </div> <div class="sect4"> <h5 id="nsa-user-service-attributes"><a class="anchor" href="#nsa-user-service-attributes"></a><user-service> Attributes</h5> <div id="nsa-user-service-id" class="ulist"> <ul> <li> <p><strong>id</strong> A bean identifier, used for referring to the bean elsewhere in the context.</p> </li> </ul> </div> <div id="nsa-user-service-properties" class="ulist"> <ul> <li> <p><strong>properties</strong> The location of a Properties file where each line is in the format of</p> <div class="listingblock"> <div class="content"> <pre style="" class="prettyprint prettyprinted"><code><span class="pln">username</span><span class="pun">=</span><span class="pln">password</span><span class="pun">,</span><span class="pln">grantedAuthority</span><span class="pun">[,</span><span class="pln">grantedAuthority</span><span class="pun">][,</span><span class="pln">enabled</span><span class="pun">|</span><span class="pln">disabled</span><span class="pun">]</span></code></pre> </div> </div> </li> </ul> </div> </div> <div class="sect4"> <h5 id="nsa-user-service-children"><a class="anchor" href="#nsa-user-service-children"></a>Child Elements of <user-service></h5> <div class="ulist"> <ul> <li> <p><a href="#nsa-user">user</a></p> </li> </ul> </div> </div> </div> <div class="sect3"> <h4 id="nsa-user"><a class="anchor" href="#nsa-user"></a>2.2.7. <user></h4> <div class="paragraph"> <p>Represents a user in the application.</p> </div> <div class="sect4"> <h5 id="nsa-user-parents"><a class="anchor" href="#nsa-user-parents"></a>Parent Elements of <user></h5> <div class="ulist"> <ul> <li> <p><a href="#nsa-user-service">user-service</a></p> </li> </ul> </div> </div> <div class="sect4"> <h5 id="nsa-user-attributes"><a class="anchor" href="#nsa-user-attributes"></a><user> Attributes</h5> <div id="nsa-user-authorities" class="ulist"> <ul> <li> <p><strong>authorities</strong> One of more authorities granted to the user. Separate authorities with a comma (but no space). For example, "ROLE_USER,ROLE_ADMINISTRATOR"</p> </li> </ul> </div> <div id="nsa-user-disabled" class="ulist"> <ul> <li> <p><strong>disabled</strong> Can be set to "true" to mark an account as disabled and unusable.</p> </li> </ul> </div> <div id="nsa-user-locked" class="ulist"> <ul> <li> <p><strong>locked</strong> Can be set to "true" to mark an account as locked and unusable.</p> </li> </ul> </div> <div id="nsa-user-name" class="ulist"> <ul> <li> <p><strong>name</strong> The username assigned to the user.</p> </li> </ul> </div> <div id="nsa-user-password" class="ulist"> <ul> <li> <p><strong>password</strong> The password assigned to the user. This may be hashed if the corresponding authentication provider supports hashing (remember to set the "hash" attribute of the "user-service" element). This attribute be omitted in the case where the data will not be used for authentication, but only for accessing authorities. If omitted, the namespace will generate a random value, preventing its accidental use for authentication. Cannot be empty.</p> </li> </ul> </div> </div> </div> </div> <div class="sect2"> <h3 id="nsa-method-security"><a class="anchor" href="#nsa-method-security"></a>2.3. Method Security</h3> <div class="sect3"> <h4 id="nsa-global-method-security"><a class="anchor" href="#nsa-global-method-security"></a>2.3.1. <global-method-security></h4> <div class="paragraph"> <p>This element is the primary means of adding support for securing methods on Spring Security beans. Methods can be secured by the use of annotations (defined at the interface or class level) or by defining a set of pointcuts as child elements, using AspectJ syntax.</p> </div> <div class="sect4"> <h5 id="nsa-global-method-security-attributes"><a class="anchor" href="#nsa-global-method-security-attributes"></a><global-method-security> Attributes</h5> <div id="nsa-global-method-security-access-decision-manager-ref" class="ulist"> <ul> <li> <p><strong>access-decision-manager-ref</strong> Method security uses the same <code>AccessDecisionManager</code> configuration as web security, but this can be overridden using this attribute. By default an AffirmativeBased implementation is used for with a RoleVoter and an AuthenticatedVoter.</p> </li> </ul> </div> <div id="nsa-global-method-security-authentication-manager-ref" class="ulist"> <ul> <li> <p><strong>authentication-manager-ref</strong> A reference to an <code>AuthenticationManager</code> that should be used for method security.</p> </li> </ul> </div> <div id="nsa-global-method-security-jsr250-annotations" class="ulist"> <ul> <li> <p><strong>jsr250-annotations</strong> Specifies whether JSR-250 style attributes are to be used (for example "RolesAllowed"). This will require the javax.annotation.security classes on the classpath. Setting this to true also adds a <code>Jsr250Voter</code> to the <code>AccessDecisionManager</code>, so you need to make sure you do this if you are using a custom implementation and want to use these annotations.</p> </li> </ul> </div> <div id="nsa-global-method-security-metadata-source-ref" class="ulist"> <ul> <li> <p><strong>metadata-source-ref</strong> An external <code>MethodSecurityMetadataSource</code> instance can be supplied which will take priority over other sources (such as the default annotations).</p> </li> </ul> </div> <div id="nsa-global-method-security-mode" class="ulist"> <ul> <li> <p><strong>mode</strong> This attribute can be set to "aspectj" to specify that AspectJ should be used instead of the default Spring AOP. Secured methods must be woven with the <code>AnnotationSecurityAspect</code> from the <code>spring-security-aspects</code> module.</p> </li> </ul> </div> <div class="paragraph"> <p>It is important to note that AspectJ follows Java’s rule that annotations on interfaces are not inherited. This means that methods that define the Security annotaitons on the interface will not be secured. Instead, you must place the Security annotation on the class when using AspectJ.</p> </div> <div id="nsa-global-method-security-order" class="ulist"> <ul> <li> <p><strong>order</strong> Allows the advice "order" to be set for the method security interceptor.</p> </li> </ul> </div> <div id="nsa-global-method-security-pre-post-annotations" class="ulist"> <ul> <li> <p><strong>pre-post-annotations</strong> Specifies whether the use of Spring Security’s pre and post invocation annotations (@PreFilter, @PreAuthorize, @PostFilter, @PostAuthorize) should be enabled for this application context. Defaults to "disabled".</p> </li> </ul> </div> <div id="nsa-global-method-security-proxy-target-class" class="ulist"> <ul> <li> <p><strong>proxy-target-class</strong> If true, class based proxying will be used instead of interface based proxying.</p> </li> </ul> </div> <div id="nsa-global-method-security-run-as-manager-ref" class="ulist"> <ul> <li> <p><strong>run-as-manager-ref</strong> A reference to an optional <code>RunAsManager</code> implementation which will be used by the configured <code>MethodSecurityInterceptor</code></p> </li> </ul> </div> <div id="nsa-global-method-security-secured-annotations" class="ulist"> <ul> <li> <p><strong>secured-annotations</strong> Specifies whether the use of Spring Security’s @Secured annotations should be enabled for this application context. Defaults to "disabled".</p> </li> </ul> </div> </div> <div class="sect4"> <h5 id="nsa-global-method-security-children"><a class="anchor" href="#nsa-global-method-security-children"></a>Child Elements of <global-method-security></h5> <div class="ulist"> <ul> <li> <p><a href="#nsa-after-invocation-provider">after-invocation-provider</a></p> </li> <li> <p><a href="#nsa-expression-handler">expression-handler</a></p> </li> <li> <p><a href="#nsa-pre-post-annotation-handling">pre-post-annotation-handling</a></p> </li> <li> <p><a href="#nsa-protect-pointcut">protect-pointcut</a></p> </li> </ul> </div> </div> </div> <div class="sect3"> <h4 id="nsa-after-invocation-provider"><a class="anchor" href="#nsa-after-invocation-provider"></a>2.3.2. <after-invocation-provider></h4> <div class="paragraph"> <p>This element can be used to decorate an <code>AfterInvocationProvider</code> for use by the security interceptor maintained by the <code><global-method-security></code> namespace. You can define zero or more of these within the <code>global-method-security</code> element, each with a <code>ref</code> attribute pointing to an <code>AfterInvocationProvider</code> bean instance within your application context.</p> </div> <div class="sect4"> <h5 id="nsa-after-invocation-provider-parents"><a class="anchor" href="#nsa-after-invocation-provider-parents"></a>Parent Elements of <after-invocation-provider></h5> <div class="ulist"> <ul> <li> <p><a href="#nsa-global-method-security">global-method-security</a></p> </li> </ul> </div> </div> <div class="sect4"> <h5 id="nsa-after-invocation-provider-attributes"><a class="anchor" href="#nsa-after-invocation-provider-attributes"></a><after-invocation-provider> Attributes</h5> <div id="nsa-after-invocation-provider-ref" class="ulist"> <ul> <li> <p><strong>ref</strong> Defines a reference to a Spring bean that implements ` AfterInvocationProvider`.</p> </li> </ul> </div> </div> </div> <div class="sect3"> <h4 id="nsa-pre-post-annotation-handling"><a class="anchor" href="#nsa-pre-post-annotation-handling"></a>2.3.3. <pre-post-annotation-handling></h4> <div class="paragraph"> <p>Allows the default expression-based mechanism for handling Spring Security’s pre and post invocation annotations (@PreFilter, @PreAuthorize, @PostFilter, @PostAuthorize) to be replace entirely. Only applies if these annotations are enabled.</p> </div> <div class="sect4"> <h5 id="nsa-pre-post-annotation-handling-parents"><a class="anchor" href="#nsa-pre-post-annotation-handling-parents"></a>Parent Elements of <pre-post-annotation-handling></h5> <div class="ulist"> <ul> <li> <p><a href="#nsa-global-method-security">global-method-security</a></p> </li> </ul> </div> </div> <div class="sect4"> <h5 id="nsa-pre-post-annotation-handling-children"><a class="anchor" href="#nsa-pre-post-annotation-handling-children"></a>Child Elements of <pre-post-annotation-handling></h5> <div class="ulist"> <ul> <li> <p><a href="#nsa-invocation-attribute-factory">invocation-attribute-factory</a></p> </li> <li> <p><a href="#nsa-post-invocation-advice">post-invocation-advice</a></p> </li> <li> <p><a href="#nsa-pre-invocation-advice">pre-invocation-advice</a></p> </li> </ul> </div> </div> </div> <div class="sect3"> <h4 id="nsa-invocation-attribute-factory"><a class="anchor" href="#nsa-invocation-attribute-factory"></a>2.3.4. <invocation-attribute-factory></h4> <div class="paragraph"> <p>Defines the PrePostInvocationAttributeFactory instance which is used to generate pre and post invocation metadata from the annotated methods.</p> </div> <div class="sect4"> <h5 id="nsa-invocation-attribute-factory-parents"><a class="anchor" href="#nsa-invocation-attribute-factory-parents"></a>Parent Elements of <invocation-attribute-factory></h5> <div class="ulist"> <ul> <li> <p><a href="#nsa-pre-post-annotation-handling">pre-post-annotation-handling</a></p> </li> </ul> </div> </div> <div class="sect4"> <h5 id="nsa-invocation-attribute-factory-attributes"><a class="anchor" href="#nsa-invocation-attribute-factory-attributes"></a><invocation-attribute-factory> Attributes</h5> <div id="nsa-invocation-attribute-factory-ref" class="ulist"> <ul> <li> <p><strong>ref</strong> Defines a reference to a Spring bean Id.</p> </li> </ul> </div> </div> </div> <div class="sect3"> <h4 id="nsa-post-invocation-advice"><a class="anchor" href="#nsa-post-invocation-advice"></a>2.3.5. <post-invocation-advice></h4> <div class="paragraph"> <p>Customizes the <code>PostInvocationAdviceProvider</code> with the ref as the <code>PostInvocationAuthorizationAdvice</code> for the <pre-post-annotation-handling> element.</p> </div> <div class="sect4"> <h5 id="nsa-post-invocation-advice-parents"><a class="anchor" href="#nsa-post-invocation-advice-parents"></a>Parent Elements of <post-invocation-advice></h5> <div class="ulist"> <ul> <li> <p><a href="#nsa-pre-post-annotation-handling">pre-post-annotation-handling</a></p> </li> </ul> </div> </div> <div class="sect4"> <h5 id="nsa-post-invocation-advice-attributes"><a class="anchor" href="#nsa-post-invocation-advice-attributes"></a><post-invocation-advice> Attributes</h5> <div id="nsa-post-invocation-advice-ref" class="ulist"> <ul> <li> <p><strong>ref</strong> Defines a reference to a Spring bean Id.</p> </li> </ul> </div> </div> </div> <div class="sect3"> <h4 id="nsa-pre-invocation-advice"><a class="anchor" href="#nsa-pre-invocation-advice"></a>2.3.6. <pre-invocation-advice></h4> <div class="paragraph"> <p>Customizes the <code>PreInvocationAuthorizationAdviceVoter</code> with the ref as the <code>PreInvocationAuthorizationAdviceVoter</code> for the <pre-post-annotation-handling> element.</p> </div> <div class="sect4"> <h5 id="nsa-pre-invocation-advice-parents"><a class="anchor" href="#nsa-pre-invocation-advice-parents"></a>Parent Elements of <pre-invocation-advice></h5> <div class="ulist"> <ul> <li> <p><a href="#nsa-pre-post-annotation-handling">pre-post-annotation-handling</a></p> </li> </ul> </div> </div> <div class="sect4"> <h5 id="nsa-pre-invocation-advice-attributes"><a class="anchor" href="#nsa-pre-invocation-advice-attributes"></a><pre-invocation-advice> Attributes</h5> <div id="nsa-pre-invocation-advice-ref" class="ulist"> <ul> <li> <p><strong>ref</strong> Defines a reference to a Spring bean Id.</p> </li> </ul> </div> </div> </div> <div class="sect3"> <h4 id="nsa-protect-pointcut"><a class="anchor" href="#nsa-protect-pointcut"></a>2.3.7. Securing Methods using</h4> <div class="paragraph"> <p><code><protect-pointcut></code> Rather than defining security attributes on an individual method or class basis using the <code>@Secured</code> annotation, you can define cross-cutting security constraints across whole sets of methods and interfaces in your service layer using the <code><protect-pointcut></code> element. You can find an example in the <a href="#ns-protect-pointcut">namespace introduction</a>.</p> </div> <div class="sect4"> <h5 id="nsa-protect-pointcut-parents"><a class="anchor" href="#nsa-protect-pointcut-parents"></a>Parent Elements of <protect-pointcut></h5> <div class="ulist"> <ul> <li> <p><a href="#nsa-global-method-security">global-method-security</a></p> </li> </ul> </div> </div> <div class="sect4"> <h5 id="nsa-protect-pointcut-attributes"><a class="anchor" href="#nsa-protect-pointcut-attributes"></a><protect-pointcut> Attributes</h5> <div id="nsa-protect-pointcut-access" class="ulist"> <ul> <li> <p><strong>access</strong> Access configuration attributes list that applies to all methods matching the pointcut, e.g. "ROLE_A,ROLE_B"</p> </li> </ul> </div> <div id="nsa-protect-pointcut-expression" class="ulist"> <ul> <li> <p><strong>expression</strong> An AspectJ expression, including the <em>execution</em> keyword. For example, <em>execution(int com.foo.TargetObject.countLength(String))</em> (without the quotes).</p> </li> </ul> </div> </div> </div> <div class="sect3"> <h4 id="nsa-intercept-methods"><a class="anchor" href="#nsa-intercept-methods"></a>2.3.8. <intercept-methods></h4> <div class="paragraph"> <p>Can be used inside a bean definition to add a security interceptor to the bean and set up access configuration attributes for the bean’s methods</p> </div> <div class="sect4"> <h5 id="nsa-intercept-methods-attributes"><a class="anchor" href="#nsa-intercept-methods-attributes"></a><intercept-methods> Attributes</h5> <div id="nsa-intercept-methods-access-decision-manager-ref" class="ulist"> <ul> <li> <p><strong>access-decision-manager-ref</strong> Optional AccessDecisionManager bean ID to be used by the created method security interceptor.</p> </li> </ul> </div> </div> <div class="sect4"> <h5 id="nsa-intercept-methods-children"><a class="anchor" href="#nsa-intercept-methods-children"></a>Child Elements of <intercept-methods></h5> <div class="ulist"> <ul> <li> <p><a href="#nsa-protect">protect</a></p> </li> </ul> </div> </div> </div> <div class="sect3"> <h4 id="nsa-method-security-metadata-source"><a class="anchor" href="#nsa-method-security-metadata-source"></a>2.3.9. <method-security-metadata-source></h4> <div class="paragraph"> <p>Creates a MethodSecurityMetadataSource instance</p> </div> <div class="sect4"> <h5 id="nsa-method-security-metadata-source-attributes"><a class="anchor" href="#nsa-method-security-metadata-source-attributes"></a><method-security-metadata-source> Attributes</h5> <div id="nsa-method-security-metadata-source-id" class="ulist"> <ul> <li> <p><strong>id</strong> A bean identifier, used for referring to the bean elsewhere in the context.</p> </li> </ul> </div> <div id="nsa-method-security-metadata-source-use-expressions" class="ulist"> <ul> <li> <p><strong>use-expressions</strong> Enables the use of expressions in the <em>access</em> attributes in <intercept-url> elements rather than the traditional list of configuration attributes. Defaults to <em>false</em>. If enabled, each attribute should contain a single boolean expression. If the expression evaluates to <em>true</em>, access will be granted.</p> </li> </ul> </div> </div> <div class="sect4"> <h5 id="nsa-method-security-metadata-source-children"><a class="anchor" href="#nsa-method-security-metadata-source-children"></a>Child Elements of <method-security-metadata-source></h5> <div class="ulist"> <ul> <li> <p><a href="#nsa-protect">protect</a></p> </li> </ul> </div> </div> </div> <div class="sect3"> <h4 id="nsa-protect"><a class="anchor" href="#nsa-protect"></a>2.3.10. <protect></h4> <div class="paragraph"> <p>Defines a protected method and the access control configuration attributes that apply to it. We strongly advise you NOT to mix "protect" declarations with any services provided "global-method-security".</p> </div> <div class="sect4"> <h5 id="nsa-protect-parents"><a class="anchor" href="#nsa-protect-parents"></a>Parent Elements of <protect></h5> <div class="ulist"> <ul> <li> <p><a href="#nsa-intercept-methods">intercept-methods</a></p> </li> <li> <p><a href="#nsa-method-security-metadata-source">method-security-metadata-source</a></p> </li> </ul> </div> </div> <div class="sect4"> <h5 id="nsa-protect-attributes"><a class="anchor" href="#nsa-protect-attributes"></a><protect> Attributes</h5> <div id="nsa-protect-access" class="ulist"> <ul> <li> <p><strong>access</strong> Access configuration attributes list that applies to the method, e.g. "ROLE_A,ROLE_B".</p> </li> </ul> </div> <div id="nsa-protect-method" class="ulist"> <ul> <li> <p><strong>method</strong> A method name</p> </li> </ul> </div> </div> </div> </div> <div class="sect2"> <h3 id="nsa-ldap"><a class="anchor" href="#nsa-ldap"></a>2.4. LDAP Namespace Options</h3> <div class="paragraph"> <p>LDAP is covered in some details in <a href="#ldap">its own chapter</a>. We will expand on that here with some explanation of how the namespace options map to Spring beans. The LDAP implementation uses Spring LDAP extensively, so some familiarity with that project’s API may be useful.</p> </div> <div class="sect3"> <h4 id="nsa-ldap-server"><a class="anchor" href="#nsa-ldap-server"></a>2.4.1. Defining the LDAP Server using the</h4> <div class="paragraph"> <p><code><ldap-server></code> Element This element sets up a Spring LDAP <code>ContextSource</code> for use by the other LDAP beans, defining the location of the LDAP server and other information (such as a username and password, if it doesn’t allow anonymous access) for connecting to it. It can also be used to create an embedded server for testing. Details of the syntax for both options are covered in the <a href="#ldap-server">LDAP chapter</a>. The actual <code>ContextSource</code> implementation is <code>DefaultSpringSecurityContextSource</code> which extends Spring LDAP’s <code>LdapContextSource</code> class. The <code>manager-dn</code> and <code>manager-password</code> attributes map to the latter’s <code>userDn</code> and <code>password</code> properties respectively.</p> </div> <div class="paragraph"> <p>If you only have one server defined in your application context, the other LDAP namespace-defined beans will use it automatically. Otherwise, you can give the element an "id" attribute and refer to it from other namespace beans using the <code>server-ref</code> attribute. This is actually the bean <code>id</code> of the <code>ContextSource</code> instance, if you want to use it in other traditional Spring beans.</p> </div> <div class="sect4"> <h5 id="nsa-ldap-server-attributes"><a class="anchor" href="#nsa-ldap-server-attributes"></a><ldap-server> Attributes</h5> <div id="nsa-ldap-server-id" class="ulist"> <ul> <li> <p><strong>id</strong> A bean identifier, used for referring to the bean elsewhere in the context.</p> </li> </ul> </div> <div id="nsa-ldap-server-ldif" class="ulist"> <ul> <li> <p><strong>ldif</strong> Explicitly specifies an ldif file resource to load into an embedded LDAP server. The ldiff is should be a Spring resource pattern (i.e. classpath:init.ldiff). The default is classpath*:*.ldiff</p> </li> </ul> </div> <div id="nsa-ldap-server-manager-dn" class="ulist"> <ul> <li> <p><strong>manager-dn</strong> Username (DN) of the "manager" user identity which will be used to authenticate to a (non-embedded) LDAP server. If omitted, anonymous access will be used.</p> </li> </ul> </div> <div id="nsa-ldap-server-manager-password" class="ulist"> <ul> <li> <p><strong>manager-password</strong> The password for the manager DN. This is required if the manager-dn is specified.</p> </li> </ul> </div> <div id="nsa-ldap-server-port" class="ulist"> <ul> <li> <p><strong>port</strong> Specifies an IP port number. Used to configure an embedded LDAP server, for example. The default value is 33389.</p> </li> </ul> </div> <div id="nsa-ldap-server-root" class="ulist"> <ul> <li> <p><strong>root</strong> Optional root suffix for the embedded LDAP server. Default is "dc=springframework,dc=org"</p> </li> </ul> </div> <div id="nsa-ldap-server-url" class="ulist"> <ul> <li> <p><strong>url</strong> Specifies the ldap server URL when not using the embedded LDAP server.</p> </li> </ul> </div> </div> </div> <div class="sect3"> <h4 id="nsa-ldap-authentication-provider"><a class="anchor" href="#nsa-ldap-authentication-provider"></a>2.4.2. <ldap-authentication-provider></h4> <div class="paragraph"> <p>This element is shorthand for the creation of an <code>LdapAuthenticationProvider</code> instance. By default this will be configured with a <code>BindAuthenticator</code> instance and a <code>DefaultAuthoritiesPopulator</code>. As with all namespace authentication providers, it must be included as a child of the <code>authentication-provider</code> element.</p> </div> <div class="sect4"> <h5 id="nsa-ldap-authentication-provider-parents"><a class="anchor" href="#nsa-ldap-authentication-provider-parents"></a>Parent Elements of <ldap-authentication-provider></h5> <div class="ulist"> <ul> <li> <p><a href="#nsa-authentication-manager">authentication-manager</a></p> </li> </ul> </div> </div> <div class="sect4"> <h5 id="nsa-ldap-authentication-provider-attributes"><a class="anchor" href="#nsa-ldap-authentication-provider-attributes"></a><ldap-authentication-provider> Attributes</h5> <div id="nsa-ldap-authentication-provider-group-role-attribute" class="ulist"> <ul> <li> <p><strong>group-role-attribute</strong> The LDAP attribute name which contains the role name which will be used within Spring Security. Maps to the <code>DefaultLdapAuthoritiesPopulator</code>'s <code>groupRoleAttribute</code> property. Defaults to "cn".</p> </li> </ul> </div> <div id="nsa-ldap-authentication-provider-group-search-base" class="ulist"> <ul> <li> <p><strong>group-search-base</strong> Search base for group membership searches. Maps to the <code>DefaultLdapAuthoritiesPopulator</code>'s <code>groupSearchBase</code> constructor argument. Defaults to "" (searching from the root).</p> </li> </ul> </div> <div id="nsa-ldap-authentication-provider-group-search-filter" class="ulist"> <ul> <li> <p><strong>group-search-filter</strong> Group search filter. Maps to the <code>DefaultLdapAuthoritiesPopulator</code>'s <code>groupSearchFilter</code> property. Defaults to (uniqueMember={0}). The substituted parameter is the DN of the user.</p> </li> </ul> </div> <div id="nsa-ldap-authentication-provider-role-prefix" class="ulist"> <ul> <li> <p><strong>role-prefix</strong> A non-empty string prefix that will be added to role strings loaded from persistent. Maps to the <code>DefaultLdapAuthoritiesPopulator</code>'s <code>rolePrefix</code> property. Defaults to "ROLE_". Use the value "none" for no prefix in cases where the default is non-empty.</p> </li> </ul> </div> <div id="nsa-ldap-authentication-provider-server-ref" class="ulist"> <ul> <li> <p><strong>server-ref</strong> The optional server to use. If omitted, and a default LDAP server is registered (using <ldap-server> with no Id), that server will be used.</p> </li> </ul> </div> <div id="nsa-ldap-authentication-provider-user-context-mapper-ref" class="ulist"> <ul> <li> <p><strong>user-context-mapper-ref</strong> Allows explicit customization of the loaded user object by specifying a UserDetailsContextMapper bean which will be called with the context information from the user’s directory entry</p> </li> </ul> </div> <div id="nsa-ldap-authentication-provider-user-details-class" class="ulist"> <ul> <li> <p><strong>user-details-class</strong> Allows the objectClass of the user entry to be specified. If set, the framework will attempt to load standard attributes for the defined class into the returned UserDetails object</p> </li> </ul> </div> <div id="nsa-ldap-authentication-provider-user-dn-pattern" class="ulist"> <ul> <li> <p><strong>user-dn-pattern</strong> If your users are at a fixed location in the directory (i.e. you can work out the DN directly from the username without doing a directory search), you can use this attribute to map directly to the DN. It maps directly to the <code>userDnPatterns</code> property of <code>AbstractLdapAuthenticator</code>. The value is a specific pattern used to build the user’s DN, for example "uid={0},ou=people". The key "{0}" must be present and will be substituted with the username.</p> </li> </ul> </div> <div id="nsa-ldap-authentication-provider-user-search-base" class="ulist"> <ul> <li> <p><strong>user-search-base</strong> Search base for user searches. Defaults to "". Only used with a <em>user-search-filter</em>.</p> <div class="paragraph"> <p>If you need to perform a search to locate the user in the directory, then you can set these attributes to control the search. The <code>BindAuthenticator</code> will be configured with a <code>FilterBasedLdapUserSearch</code> and the attribute values map directly to the first two arguments of that bean’s constructor. If these attributes aren’t set and no <code>user-dn-pattern</code> has been supplied as an alternative, then the default search values of <code>user-search-filter="(uid={0})"</code> and <code>user-search-base=""</code> will be used.</p> </div> </li> </ul> </div> <div id="nsa-ldap-authentication-provider-user-search-filter" class="ulist"> <ul> <li> <p><strong>user-search-filter</strong> The LDAP filter used to search for users (optional). For example "(uid={0})". The substituted parameter is the user’s login name.</p> <div class="paragraph"> <p>If you need to perform a search to locate the user in the directory, then you can set these attributes to control the search. The <code>BindAuthenticator</code> will be configured with a <code>FilterBasedLdapUserSearch</code> and the attribute values map directly to the first two arguments of that bean’s constructor. If these attributes aren’t set and no <code>user-dn-pattern</code> has been supplied as an alternative, then the default search values of <code>user-search-filter="(uid={0})"</code> and <code>user-search-base=""</code> will be used.</p> </div> </li> </ul> </div> </div> <div class="sect4"> <h5 id="nsa-ldap-authentication-provider-children"><a class="anchor" href="#nsa-ldap-authentication-provider-children"></a>Child Elements of <ldap-authentication-provider></h5> <div class="ulist"> <ul> <li> <p><a href="#nsa-password-compare">password-compare</a></p> </li> </ul> </div> </div> </div> <div class="sect3"> <h4 id="nsa-password-compare"><a class="anchor" href="#nsa-password-compare"></a>2.4.3. <password-compare></h4> <div class="paragraph"> <p>This is used as child element to <code><ldap-provider></code> and switches the authentication strategy from <code>BindAuthenticator</code> to <code>PasswordComparisonAuthenticator</code>.</p> </div> <div class="sect4"> <h5 id="nsa-password-compare-parents"><a class="anchor" href="#nsa-password-compare-parents"></a>Parent Elements of <password-compare></h5> <div class="ulist"> <ul> <li> <p><a href="#nsa-ldap-authentication-provider">ldap-authentication-provider</a></p> </li> </ul> </div> </div> <div class="sect4"> <h5 id="nsa-password-compare-attributes"><a class="anchor" href="#nsa-password-compare-attributes"></a><password-compare> Attributes</h5> <div id="nsa-password-compare-hash" class="ulist"> <ul> <li> <p><strong>hash</strong> Defines the hashing algorithm used on user passwords. We recommend strongly against using MD4, as it is a very weak hashing algorithm.</p> </li> </ul> </div> <div id="nsa-password-compare-password-attribute" class="ulist"> <ul> <li> <p><strong>password-attribute</strong> The attribute in the directory which contains the user password. Defaults to "userPassword".</p> </li> </ul> </div> </div> <div class="sect4"> <h5 id="nsa-password-compare-children"><a class="anchor" href="#nsa-password-compare-children"></a>Child Elements of <password-compare></h5> <div class="ulist"> <ul> <li> <p><a href="#nsa-password-encoder">password-encoder</a></p> </li> </ul> </div> </div> </div> <div class="sect3"> <h4 id="nsa-ldap-user-service"><a class="anchor" href="#nsa-ldap-user-service"></a>2.4.4. <ldap-user-service></h4> <div class="paragraph"> <p>This element configures an LDAP <code>UserDetailsService</code>. The class used is <code>LdapUserDetailsService</code> which is a combination of a <code>FilterBasedLdapUserSearch</code> and a <code>DefaultLdapAuthoritiesPopulator</code>. The attributes it supports have the same usage as in <code><ldap-provider></code>.</p> </div> <div class="sect4"> <h5 id="nsa-ldap-user-service-attributes"><a class="anchor" href="#nsa-ldap-user-service-attributes"></a><ldap-user-service> Attributes</h5> <div id="nsa-ldap-user-service-cache-ref" class="ulist"> <ul> <li> <p><strong>cache-ref</strong> Defines a reference to a cache for use with a UserDetailsService.</p> </li> </ul> </div> <div id="nsa-ldap-user-service-group-role-attribute" class="ulist"> <ul> <li> <p><strong>group-role-attribute</strong> The LDAP attribute name which contains the role name which will be used within Spring Security. Defaults to "cn".</p> </li> </ul> </div> <div id="nsa-ldap-user-service-group-search-base" class="ulist"> <ul> <li> <p><strong>group-search-base</strong> Search base for group membership searches. Defaults to "" (searching from the root).</p> </li> </ul> </div> <div id="nsa-ldap-user-service-group-search-filter" class="ulist"> <ul> <li> <p><strong>group-search-filter</strong> Group search filter. Defaults to (uniqueMember={0}). The substituted parameter is the DN of the user.</p> </li> </ul> </div> <div id="nsa-ldap-user-service-id" class="ulist"> <ul> <li> <p><strong>id</strong> A bean identifier, used for referring to the bean elsewhere in the context.</p> </li> </ul> </div> <div id="nsa-ldap-user-service-role-prefix" class="ulist"> <ul> <li> <p><strong>role-prefix</strong> A non-empty string prefix that will be added to role strings loaded from persistent storage (e.g. "ROLE_"). Use the value "none" for no prefix in cases where the default is non-empty.</p> </li> </ul> </div> <div id="nsa-ldap-user-service-server-ref" class="ulist"> <ul> <li> <p><strong>server-ref</strong> The optional server to use. If omitted, and a default LDAP server is registered (using <ldap-server> with no Id), that server will be used.</p> </li> </ul> </div> <div id="nsa-ldap-user-service-user-context-mapper-ref" class="ulist"> <ul> <li> <p><strong>user-context-mapper-ref</strong> Allows explicit customization of the loaded user object by specifying a UserDetailsContextMapper bean which will be called with the context information from the user’s directory entry</p> </li> </ul> </div> <div id="nsa-ldap-user-service-user-details-class" class="ulist"> <ul> <li> <p><strong>user-details-class</strong> Allows the objectClass of the user entry to be specified. If set, the framework will attempt to load standard attributes for the defined class into the returned UserDetails object</p> </li> </ul> </div> <div id="nsa-ldap-user-service-user-search-base" class="ulist"> <ul> <li> <p><strong>user-search-base</strong> Search base for user searches. Defaults to "". Only used with a <em>user-search-filter</em>.</p> </li> </ul> </div> <div id="nsa-ldap-user-service-user-search-filter" class="ulist"> <ul> <li> <p><strong>user-search-filter</strong> The LDAP filter used to search for users (optional). For example "(uid={0})". The substituted parameter is the user’s login name.</p> </li> </ul> </div> </div> </div> </div> </div> </div> <div class="sect1"> <h2 id="appendix-dependencies"><a class="anchor" href="#appendix-dependencies"></a>3. Spring Security Dependencies</h2> <div class="sectionbody"> <div class="paragraph"> <p>This appendix provides a reference of the modules in Spring Security and the additional dependencies that they require in order to function in a running application. We don’t include dependenices that are only used when building or testing Spring Security itself. Nor do we include transitive dependencies which are required by external dependencies.</p> </div> <div class="paragraph"> <p>The version of Spring required is listed on the project website, so the specific versions are omitted for Spring dependencies below. Note that some of the dependencies listed as"optional" below may still be required for other non-security functionality in a Spring application. Also dependencies listed as "optional" may not actually be marked as such in the project’s Maven pom files if they are used in most applications. They are"optional" only in the sense that you don’t need them unless you are using the specified functionality.</p> </div> <div class="paragraph"> <p>Where a module depends on another Spring Security module, the non-optional dependencies of the module it depends on are also assumed to be required and are not listed separately.</p> </div> <div class="sect2"> <h3 id="spring-security-core-2"><a class="anchor" href="#spring-security-core-2"></a>3.1. spring-security-core</h3> <div class="paragraph"> <p>The core module must be included in any project using Spring Security.</p> </div> <table class="tableblock frame-all grid-all" style="width:100%; "> <caption class="title">Table 3. Core Depenendencies</caption> <colgroup> <col style="width:33%;"> <col style="width:33%;"> <col style="width:33%;"> </colgroup> <thead> <tr> <th class="tableblock halign-left valign-top">Dependency</th> <th class="tableblock halign-left valign-top">Version</th> <th class="tableblock halign-left valign-top">Description</th> </tr> </thead> <tbody> <tr> <td class="tableblock halign-left valign-top"><p class="tableblock">aopalliance</p></td> <td class="tableblock halign-left valign-top"><p class="tableblock">1.0</p></td> <td class="tableblock halign-left valign-top"><p class="tableblock">Required for method security implementation.</p></td> </tr> <tr> <td class="tableblock halign-left valign-top"><p class="tableblock">ehcache</p></td> <td class="tableblock halign-left valign-top"><p class="tableblock">1.6.2</p></td> <td class="tableblock halign-left valign-top"><p class="tableblock">Required if the ehcache-based user cache implementation is used (optional).</p></td> </tr> <tr> <td class="tableblock halign-left valign-top"><p class="tableblock">spring-aop</p></td> <td class="tableblock halign-left valign-top"></td> <td class="tableblock halign-left valign-top"><p class="tableblock">Method security is based on Spring AOP</p></td> </tr> <tr> <td class="tableblock halign-left valign-top"><p class="tableblock">spring-beans</p></td> <td class="tableblock halign-left valign-top"></td> <td class="tableblock halign-left valign-top"><p class="tableblock">Required for Spring configuration</p></td> </tr> <tr> <td class="tableblock halign-left valign-top"><p class="tableblock">spring-expression</p></td> <td class="tableblock halign-left valign-top"></td> <td class="tableblock halign-left valign-top"><p class="tableblock">Required for expression-based method security (optional)</p></td> </tr> <tr> <td class="tableblock halign-left valign-top"><p class="tableblock">spring-jdbc</p></td> <td class="tableblock halign-left valign-top"></td> <td class="tableblock halign-left valign-top"><p class="tableblock">Required if using a database to store user data (optional).</p></td> </tr> <tr> <td class="tableblock halign-left valign-top"><p class="tableblock">spring-tx</p></td> <td class="tableblock halign-left valign-top"></td> <td class="tableblock halign-left valign-top"><p class="tableblock">Required if using a database to store user data (optional).</p></td> </tr> <tr> <td class="tableblock halign-left valign-top"><p class="tableblock">aspectjrt</p></td> <td class="tableblock halign-left valign-top"><p class="tableblock">1.6.10</p></td> <td class="tableblock halign-left valign-top"><p class="tableblock">Required if using AspectJ support (optional).</p></td> </tr> <tr> <td class="tableblock halign-left valign-top"><p class="tableblock">jsr250-api</p></td> <td class="tableblock halign-left valign-top"><p class="tableblock">1.0</p></td> <td class="tableblock halign-left valign-top"><p class="tableblock">Required if you are using JSR-250 method-security annotations (optional).</p></td> </tr> </tbody> </table> </div> <div class="sect2"> <h3 id="spring-security-remoting-2"><a class="anchor" href="#spring-security-remoting-2"></a>3.2. spring-security-remoting</h3> <div class="paragraph"> <p>This module is typically required in web applications which use the Servlet API.</p> </div> <table class="tableblock frame-all grid-all" style="width:100%; "> <caption class="title">Table 4. Remoting Dependencies</caption> <colgroup> <col style="width:33%;"> <col style="width:33%;"> <col style="width:33%;"> </colgroup> <thead> <tr> <th class="tableblock halign-left valign-top">Dependency</th> <th class="tableblock halign-left valign-top">Version</th> <th class="tableblock halign-left valign-top">Description</th> </tr> </thead> <tbody> <tr> <td class="tableblock halign-left valign-top"><p class="tableblock">spring-security-core</p></td> <td class="tableblock halign-left valign-top"></td> <td class="tableblock halign-left valign-top"></td> </tr> <tr> <td class="tableblock halign-left valign-top"><p class="tableblock">spring-web</p></td> <td class="tableblock halign-left valign-top"></td> <td class="tableblock halign-left valign-top"><p class="tableblock">Required for clients which use HTTP remoting support.</p></td> </tr> </tbody> </table> </div> <div class="sect2"> <h3 id="spring-security-web-2"><a class="anchor" href="#spring-security-web-2"></a>3.3. spring-security-web</h3> <div class="paragraph"> <p>This module is typically required in web applications which use the Servlet API.</p> </div> <table class="tableblock frame-all grid-all" style="width:100%; "> <caption class="title">Table 5. Web Dependencies</caption> <colgroup> <col style="width:33%;"> <col style="width:33%;"> <col style="width:33%;"> </colgroup> <thead> <tr> <th class="tableblock halign-left valign-top">Dependency</th> <th class="tableblock halign-left valign-top">Version</th> <th class="tableblock halign-left valign-top">Description</th> </tr> </thead> <tbody> <tr> <td class="tableblock halign-left valign-top"><p class="tableblock">spring-security-core</p></td> <td class="tableblock halign-left valign-top"></td> <td class="tableblock halign-left valign-top"></td> </tr> <tr> <td class="tableblock halign-left valign-top"><p class="tableblock">spring-web</p></td> <td class="tableblock halign-left valign-top"></td> <td class="tableblock halign-left valign-top"><p class="tableblock">Spring web support classes are used extensively.</p></td> </tr> <tr> <td class="tableblock halign-left valign-top"><p class="tableblock">spring-jdbc</p></td> <td class="tableblock halign-left valign-top"></td> <td class="tableblock halign-left valign-top"><p class="tableblock">Required for JDBC-based persistent remember-me token repository (optional).</p></td> </tr> <tr> <td class="tableblock halign-left valign-top"><p class="tableblock">spring-tx</p></td> <td class="tableblock halign-left valign-top"></td> <td class="tableblock halign-left valign-top"><p class="tableblock">Required by remember-me persistent token repository implementations (optional).</p></td> </tr> </tbody> </table> </div> <div class="sect2"> <h3 id="spring-security-ldap-2"><a class="anchor" href="#spring-security-ldap-2"></a>3.4. spring-security-ldap</h3> <div class="paragraph"> <p>This module is only required if you are using LDAP authentication.</p> </div> <table class="tableblock frame-all grid-all" style="width:100%; "> <caption class="title">Table 6. LDAP Dependencies</caption> <colgroup> <col style="width:33%;"> <col style="width:33%;"> <col style="width:33%;"> </colgroup> <thead> <tr> <th class="tableblock halign-left valign-top">Dependency</th> <th class="tableblock halign-left valign-top">Version</th> <th class="tableblock halign-left valign-top">Description</th> </tr> </thead> <tbody> <tr> <td class="tableblock halign-left valign-top"><p class="tableblock">spring-security-core</p></td> <td class="tableblock halign-left valign-top"></td> <td class="tableblock halign-left valign-top"></td> </tr> <tr> <td class="tableblock halign-left valign-top"><p class="tableblock">spring-ldap-core</p></td> <td class="tableblock halign-left valign-top"><p class="tableblock">1.3.0</p></td> <td class="tableblock halign-left valign-top"><p class="tableblock">LDAP support is based on Spring LDAP.</p></td> </tr> <tr> <td class="tableblock halign-left valign-top"><p class="tableblock">spring-tx</p></td> <td class="tableblock halign-left valign-top"></td> <td class="tableblock halign-left valign-top"><p class="tableblock">Data exception classes are required.</p></td> </tr> <tr> <td class="tableblock halign-left valign-top"><p class="tableblock">apache-ds <span class="footnote">[<a id="_footnoteref_27" class="footnote" href="#_footnote_27" title="View footnote.">27</a>]</span></p></td> <td class="tableblock halign-left valign-top"><p class="tableblock">1.5.5</p></td> <td class="tableblock halign-left valign-top"><p class="tableblock">Required if you are using an embedded LDAP server (optional).</p></td> </tr> <tr> <td class="tableblock halign-left valign-top"><p class="tableblock">shared-ldap</p></td> <td class="tableblock halign-left valign-top"><p class="tableblock">0.9.15</p></td> <td class="tableblock halign-left valign-top"><p class="tableblock">Required if you are using an embedded LDAP server (optional).</p></td> </tr> <tr> <td class="tableblock halign-left valign-top"><p class="tableblock">ldapsdk</p></td> <td class="tableblock halign-left valign-top"><p class="tableblock">4.1</p></td> <td class="tableblock halign-left valign-top"><p class="tableblock">Mozilla LdapSDK. Used for decoding LDAP password policy controls if you are using password-policy functionality with OpenLDAP, for example.</p></td> </tr> </tbody> </table> </div> <div class="sect2"> <h3 id="spring-security-config-2"><a class="anchor" href="#spring-security-config-2"></a>3.5. spring-security-config</h3> <div class="paragraph"> <p>This module is required if you are using Spring Security namespace configuration.</p> </div> <table class="tableblock frame-all grid-all" style="width:100%; "> <caption class="title">Table 7. Config Dependencies</caption> <colgroup> <col style="width:33%;"> <col style="width:33%;"> <col style="width:33%;"> </colgroup> <thead> <tr> <th class="tableblock halign-left valign-top">Dependency</th> <th class="tableblock halign-left valign-top">Version</th> <th class="tableblock halign-left valign-top">Description</th> </tr> </thead> <tbody> <tr> <td class="tableblock halign-left valign-top"><p class="tableblock">spring-security-core</p></td> <td class="tableblock halign-left valign-top"></td> <td class="tableblock halign-left valign-top"></td> </tr> <tr> <td class="tableblock halign-left valign-top"><p class="tableblock">spring-security-web</p></td> <td class="tableblock halign-left valign-top"></td> <td class="tableblock halign-left valign-top"><p class="tableblock">Required if you are using any web-related namespace configuration (optional).</p></td> </tr> <tr> <td class="tableblock halign-left valign-top"><p class="tableblock">spring-security-ldap</p></td> <td class="tableblock halign-left valign-top"></td> <td class="tableblock halign-left valign-top"><p class="tableblock">Required if you are using the LDAP namespace options (optional).</p></td> </tr> <tr> <td class="tableblock halign-left valign-top"><p class="tableblock">spring-security-openid</p></td> <td class="tableblock halign-left valign-top"></td> <td class="tableblock halign-left valign-top"><p class="tableblock">Required if you are using OpenID authentication (optional).</p></td> </tr> <tr> <td class="tableblock halign-left valign-top"><p class="tableblock">aspectjweaver</p></td> <td class="tableblock halign-left valign-top"><p class="tableblock">1.6.10</p></td> <td class="tableblock halign-left valign-top"><p class="tableblock">Required if using the protect-pointcut namespace syntax (optional).</p></td> </tr> </tbody> </table> </div> <div class="sect2"> <h3 id="spring-security-acl-2"><a class="anchor" href="#spring-security-acl-2"></a>3.6. spring-security-acl</h3> <div class="paragraph"> <p>The ACL module.</p> </div> <table class="tableblock frame-all grid-all" style="width:100%; "> <caption class="title">Table 8. ACL Dependencies</caption> <colgroup> <col style="width:33%;"> <col style="width:33%;"> <col style="width:33%;"> </colgroup> <thead> <tr> <th class="tableblock halign-left valign-top">Dependency</th> <th class="tableblock halign-left valign-top">Version</th> <th class="tableblock halign-left valign-top">Description</th> </tr> </thead> <tbody> <tr> <td class="tableblock halign-left valign-top"><p class="tableblock">spring-security-core</p></td> <td class="tableblock halign-left valign-top"></td> <td class="tableblock halign-left valign-top"></td> </tr> <tr> <td class="tableblock halign-left valign-top"><p class="tableblock">ehcache</p></td> <td class="tableblock halign-left valign-top"><p class="tableblock">1.6.2</p></td> <td class="tableblock halign-left valign-top"><p class="tableblock">Required if the ehcache-based ACL cache implementation is used (optional if you are using your own implementation).</p></td> </tr> <tr> <td class="tableblock halign-left valign-top"><p class="tableblock">spring-jdbc</p></td> <td class="tableblock halign-left valign-top"></td> <td class="tableblock halign-left valign-top"><p class="tableblock">Required if you are using the default JDBC-based AclService (optional if you implement your own).</p></td> </tr> <tr> <td class="tableblock halign-left valign-top"><p class="tableblock">spring-tx</p></td> <td class="tableblock halign-left valign-top"></td> <td class="tableblock halign-left valign-top"><p class="tableblock">Required if you are using the default JDBC-based AclService (optional if you implement your own).</p></td> </tr> </tbody> </table> </div> <div class="sect2"> <h3 id="spring-security-cas-2"><a class="anchor" href="#spring-security-cas-2"></a>3.7. spring-security-cas</h3> <div class="paragraph"> <p>The CAS module provides integration with JA-SIG CAS.</p> </div> <table class="tableblock frame-all grid-all" style="width:100%; "> <caption class="title">Table 9. CAS Dependencies</caption> <colgroup> <col style="width:33%;"> <col style="width:33%;"> <col style="width:33%;"> </colgroup> <thead> <tr> <th class="tableblock halign-left valign-top">Dependency</th> <th class="tableblock halign-left valign-top">Version</th> <th class="tableblock halign-left valign-top">Description</th> </tr> </thead> <tbody> <tr> <td class="tableblock halign-left valign-top"><p class="tableblock">spring-security-core</p></td> <td class="tableblock halign-left valign-top"></td> <td class="tableblock halign-left valign-top"></td> </tr> <tr> <td class="tableblock halign-left valign-top"><p class="tableblock">spring-security-web</p></td> <td class="tableblock halign-left valign-top"></td> <td class="tableblock halign-left valign-top"></td> </tr> <tr> <td class="tableblock halign-left valign-top"><p class="tableblock">cas-client-core</p></td> <td class="tableblock halign-left valign-top"><p class="tableblock">3.1.12</p></td> <td class="tableblock halign-left valign-top"><p class="tableblock">The JA-SIG CAS Client. This is the basis of the Spring Security integration.</p></td> </tr> <tr> <td class="tableblock halign-left valign-top"><p class="tableblock">ehcache</p></td> <td class="tableblock halign-left valign-top"><p class="tableblock">1.6.2</p></td> <td class="tableblock halign-left valign-top"><p class="tableblock">Required if you are using the ehcache-based ticket cache (optional).</p></td> </tr> </tbody> </table> </div> <div class="sect2"> <h3 id="spring-security-openid-2"><a class="anchor" href="#spring-security-openid-2"></a>3.8. spring-security-openid</h3> <div class="paragraph"> <p>The OpenID module.</p> </div> <table class="tableblock frame-all grid-all" style="width:100%; "> <caption class="title">Table 10. OpenID Dependencies</caption> <colgroup> <col style="width:33%;"> <col style="width:33%;"> <col style="width:33%;"> </colgroup> <thead> <tr> <th class="tableblock halign-left valign-top">Dependency</th> <th class="tableblock halign-left valign-top">Version</th> <th class="tableblock halign-left valign-top">Description</th> </tr> </thead> <tbody> <tr> <td class="tableblock halign-left valign-top"><p class="tableblock">spring-security-core</p></td> <td class="tableblock halign-left valign-top"></td> <td class="tableblock halign-left valign-top"></td> </tr> <tr> <td class="tableblock halign-left valign-top"><p class="tableblock">spring-security-web</p></td> <td class="tableblock halign-left valign-top"></td> <td class="tableblock halign-left valign-top"></td> </tr> <tr> <td class="tableblock halign-left valign-top"><p class="tableblock">openid4java-nodeps</p></td> <td class="tableblock halign-left valign-top"><p class="tableblock">0.9.6</p></td> <td class="tableblock halign-left valign-top"><p class="tableblock">Spring Security’s OpenID integration uses OpenID4Java.</p></td> </tr> <tr> <td class="tableblock halign-left valign-top"><p class="tableblock">httpclient</p></td> <td class="tableblock halign-left valign-top"><p class="tableblock">4.1.1</p></td> <td class="tableblock halign-left valign-top"><p class="tableblock">openid4java-nodeps depends on HttpClient 4.</p></td> </tr> <tr> <td class="tableblock halign-left valign-top"><p class="tableblock">guice</p></td> <td class="tableblock halign-left valign-top"><p class="tableblock">2.0</p></td> <td class="tableblock halign-left valign-top"><p class="tableblock">openid4java-nodeps depends on Guice 2.</p></td> </tr> </tbody> </table> </div> <div class="sect2"> <h3 id="spring-security-taglibs"><a class="anchor" href="#spring-security-taglibs"></a>3.9. spring-security-taglibs</h3> <div class="paragraph"> <p>Provides Spring Security’s JSP tag implementations.</p> </div> <table class="tableblock frame-all grid-all" style="width:100%; "> <caption class="title">Table 11. Taglib Dependencies</caption> <colgroup> <col style="width:33%;"> <col style="width:33%;"> <col style="width:33%;"> </colgroup> <thead> <tr> <th class="tableblock halign-left valign-top">Dependency</th> <th class="tableblock halign-left valign-top">Version</th> <th class="tableblock halign-left valign-top">Description</th> </tr> </thead> <tbody> <tr> <td class="tableblock halign-left valign-top"><p class="tableblock">spring-security-core</p></td> <td class="tableblock halign-left valign-top"></td> <td class="tableblock halign-left valign-top"></td> </tr> <tr> <td class="tableblock halign-left valign-top"><p class="tableblock">spring-security-web</p></td> <td class="tableblock halign-left valign-top"></td> <td class="tableblock halign-left valign-top"></td> </tr> <tr> <td class="tableblock halign-left valign-top"><p class="tableblock">spring-security-acl</p></td> <td class="tableblock halign-left valign-top"></td> <td class="tableblock halign-left valign-top"><p class="tableblock">Required if you are using the <code>accesscontrollist</code> tag or <code>hasPermission()</code> expressions with ACLs (optional).</p></td> </tr> <tr> <td class="tableblock halign-left valign-top"><p class="tableblock">spring-expression</p></td> <td class="tableblock halign-left valign-top"></td> <td class="tableblock halign-left valign-top"><p class="tableblock">Required if you are using SPEL expressions in your tag access constraints.</p></td> </tr> </tbody> </table> </div> </div> </div> </div> <div id="footnotes"> <hr> <div class="footnote" id="_footnote_1"> <a href="#_footnoteref_1">1</a>. You can find out more about the use of the <code>ldap-server</code> element in the chapter on <a href="#ldap">LDAP Authentication</a>. </div> <div class="footnote" id="_footnote_2"> <a href="#_footnoteref_2">2</a>. See the section on <a href="#request-matching">Request Matching and HttpFirewall</a> in the Web Application Infrastructure chapter for more details on how matches are actually performed. </div> <div class="footnote" id="_footnote_3"> <a href="#_footnoteref_3">3</a>. The interpretation of the comma-separated values in the <code>access</code> attribute depends on the implementation of the <a href="#ns-access-manager">AccessDecisionManager</a> which is used. In Spring Security 3.0, the attribute can also be populated with an <a href="#el-access">EL expression</a>. </div> <div class="footnote" id="_footnote_4"> <a href="#_footnoteref_4">4</a>. See the chapter on <a href="#anonymous">Anonymous Authentication</a> </div> <div class="footnote" id="_footnote_5"> <a href="#_footnoteref_5">5</a>. The use of multiple <code><http></code> elements is an important feature, allowing the namespace to simultaneously support both stateful and stateless paths within the same application, for example. The previous syntax, using the attribute <code>filters="none"</code> on an <code>intercept-url</code> element is incompatible with this change and is no longer supported in 3.1. </div> <div class="footnote" id="_footnote_6"> <a href="#_footnoteref_6">6</a>. For more details on how channel-processing is implemented, see the Javadoc for <code>ChannelProcessingFilter</code> and related classes. </div> <div class="footnote" id="_footnote_7"> <a href="#_footnoteref_7">7</a>. It isn’t possible to create a session once the response has been committed. </div> <div class="footnote" id="_footnote_8"> <a href="#_footnoteref_8">8</a>. Note that you’ll need to include the security namespace in your application context XML file in order to use this syntax. The older syntax which used a <code>filter-chain-map</code> is still supported, but is deprecated in favour of the constructor argument injection. </div> <div class="footnote" id="_footnote_9"> <a href="#_footnoteref_9">9</a>. Instead of a path pattern, the <code>request-matcher-ref</code> attribute can be used to specify a <code>RequestMatcher</code> instance for more powerful matching </div> <div class="footnote" id="_footnote_10"> <a href="#_footnoteref_10">10</a>. You have probably seen this when a browser doesn’t support cookies and the <code>jsessionid</code> parameter is appended to the URL after a semi-colon. However the RFC allows the presence of these parameters in any path segment of the URL </div> <div class="footnote" id="_footnote_11"> <a href="#_footnoteref_11">11</a>. The original values will be returned once the request leaves the <code>FilterChainProxy</code>, so will still be available to the application. </div> <div class="footnote" id="_footnote_12"> <a href="#_footnoteref_12">12</a>. So, for example, an original request path <code>/secure;hack=1/somefile.html;hack=2</code> will be returned as <code>/secure/somefile.html</code>. </div> <div class="footnote" id="_footnote_13"> <a href="#_footnoteref_13">13</a>. We use a forward so that the SecurityContextHolder still contains details of the principal, which may be useful for displaying to the user. In old releases of Spring Security we relied upon the servlet container to handle a 403 error message, which lacked this useful contextual information. </div> <div class="footnote" id="_footnote_14"> <a href="#_footnoteref_14">14</a>. In Spring Security 2.0 and earlier, this filter was called <code>HttpSessionContextIntegrationFilter</code> and performed all the work of storing the context was performed by the filter itself. If you were familiar with this class, then most of the configuration options which were available can now be found on`HttpSessionSecurityContextRepository`. </div> <div class="footnote" id="_footnote_15"> <a href="#_footnoteref_15">15</a>. For historical reasons, prior to Spring Security 3.0, this filter was called <code>AuthenticationProcessingFilter</code> and the entry point was called <code>AuthenticationProcessingFilterEntryPoint</code>. Since the framework now supports many different forms of authentication, they have both been given more specific names in 3.0. </div> <div class="footnote" id="_footnote_16"> <a href="#_footnoteref_16">16</a>. In versions prior to 3.0, the application flow at this point had evolved to a stage was controlled by a mix of properties on this class and strategy plugins. The decision was made for 3.0 to refactor the code to make these two strategies entirely responsible. </div> <div class="footnote" id="_footnote_17"> <a href="#_footnoteref_17">17</a>. It is possible to encode the password in the format HEX( MD5(username:realm:password) ) provided the <code>DigestAuthenticationFilter.passwordAlreadyEncoded</code> is set to <code>true</code>. However, other password encodings will not work with digest authentication. </div> <div class="footnote" id="_footnote_18"> <a href="#_footnoteref_18">18</a>. Essentially, the username is not included in the cookie, to prevent exposing a valid login name unecessarily. There is a discussion on this in the comments section of this article. </div> <div class="footnote" id="_footnote_19"> <a href="#_footnoteref_19">19</a>. Authentication by mechanisms which perform a redirect after authenticating (such as form-login) will not be detected by`SessionManagementFilter`, as the filter will not be invoked during the authenticating request. Session-management functionality has to be handled separately in these cases. </div> <div class="footnote" id="_footnote_20"> <a href="#_footnoteref_20">20</a>. The use of the <code>key</code> property should not be regarded as providing any real security here. It is merely a book-keeping exercise. If you are sharing a <code>ProviderManager</code> which contains an <code>AnonymousAuthenticationProvider</code> in a scenario where it is possible for an authenticating client to construct the <code>Authentication</code> object (such as with RMI invocations), then a malicious client could submit an <code>AnonymousAuthenticationToken</code> which it had created itself (with chosen username and authority list). If the <code>key</code> is guessable or can be found out, then the token would be accepted by the anonymous provider. This isn’t a problem with normal usage but if you are using RMI you would be best to use a customized <code>ProviderManager</code> which omits the anonymous provider rather than sharing the one you use for your HTTP authentication mechanisms. </div> <div class="footnote" id="_footnote_21"> <a href="#_footnoteref_21">21</a>. Note that this is different from the default configuration of the underlying <code>DefaultLdapAuthoritiesPopulator</code> which uses <code>member={0}</code>. </div> <div class="footnote" id="_footnote_22"> <a href="#_footnoteref_22">22</a>. It is also possible to obtain the server’s IP address using a DNS lookup. This is not currently supported, but hopefully will be in a future version. </div> <div class="footnote" id="_footnote_23"> <a href="#_footnoteref_23">23</a>. The legacy options from Spring Security 2.0 are also supported, but discouraged. </div> <div class="footnote" id="_footnote_24"> <a href="#_footnoteref_24">24</a>. See the <a href="#ns-web-xml">introductory chapter</a> for how to set up the mapping from your <code>web.xml</code> </div> <div class="footnote" id="_footnote_25"> <a href="#_footnoteref_25">25</a>. This feature is really just provided for convenience and is not intended for production (where a view technology will have been chosen and can be used to render a customized login page). The class <code>DefaultLoginPageGeneratingFilter</code> is responsible for rendering the login page and will provide login forms for both normal form login and/or OpenID if required. </div> <div class="footnote" id="_footnote_26"> <a href="#_footnoteref_26">26</a>. This doesn’t affect the use of <code>PersistentTokenBasedRememberMeServices</code>, where the tokens are stored on the server side. </div> <div class="footnote" id="_footnote_27"> <a href="#_footnoteref_27">27</a>. The modules <code>apacheds-core</code>, <code>apacheds-core-entry</code>, <code>apacheds-protocol-shared</code>, <code>apacheds-protocol-ldap</code> and <code>apacheds-server-jndi</code> are required. </div> </div> <div id="footer"> <div id="footer-text"> Version 3.2.6.RELEASE<br> Last updated 2015-02-25 08:07:49 PST </div> </div> <!-- Begin new Google code - a mod --> <script type="text/javascript"> var _gaq = _gaq || []; var pluginUrl = '//www.google-analytics.com/plugins/ga/inpage_linkid.js'; _gaq.push( ['_require', 'inpage_linkid', pluginUrl], ['_setAccount', 'UA-2728886-23'], ['_trackPageview'], ['b._require', 'inpage_linkid', pluginUrl], ['b._setAccount', 'UA-2728886-19'], ['b._trackPageview'] ); (function() { var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true; ga.src = ('https:' == document.location.protocol ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js'; var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s); })(); </script> <!-- End 2nd Google code --> <script type="text/javascript"> function detectLastFrame() { var thisF = this.window; var allF = parent.top.frames; return allF[allF.length - 1] == thisF; } // Only inject the following code if this is a normal page or the last // frame of a frameset. if (parent.top.frames.length == 0 || detectLastFrame()) { // Inject the SpringSource search widget too. document.write(unescape("%3Cscript src='http://search.springsource.org/widget/searchtool.js' type='text/javascript'%3E%3C/script%3E")); // Inject the Eloqua code //document.write(unescape("%3Cscript src='/elqNow/elqCfg.js' type='text/javascript'%3E%3C/script%3E")); //document.write(unescape("%3Cscript src='/elqNow/elqImg.js' type='text/javascript'%3E%3C/script%3E")); } </script><script src="Spring%20Security%20Reference_files/searchtool.js" type="text/javascript"></script> <script type="text/javascript"> /* <![CDATA[ */ (function(){try{var s,a,i,j,r,c,l=document.getElementsByTagName("a"),t=document.createElement("textarea");for(i=0;l.length-i;i++){try{a=l[i].getAttribute("href");if(a&&a.indexOf("/cdn-cgi/l/email-protection") > -1 && (a.length > 28)){s='';j=27+ 1 + a.indexOf("/cdn-cgi/l/email-protection");if (a.length > j) {r=parseInt(a.substr(j,2),16);for(j+=2;a.length>j&&a.substr(j,1)!='X';j+=2){c=parseInt(a.substr(j,2),16)^r;s+=String.fromCharCode(c);}j+=1;s+=a.substr(j,a.length-j);}t.innerHTML=s.replace(/</g,"<").replace(/>/g,">");l[i].setAttribute("href","mailto:"+t.value);}}catch(e){}}}catch(e){}})(); /* ]]> */ </script> <div id="bodyEmptyFiller"> </div><div id="searchBar"> <div style="left:-1px;bottom:1px;" id="collapseLink"><a href="javascript:void(0);"><img class="springClass" src="Spring%20Security%20Reference_files/ArrowLeft_spring.png" border="0"></a></div> <div id="logoSpan" class="springClass"><a target="_new" href="http://spring.io/"><img class="springClass" src="Spring%20Security%20Reference_files/Logo_spring_SearchBar.png" border="0"></a></div> <div id="searchFields"> <input style="color: rgb(204, 204, 204);" name="searchKeys" id="searchKeys" value="Search Documentation" type="text"> <select name="searchWhat" id="searchWhat"><option selected="selected" value="all">all</option><option value="Spring">Spring</option><option value="Grails">Grails</option><option value="Gemstone">Gemstone</option><option value="RabbitMQ">RabbitMQ</option></select> <img title="Search Documentation" src="Spring%20Security%20Reference_files/Btn_Search_spring.png" id="searchLens"> </div> <div id="resultsDiv"></div> <div id="daAd"> <script type="text/javascript"> (function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){ (i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o), m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m) })(window,document,'script','//www.google-analytics.com/analytics.js','gaPiAd'); gaPiAd('create', 'UA-42481901-1', 'none'); gaPiAd('send', 'event', 'Impression', 'What's New in Spring [V1.0] - 13 Jun 2015 - Live Online', location.href); var gaPiAdClick_54dcdc20e5de8829ab000007 = function() { gaPiAd('send', 'event', 'Click', 'What's New in Spring [V1.0] - 13 Jun 2015 - Live Online', location.href) }; </script><div class="PivotalAdBannerDiv"> <style> /* custom banner style placeholder */ /* #gaPiAdDivId_54dcdc20e5de8829ab000007 { } */ </style> <a style="text-decoration:none;" onclick="gaPiAdClick_54dcdc20e5de8829ab000007();" href="http://mylearn.vmware.com/gateway/?credits=0&course=254903" target="_new"> <div id="gaPiAdDivId_54dcdc20e5de8829ab000007" class="S2UniGeoipBanner"> <span class="S2GPcourse_name">What's New in Spring [V1.0]</span> <span class="S2GPcity">Live Online, </span> <span class="S2GPstart_date">13 Jun 2015</span> <span class="learn-more-button">Learn More</span> </div></a> </div> </div></div></body></html>