How to Add Channel Security in Spring
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>
Therequires-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" />
<intercept-url pattern="/login" access="ROLE_USER" requires-channel="http" />
<intercept-url pattern="/login" access="ROLE_USER" requires-channel="any" />
<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>
/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>