<?xml version="1.0" encoding="UTF-8"?><rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	>

<channel>
	<title>Spring Security &#8211; My Shitty Code</title>
	<atom:link href="https://myshittycode.com/tag/spring-security/feed/" rel="self" type="application/rss+xml" />
	<link>https://myshittycode.com</link>
	<description>Embracing the Messiness in Search of Epic Solutions</description>
	<lastBuildDate>Fri, 06 Jan 2023 17:01:41 +0000</lastBuildDate>
	<language>en-US</language>
	<sy:updatePeriod>
	hourly	</sy:updatePeriod>
	<sy:updateFrequency>
	1	</sy:updateFrequency>
	<generator>https://wordpress.org/?v=6.9.1</generator>

<image>
	<url>https://myshittycode.com/wp-content/uploads/2022/04/cropped-icon-32x32.png</url>
	<title>Spring Security &#8211; My Shitty Code</title>
	<link>https://myshittycode.com</link>
	<width>32</width>
	<height>32</height>
</image> 
<site xmlns="com-wordpress:feed-additions:1">205304208</site>	<item>
		<title>Spring Security: Propagating Security Context to Spawned Threads</title>
		<link>https://myshittycode.com/2018/03/09/spring-security-propagating-security-context-to-spawned-threads/</link>
					<comments>https://myshittycode.com/2018/03/09/spring-security-propagating-security-context-to-spawned-threads/#respond</comments>
		
		<dc:creator><![CDATA[Shitty Author]]></dc:creator>
		<pubDate>Sat, 10 Mar 2018 03:09:49 +0000</pubDate>
				<category><![CDATA[Programming Language]]></category>
		<category><![CDATA[Groovy]]></category>
		<category><![CDATA[Spring Security]]></category>
		<guid isPermaLink="false">http://myshittycode.com/?p=1068</guid>

					<description><![CDATA[<p>PROBLEM Let&#8217;s assume we have the following Parent class&#8230; &#8230; and Child class&#8230; Let&#8217;s also assume the user has successfully logged in and Spring Security has set up the user authentication info. The Parent will spawn a new thread (through @Async) to run Child. When invoking the Parent, this is what we see:- The Child, [&#8230;]</p>
<p>The post <a rel="nofollow" href="https://myshittycode.com/2018/03/09/spring-security-propagating-security-context-to-spawned-threads/">Spring Security: Propagating Security Context to Spawned Threads</a> appeared first on <a rel="nofollow" href="https://myshittycode.com">My Shitty Code</a>.</p>
]]></description>
										<content:encoded><![CDATA[
<h2 class="wp-block-heading">PROBLEM</h2>



<p>Let&#8217;s assume we have the following <b>Parent</b> class&#8230;</p>


<div class="wp-block-syntaxhighlighter-code "><pre class="brush: groovy; title: ; notranslate">
@Service
class Parent {
    @Autowired
    Child child

    void run() {
        println &quot;Parent: ${SecurityContextHolder.context.authentication?.principal}&quot;

        child.run()

        println &quot;Parent: Done&quot;
    }
}
</pre></div>


<p>&#8230; and <b>Child</b> class&#8230;</p>


<div class="wp-block-syntaxhighlighter-code "><pre class="brush: groovy; title: ; notranslate">
@Service
class Child {
    @Async
    void run() {
        Thread.sleep(500)
        println &quot;Child: ${SecurityContextHolder.context.authentication?.principal}&quot;
    }
}
</pre></div>


<p>Let&#8217;s also assume the user has successfully logged in and Spring Security has set up the user authentication info.</p>



<p>The <b>Parent</b> will spawn a new thread (through <b>@Async</b>) to run <b>Child</b>.</p>



<p>When invoking the <b>Parent</b>, this is what we see:-</p>


<div class="wp-block-syntaxhighlighter-code "><pre class="brush: plain; title: ; notranslate">
Parent: USER_PRINCIPAL
Parent: Done
Child: null
</pre></div>


<p>The <b>Child</b>, for some reason, doesn&#8217;t get the receive the user authentication info.</p>



<h2 class="wp-block-heading">SOLUTION</h2>



<p>By default, <b>SecurityContextHolder</b> uses <b>MODE_THREADLOCAL</b> to store the user authentication info. As a result, this info is not accessible to methods outside the current execution thread.</p>



<p>To fix this, configure <b>SecurityContextHolder</b> to use <b>MODE_INHERITABLETHREADLOCAL</b> to pass the user authentication info to other spawned threads.</p>


<div class="wp-block-syntaxhighlighter-code "><pre class="brush: groovy; highlight: [5]; title: ; notranslate">
@Configuration
@EnableAsync
class AppConfig {
    AppConfig() {
        SecurityContextHolder.setStrategyName(SecurityContextHolder.MODE_INHERITABLETHREADLOCAL)
    }
}
</pre></div>


<p>When invoking the <b>Parent</b> again, now the <b>Child</b> will also receive the user authentication object:-</p>


<div class="wp-block-syntaxhighlighter-code "><pre class="brush: plain; title: ; notranslate">
Parent: USER_PRINCIPAL
Parent: Done
Child: USER_PRINCIPAL
</pre></div>


<p></p>
<p>The post <a rel="nofollow" href="https://myshittycode.com/2018/03/09/spring-security-propagating-security-context-to-spawned-threads/">Spring Security: Propagating Security Context to Spawned Threads</a> appeared first on <a rel="nofollow" href="https://myshittycode.com">My Shitty Code</a>.</p>
]]></content:encoded>
					
					<wfw:commentRss>https://myshittycode.com/2018/03/09/spring-security-propagating-security-context-to-spawned-threads/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
		<post-id xmlns="com-wordpress:feed-additions:1">1068</post-id>	</item>
		<item>
		<title>JEE Security: Preventing Clickjacking Attacks</title>
		<link>https://myshittycode.com/2017/08/31/jee-security-preventing-clickjacking-attacks/</link>
					<comments>https://myshittycode.com/2017/08/31/jee-security-preventing-clickjacking-attacks/#respond</comments>
		
		<dc:creator><![CDATA[Shitty Author]]></dc:creator>
		<pubDate>Thu, 31 Aug 2017 15:03:05 +0000</pubDate>
				<category><![CDATA[Programming Language]]></category>
		<category><![CDATA[Groovy]]></category>
		<category><![CDATA[Java]]></category>
		<category><![CDATA[Spring]]></category>
		<category><![CDATA[Spring Boot]]></category>
		<category><![CDATA[Spring Security]]></category>
		<guid isPermaLink="false">http://myshittycode.com/?p=1066</guid>

					<description><![CDATA[<p>PROBLEM Clickjacking is an attack that tricks the users to perform unintended actions&#8230; see OWASP&#8217;s Testing for Clickjacking (OTG-CLIENT-009) SOLUTION To prevent clickjacking attacks, the app must set X-FRAME-OPTIONS header with an appropriate value:- If set correctly, the HTTPS response should show X-FRAME-OPTIONS header:- There are several ways to set this header. Solution 1: Using [&#8230;]</p>
<p>The post <a rel="nofollow" href="https://myshittycode.com/2017/08/31/jee-security-preventing-clickjacking-attacks/">JEE Security: Preventing Clickjacking Attacks</a> appeared first on <a rel="nofollow" href="https://myshittycode.com">My Shitty Code</a>.</p>
]]></description>
										<content:encoded><![CDATA[
<h2 class="wp-block-heading">PROBLEM</h2>



<p>Clickjacking is an attack that tricks the users to perform unintended actions&#8230; see <a href="https://www.owasp.org/index.php/Testing_for_Clickjacking_(OTG-CLIENT-009)" target="_blank" rel="noopener">OWASP&#8217;s Testing for Clickjacking (OTG-CLIENT-009)</a></p>



<h2 class="wp-block-heading">SOLUTION</h2>



<p>To prevent clickjacking attacks, the app must set X-FRAME-OPTIONS header with an appropriate value:-</p>



<ul class="wp-block-list">
<li><b>DENY</b>: this denies any domain using the page as an iFrame source. This is the best option.</li>



<li><b>SAMEORIGIN</b>: this allows pages within the same domain to use other application pages as iFrame sources.</li>



<li><b>ALLOW-FROM [whitelisted domains]</b>: this declares a list of domains that are allowed to include the pages as iFrame sources.</li>
</ul>



<p>If set correctly, the HTTPS response should show X-FRAME-OPTIONS header:-</p>


<div class="wp-block-syntaxhighlighter-code "><pre class="brush: plain; highlight: [9]; title: ; notranslate">
➜  ~ curl -i -k https://localhost:8443/
HTTP/1.1 200
X-Content-Type-Options: nosniff
X-XSS-Protection: 1; mode=block
Cache-Control: no-cache, no-store, max-age=0, must-revalidate
Pragma: no-cache
Expires: 0
Strict-Transport-Security: max-age=31536000 ; includeSubDomains
X-Frame-Options: DENY
X-Application-Context: application:local:8443
Set-Cookie: JSESSIONID=04ADDAF886A20AA561021E869E980BCC; Path=/; Secure; HttpOnly
Content-Type: text/html;charset=UTF-8
Content-Language: en-US
Content-Length: 631
Date: Thu, 31 Aug 2017 14:56:57 GMT
</pre></div>


<p>There are several ways to set this header.</p>



<h3 class="wp-block-heading">Solution 1: Using a servlet filter</h3>



<p>You may create a servlet filter that sets X-FRAME-OPTIONS in the response header.</p>



<p>Here&#8217;s an example using web.xml-less Spring Boot:-</p>


<div class="wp-block-syntaxhighlighter-code "><pre class="brush: groovy; highlight: [12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,32,33,34,35]; title: ; notranslate">
@SpringBootApplication
class Application extends SpringBootServletInitializer {
    static void main(String&#x5B;] args) {
        SpringApplication.run(Application, args)
    }

    @Override
    protected SpringApplicationBuilder configure(SpringApplicationBuilder builder) {
        return builder.sources(Application)
    }

    @Bean
    FilterRegistrationBean clickjackingPreventionFilter() {
        return new FilterRegistrationBean(
                urlPatterns: &#x5B;&#039;/**&#039;],
                filter: new Filter() {
                    @Override
                    void init(final FilterConfig filterConfig) throws ServletException {
                    }

                    @Override
                    void doFilter(final ServletRequest servletRequest,
                                  final ServletResponse servletResponse,
                                  final FilterChain filterChain) throws IOException, ServletException {
                        final HttpServletResponse response = (HttpServletResponse) servletResponse
                        response.addHeader(&#039;X-FRAME-OPTIONS&#039;, &#039;DENY&#039;)
                        filterChain.doFilter(servletRequest, servletResponse)
                    }

                    @Override
                    void destroy() {
                    }
                }
        )
    }
}
</pre></div>


<h3 class="wp-block-heading">Solution 2: Using Spring Security</h3>



<p>Spring Security provides a very easy way to set the X-FRAME-OPTIONS header:-</p>


<div class="wp-block-syntaxhighlighter-code "><pre class="brush: groovy; highlight: [7]; title: ; notranslate">
@Configuration
@EnableWebSecurity
class SecurityConfig extends WebSecurityConfigurerAdapter {
    @Override
    protected void configure(final HttpSecurity http) throws Exception {
        http.
                headers().frameOptions().deny().
                and().
                authorizeRequests().
                antMatchers(&#039;/**&#039;).permitAll()
    }
}
</pre></div><p>The post <a rel="nofollow" href="https://myshittycode.com/2017/08/31/jee-security-preventing-clickjacking-attacks/">JEE Security: Preventing Clickjacking Attacks</a> appeared first on <a rel="nofollow" href="https://myshittycode.com">My Shitty Code</a>.</p>
]]></content:encoded>
					
					<wfw:commentRss>https://myshittycode.com/2017/08/31/jee-security-preventing-clickjacking-attacks/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
		<post-id xmlns="com-wordpress:feed-additions:1">1066</post-id>	</item>
		<item>
		<title>Spring Security: Invalid CSRF Token &#8216;null&#8217; was found on the request parameter &#8216;_csrf&#8217; or header &#8216;X-CSRF-TOKEN&#8217;</title>
		<link>https://myshittycode.com/2015/03/30/spring-security-invalid-csrf-token-null-was-found-on-the-request-parameter-_csrf-or-header-x-csrf-token/</link>
					<comments>https://myshittycode.com/2015/03/30/spring-security-invalid-csrf-token-null-was-found-on-the-request-parameter-_csrf-or-header-x-csrf-token/#comments</comments>
		
		<dc:creator><![CDATA[Shitty Author]]></dc:creator>
		<pubDate>Mon, 30 Mar 2015 20:37:25 +0000</pubDate>
				<category><![CDATA[Programming Language]]></category>
		<category><![CDATA[CSRF]]></category>
		<category><![CDATA[Java]]></category>
		<category><![CDATA[Spring Security]]></category>
		<guid isPermaLink="false">http://myshittycode.com/?p=689</guid>

					<description><![CDATA[<p>PROBLEM With Spring Security 4.x, the CSRF protection is enabled by default. You may disable it, but to be more aligned with OWASP and the industry security standard, it&#8217;s best to leave this setting the way it is. Learn more about CSRF attack&#8230; To prevent this attack, Spring Security 4.x requires you to attach a [&#8230;]</p>
<p>The post <a rel="nofollow" href="https://myshittycode.com/2015/03/30/spring-security-invalid-csrf-token-null-was-found-on-the-request-parameter-_csrf-or-header-x-csrf-token/">Spring Security: Invalid CSRF Token &#8216;null&#8217; was found on the request parameter &#8216;_csrf&#8217; or header &#8216;X-CSRF-TOKEN&#8217;</a> appeared first on <a rel="nofollow" href="https://myshittycode.com">My Shitty Code</a>.</p>
]]></description>
										<content:encoded><![CDATA[
<h2 class="wp-block-heading">PROBLEM</h2>



<p>With Spring Security 4.x, the CSRF protection is enabled by default. You may disable it, but to be more aligned with OWASP and the industry security standard, it&#8217;s best to leave this setting the way it is. <a href="https://www.owasp.org/index.php/Cross-Site_Request_Forgery_%28CSRF%29" target="_blank" rel="noopener">Learn more about CSRF attack&#8230;</a></p>



<p>To prevent this attack, Spring Security 4.x requires you to attach a server-side generated CSRF token on any POST, PUT or DELETE calls&#8230; basically, actions that may modify the request state. Their argument for not attaching this token on GET is to prevent this token value from leaking out.</p>



<p>Further, you will require to call <b>POST /login</b> and <b>POST /logout</b> now. In the past, you can call <b>GET /j_spring_security_logout</b> without problem.</p>



<p>If you invoke POST, PUT or DELETE without this CSRF token, you will get a 403 error with this message: <b>&#8220;Invalid CSRF Token &#8216;null&#8217; was found on the request parameter &#8216;_csrf&#8217; or header &#8216;X-CSRF-TOKEN&#8217;.&#8221;</b>.</p>



<h2 class="wp-block-heading">SOLUTION</h2>



<p>To obtain this CSRF token, add this Spring Security custom tag to the JSP file:-</p>


<div class="wp-block-syntaxhighlighter-code "><pre class="brush: xml; highlight: [4]; title: ; notranslate">
&lt;!DOCTYPE html&gt;
&lt;html&gt;
	&lt;head&gt;
	    &lt;sec:csrfMetaTags/&gt;
	&lt;/head&gt;
	&lt;body&gt;
	&lt;/body&gt;
&lt;/html&gt;
</pre></div>


<p>The rendered HTML looks like this:-</p>


<div class="wp-block-syntaxhighlighter-code "><pre class="brush: xml; highlight: [4,5,6]; title: ; notranslate">
&lt;!DOCTYPE html&gt;
&lt;html class=&quot;no-js&quot;&gt;
	&lt;head&gt;
	    &lt;meta name=&quot;_csrf_parameter&quot; content=&quot;_csrf&quot; /&gt;
	    &lt;meta name=&quot;_csrf_header&quot; content=&quot;X-CSRF-TOKEN&quot; /&gt;
	    &lt;meta name=&quot;_csrf&quot; content=&quot;e62835df-f1a0-49ea-bce7-bf96f998119c&quot; /&gt;
	&lt;/head&gt;
	&lt;body&gt;
	&lt;/body&gt;
&lt;/html&gt;
</pre></div>


<p>Finally, set the request header before making the AJAX call:-</p>


<div class="wp-block-syntaxhighlighter-code "><pre class="brush: jscript; title: ; notranslate">
var header = $(&quot;meta&#x5B;name=&#039;_csrf_header&#039;]&quot;).attr(&quot;content&quot;);
var token = $(&quot;meta&#x5B;name=&#039;_csrf&#039;]&quot;).attr(&quot;content&quot;);

$.ajax({
    url: &#039;/test&#039;,
    type: &#039;POST&#039;,
    beforeSend: function(xhr){
        xhr.setRequestHeader(header, token);
    },
    success: function(data) {
        console.log(data);
    },
    error: function (xhr, ajaxOptions, thrownError) {
        console.log(xhr.status + &quot;: &quot; + thrownError);
    }
});
</pre></div><p>The post <a rel="nofollow" href="https://myshittycode.com/2015/03/30/spring-security-invalid-csrf-token-null-was-found-on-the-request-parameter-_csrf-or-header-x-csrf-token/">Spring Security: Invalid CSRF Token &#8216;null&#8217; was found on the request parameter &#8216;_csrf&#8217; or header &#8216;X-CSRF-TOKEN&#8217;</a> appeared first on <a rel="nofollow" href="https://myshittycode.com">My Shitty Code</a>.</p>
]]></content:encoded>
					
					<wfw:commentRss>https://myshittycode.com/2015/03/30/spring-security-invalid-csrf-token-null-was-found-on-the-request-parameter-_csrf-or-header-x-csrf-token/feed/</wfw:commentRss>
			<slash:comments>4</slash:comments>
		
		
		<post-id xmlns="com-wordpress:feed-additions:1">689</post-id>	</item>
		<item>
		<title>Spring Security: Forcing URLs to use HTTPS</title>
		<link>https://myshittycode.com/2014/06/12/spring-security-forcing-urls-to-use-https/</link>
					<comments>https://myshittycode.com/2014/06/12/spring-security-forcing-urls-to-use-https/#comments</comments>
		
		<dc:creator><![CDATA[Shitty Author]]></dc:creator>
		<pubDate>Thu, 12 Jun 2014 19:20:56 +0000</pubDate>
				<category><![CDATA[Programming Language]]></category>
		<category><![CDATA[Java]]></category>
		<category><![CDATA[Spring Security]]></category>
		<guid isPermaLink="false">http://myshittycode.com/?p=514</guid>

					<description><![CDATA[<p>PROBLEM Your web application supports both HTTP and HTTPS. You want to force all URLs to use HTTPS. SOLUTION Spring Security has a simple configuration that allows us to redirect all HTTP-based URLs to HTTPS. All we have to do is to set requires-channel=&#8221;https&#8221; on &#60;security:intercept-url/&#62; tag. For example:- With this configuration, when the user [&#8230;]</p>
<p>The post <a rel="nofollow" href="https://myshittycode.com/2014/06/12/spring-security-forcing-urls-to-use-https/">Spring Security: Forcing URLs to use HTTPS</a> appeared first on <a rel="nofollow" href="https://myshittycode.com">My Shitty Code</a>.</p>
]]></description>
										<content:encoded><![CDATA[
<h2 class="wp-block-heading">PROBLEM</h2>



<p>Your web application supports both HTTP and HTTPS. You want to force all URLs to use HTTPS.</p>



<h2 class="wp-block-heading">SOLUTION</h2>



<p>Spring Security has a simple configuration that allows us to redirect all HTTP-based URLs to HTTPS. All we have to do is to set <b>requires-channel=&#8221;https&#8221;</b> on <b>&lt;security:intercept-url/&gt;</b> tag.</p>



<p>For example:-</p>


<div class="wp-block-syntaxhighlighter-code "><pre class="brush: xml; highlight: [5,6,7]; title: ; notranslate">
&lt;security:http auto-config=&quot;true&quot;&gt;
	&lt;security:form-login .../&gt;
	&lt;security:logout .../&gt;

	&lt;security:intercept-url pattern=&quot;/reports&quot; access=&quot;ROLE_ADMIN&quot; requires-channel=&quot;https&quot;/&gt;
	&lt;security:intercept-url pattern=&quot;/login&quot; access=&quot;IS_AUTHENTICATED_ANONYMOUSLY&quot; requires-channel=&quot;https&quot;/&gt;
	&lt;security:intercept-url pattern=&quot;/**&quot; access=&quot;ROLE_USER&quot; requires-channel=&quot;https&quot;/&gt;
&lt;/security:http&gt;
</pre></div>


<p>With this configuration, when the user hits <b>http://server/app</b>, it will be redirected to <b>https://server/app</b>.</p>



<p>If we are seeing this &#8220;redirect loop&#8221; error&#8230;</p>



<figure class="wp-block-image aligncenter"><img fetchpriority="high" decoding="async" width="642" height="259" src="https://myshittycode.com/wp-content/uploads/2014/06/screen-shot-2014-06-12-at-1-42-22-pm-1.png?x45560" alt="" class="wp-image-515" srcset="https://myshittycode.com/wp-content/uploads/2014/06/screen-shot-2014-06-12-at-1-42-22-pm-1.png 642w, https://myshittycode.com/wp-content/uploads/2014/06/screen-shot-2014-06-12-at-1-42-22-pm-1-300x121.png 300w" sizes="(max-width: 642px) 100vw, 642px" /></figure>



<p>&#8230; and the server log went bananas&#8230;</p>


<div class="wp-block-syntaxhighlighter-code "><pre class="brush: xml; title: ; notranslate">
&quot;GET /app HTTP/1.1&quot; 302 0
&quot;GET /app/ HTTP/1.1&quot; 302 0
&quot;GET /app/app/ HTTP/1.1&quot; 302 0
&quot;GET /app/app/app/ HTTP/1.1&quot; 302 0
&quot;GET /app/app/app/app/ HTTP/1.1&quot; 302 0
&quot;GET /app/app/app/app/app/ HTTP/1.1&quot; 302 0
&quot;GET /app/app/app/app/app/app/ HTTP/1.1&quot; 302 0
&quot;GET /app/app/app/app/app/app/app/ HTTP/1.1&quot; 302 0
&quot;GET /app/app/app/app/app/app/app/app/ HTTP/1.1&quot; 302 0
&quot;GET /app/app/app/app/app/app/app/app/app/ HTTP/1.1&quot; 302 0
</pre></div>


<p>&#8230; then, chances are we are not using the default HTTP port (80) and HTTPS port (443). To fix this, we have to specify the custom port mappings in the Spring Security configuration:-</p>


<div class="wp-block-syntaxhighlighter-code "><pre class="brush: xml; highlight: [9,10,11,12,13,14,15,16,17,18]; title: ; notranslate">
&lt;security:http auto-config=&quot;true&quot;&gt;
	&lt;security:form-login .../&gt;
	&lt;security:logout .../&gt;

	&lt;security:intercept-url pattern=&quot;/reports&quot; access=&quot;ROLE_ADMIN&quot; requires-channel=&quot;https&quot;/&gt;
	&lt;security:intercept-url pattern=&quot;/login&quot; access=&quot;IS_AUTHENTICATED_ANONYMOUSLY&quot; requires-channel=&quot;https&quot;/&gt;
	&lt;security:intercept-url pattern=&quot;/**&quot; access=&quot;ROLE_USER&quot; requires-channel=&quot;https&quot;/&gt;

	&lt;security:port-mappings&gt;
		&lt;!-- Default ports --&gt;
		&lt;security:port-mapping http=&quot;80&quot; https=&quot;443&quot;/&gt;
		&lt;!-- Websphere default ports --&gt;
		&lt;security:port-mapping http=&quot;9080&quot; https=&quot;9443&quot;/&gt;
		&lt;!-- Tomcat default ports --&gt;
		&lt;security:port-mapping http=&quot;8080&quot; https=&quot;8443&quot;/&gt;
		&lt;!-- Jetty custom ports --&gt;
		&lt;security:port-mapping http=&quot;7777&quot; https=&quot;7443&quot;/&gt;
	&lt;/security:port-mappings&gt;
&lt;/security:http&gt;
</pre></div>


<p>Now, when the user hits <b>http://localhost:7777/app</b>, it will be redirected to <b>https://localhost:7443/app</b>.</p>
<p>The post <a rel="nofollow" href="https://myshittycode.com/2014/06/12/spring-security-forcing-urls-to-use-https/">Spring Security: Forcing URLs to use HTTPS</a> appeared first on <a rel="nofollow" href="https://myshittycode.com">My Shitty Code</a>.</p>
]]></content:encoded>
					
					<wfw:commentRss>https://myshittycode.com/2014/06/12/spring-security-forcing-urls-to-use-https/feed/</wfw:commentRss>
			<slash:comments>1</slash:comments>
		
		
		<post-id xmlns="com-wordpress:feed-additions:1">514</post-id>	</item>
		<item>
		<title>Spring Security: Handling 403 Error Page</title>
		<link>https://myshittycode.com/2014/04/11/spring-security-handling-403-error-page/</link>
					<comments>https://myshittycode.com/2014/04/11/spring-security-handling-403-error-page/#respond</comments>
		
		<dc:creator><![CDATA[Shitty Author]]></dc:creator>
		<pubDate>Fri, 11 Apr 2014 14:58:31 +0000</pubDate>
				<category><![CDATA[Programming Language]]></category>
		<category><![CDATA[SiteMesh]]></category>
		<category><![CDATA[Spring MVC]]></category>
		<category><![CDATA[Spring Security]]></category>
		<guid isPermaLink="false">http://myshittycode.com/?p=480</guid>

					<description><![CDATA[<p>If you are already using Spring, then you might want to use Spring Security to secure your web resources. To do that, we specify the URI to be secured with &#60;security:intercept-url/&#62; tag:- When users without role ROLE_TOPSECRET access /top-secrets/kfc-secret, they will see this default error page:- This proves that Spring Security is doing its job. [&#8230;]</p>
<p>The post <a rel="nofollow" href="https://myshittycode.com/2014/04/11/spring-security-handling-403-error-page/">Spring Security: Handling 403 Error Page</a> appeared first on <a rel="nofollow" href="https://myshittycode.com">My Shitty Code</a>.</p>
]]></description>
										<content:encoded><![CDATA[
<p>If you are already using Spring, then you might want to use Spring Security to secure your web resources.</p>



<p>To do that, we specify the URI to be secured with <code>&lt;security:intercept-url/&gt;</code> tag:-</p>


<div class="wp-block-syntaxhighlighter-code "><pre class="brush: xml; highlight: [8]; title: ; notranslate">
&lt;beans ...&gt;
    &lt;!-- Error pages don&#039;t need to be secured --&gt;
    &lt;security:http pattern=&quot;/error/**&quot; security=&quot;none&quot;/&gt;

    &lt;security:http auto-config=&quot;true&quot;&gt;
        &lt;security:form-login ... /&gt;
        &lt;security:logout ... /&gt;
        &lt;security:intercept-url pattern=&quot;/top-secrets/**&quot; access=&quot;ROLE_TOPSECRET&quot;/&gt;
    &lt;/security:http&gt;
	...
&lt;/beans&gt;
</pre></div>


<p>When users without role <code>ROLE_TOPSECRET</code> access <code>/top-secrets/kfc-secret</code>, they will see this default error page:-</p>



<figure class="wp-block-image aligncenter"><img decoding="async" src="http://myshittycode.files.wordpress.com/2014/04/screen-shot-2014-04-11-at-8-47-53-am.png" alt="" class="wp-image-484"/></figure>



<p>This proves that Spring Security is doing its job. However, the default error page looks rather F.U.G.L.Y. Further, the error page may reveal too much information about the application server. The above error page shows the application runs on Jetty. If I&#8217;m a motherhacker, I would research all the possible vulnerabilities on this particular application server in attempt to hack it.</p>



<p>A better solution is to provide a friendly error page when the user access is denied. This can be done by specifying <code>&lt;security:access-denied-handler/&gt;</code> tag:-</p>


<div class="wp-block-syntaxhighlighter-code "><pre class="brush: xml; highlight: [8]; title: ; notranslate">
&lt;beans ...&gt;
    &lt;!-- Error pages don&#039;t need to be secured --&gt;
    &lt;security:http pattern=&quot;/error/**&quot; security=&quot;none&quot;/&gt;

    &lt;security:http auto-config=&quot;true&quot;&gt;
        &lt;security:form-login ... /&gt;
        &lt;security:logout ... /&gt;
        &lt;security:access-denied-handler error-page=&quot;/error/access-denied&quot;/&gt;
        &lt;security:intercept-url pattern=&quot;/top-secrets/**&quot; access=&quot;ROLE_TOPSECRET&quot;/&gt;
    &lt;/security:http&gt;
	...
&lt;/beans&gt;
</pre></div>


<p>Then, we create a simple error controller that returns the error page:-</p>


<div class="wp-block-syntaxhighlighter-code "><pre class="brush: java; title: ; notranslate">
@Controller
@RequestMapping(value = &quot;/error&quot;)
public class ErrorController {
    @RequestMapping(value = &quot;/access-denied&quot;, method = RequestMethod.GET)
    public String accessDenied() {
        return &quot;error-access-denied&quot;;
    }
}
</pre></div>


<p>Now, the user will see this custom error page:-</p>



<figure class="wp-block-image aligncenter"><img decoding="async" width="721" height="205" src="https://myshittycode.com/wp-content/uploads/2014/04/screen-shot-2014-04-11-at-8-38-16-am-1.png?x45560" alt="" class="wp-image-483" srcset="https://myshittycode.com/wp-content/uploads/2014/04/screen-shot-2014-04-11-at-8-38-16-am-1.png 721w, https://myshittycode.com/wp-content/uploads/2014/04/screen-shot-2014-04-11-at-8-38-16-am-1-300x85.png 300w" sizes="(max-width: 721px) 100vw, 721px" /></figure>



<p>This solution is better than the previous one. However, SiteMesh doesn&#8217;t have the opportunity to decorate this error page before it gets rendered.</p>



<p>To fix this, we can create a simple redirect to allow the request to make a full-round trip to the server so that SiteMesh can decorate the error page:-</p>


<div class="wp-block-syntaxhighlighter-code "><pre class="brush: java; highlight: [4,5,6,7]; title: ; notranslate">
@Controller
@RequestMapping(value = &quot;/error&quot;)
public class ErrorController {
    @RequestMapping(value = &quot;/router&quot;, method = RequestMethod.GET)
    public String errorRouter(@RequestParam(&quot;q&quot;) String resource) {
        return &quot;redirect:/error/&quot; + resource;
    }&lt;/code&gt;
&lt;code&gt;
&lt;/code&gt;
&lt;code&gt;    @RequestMapping(value = &quot;/access-denied&quot;, method = RequestMethod.GET)
    public String accessDenied() {
        return &quot;error-access-denied&quot;;
    }
}

</pre></div>


<p>Then, we tweak the Spring Security to use the error router URI:-</p>


<div class="wp-block-syntaxhighlighter-code "><pre class="brush: xml; highlight: [8]; title: ; notranslate">
&lt;beans ...&gt;
    &lt;!-- Error pages don&#039;t need to be secured --&gt;
    &lt;security:http pattern=&quot;/error/**&quot; security=&quot;none&quot;/&gt;&lt;/code&gt;
&lt;code&gt;

    &lt;security:http auto-config=&quot;true&quot;&gt;
        &lt;security:form-login ... /&gt;
        &lt;security:logout ... /&gt;
        &lt;security:access-denied-handler error-page=&quot;/error/router?q=access-denied&quot;/&gt;
        &lt;security:intercept-url pattern=&quot;/top-secrets/**&quot; access=&quot;ROLE_TOPSECRET&quot;/&gt;
    &lt;/security:http&gt;
&lt;/code&gt;
&lt;code&gt;		...
&lt;/beans&gt;

</pre></div>


<p>Now, the user will see this nice beautiful error page:-</p>



<figure class="wp-block-image aligncenter"><img decoding="async" width="845" height="290" src="https://myshittycode.com/wp-content/uploads/2014/04/screen_shot_2014-04-11_at_8_36_30_am-1.png?x45560" alt="" class="wp-image-485" srcset="https://myshittycode.com/wp-content/uploads/2014/04/screen_shot_2014-04-11_at_8_36_30_am-1.png 845w, https://myshittycode.com/wp-content/uploads/2014/04/screen_shot_2014-04-11_at_8_36_30_am-1-300x103.png 300w, https://myshittycode.com/wp-content/uploads/2014/04/screen_shot_2014-04-11_at_8_36_30_am-1-768x264.png 768w" sizes="(max-width: 845px) 100vw, 845px" /></figure>
<p>The post <a rel="nofollow" href="https://myshittycode.com/2014/04/11/spring-security-handling-403-error-page/">Spring Security: Handling 403 Error Page</a> appeared first on <a rel="nofollow" href="https://myshittycode.com">My Shitty Code</a>.</p>
]]></content:encoded>
					
					<wfw:commentRss>https://myshittycode.com/2014/04/11/spring-security-handling-403-error-page/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
		<post-id xmlns="com-wordpress:feed-additions:1">480</post-id>	</item>
	</channel>
</rss>

<!--
Performance optimized by W3 Total Cache. Learn more: https://www.boldgrid.com/w3-total-cache/?utm_source=w3tc&utm_medium=footer_comment&utm_campaign=free_plugin

Page Caching using Disk: Enhanced 
Lazy Loading (feed)
Database Caching using Disk

Served from: myshittycode.com @ 2026-02-21 06:46:11 by W3 Total Cache
-->