How to Add Channel Security in Spring

By Arvind Rai, November 26, 2019
Spring Security provides the feature to secure the URL patterns. For any URL pattern if we want to allow only HTTPS access, we have to do a small configuration in our spring security configuration. Any URL can be accessed via HTTP or HTTPS or by both. We configure them as following.

Use requires-channel Attribute in <intercept-url>

The requires-channel is the attribute of <intercept-url> tag. It can accept three values https, http and any. Find the sample declarations.
For https
<intercept-url pattern="/login" access="ROLE_USER" requires-channel="https" /> 
For http
<intercept-url pattern="/login" access="ROLE_USER" requires-channel="http" /> 
For any
<intercept-url pattern="/login" access="ROLE_USER" requires-channel="any" /> 
We can have more than one configuration in an application.
<http auto-config="true">
     <intercept-url pattern="/secure/**" access="ROLE_USER" requires-channel="https" />
     <intercept-url pattern="/login/**" access="ROLE_USER" requires-channel="http" />
     <intercept-url pattern="/**" access="ROLE_USER" requires-channel="any" />
</http> 
In the above code snippet the URL pattern /secure/** will be accessed via HTTPS. If we try to access by HTTP, then URL will automatically be redirected to HTTPS. Now find the complete example. In our example we have secured login URL by HTTPS.
security-config.xml
   <http auto-config="true">
		<intercept-url pattern="/login" access="ROLE_USER" requires-channel="https" />
		<logout logout-success-url="/login" />
	</http>
	<authentication-manager>
      <authentication-provider>
	  <password-encoder hash="sha"/>
	  <user-service>
	    <user name="concretepage" password="0733824cc1549ce36139e8c790a9344d1e385cd2" authorities="ROLE_USER" />
	  </user-service>
      </authentication-provider>
   </authentication-manager> 
To run the example, enable the HTTPS in your web server. If you access the URL as http://localhost:8080/SpringSecurity/login then it will be redirected to https://localhost:8443/SpringSecurity/login

Download Complete Source Code

POSTED BY
ARVIND RAI
ARVIND RAI
LEARN MORE








©2024 concretepage.com | Privacy Policy | Contact Us