Custom message on redirect page when Role based access denied using spring security in Hybris | use of spring security in Hybris

Hello Friends ,
In our project there was requirement that when user has no access to any page then login page should come with custom message like "You have no permission to see page without login So please do login "
We all ready know in Hybris there is out of box spring security which is used to configure to redirect page if visitor has no access to see page but how the your custom message will display on login page for that you need to customize in Hybris.
 
First you should know how out of box redirect is working
open file
hybris\bin\ext-template\yacceleratorstorefront\web\webroot\WEB-INF\config\spring-security-config.xml

See code

<security:http disable-url-rewriting="true" pattern="/checkout/**" use-expressions="true">
        <security:anonymous username="anonymous" granted-authority="ROLE_CUSTOMERGROUPS" />
                                <security:access-denied-handler error-page="/login"/>
</security:http>


so within this page if for URL pattern if user has no role which is define like granted-authority="ROLE_CUSTOMERGROUPS"  then it will redirect to login page by using code

 
<security:access-denied-handler error-page="/login"/>



Now question is
 how to display custom message or any custom logic you want to execute before call your login then you need to use one of spring security property which is override

1. first create a custom class MyAccessDeniedHandler by implementing AccessDeniedHandler (spring security class)

 
public class MyAccessDeniedHandler  implements AccessDeniedHandler
{
}

2. Now override method
 
@Override
                public void handle(HttpServletRequest request, HttpServletResponse response,
                                AccessDeniedException accessDeniedException)
                throws IOException, ServletException {

                                //do some business logic, then redirect to errorPage url
                                response.sendRedirect(errorPage);

                }
              

             
3. After declare your bean in in your security file as

 
<bean id="myAccessDeniedHandler" class="com.yaccelrator.storefront.security.impl.MyAccessDeniedHandler">
</bean>
4.  Replace security handler with below

 
<security:http disable-url-rewriting="true" pattern="/checkout/**" use-expressions="true">
        <security:anonymous username="anonymous" granted-authority="ROLE_CUSTOMERGROUPS" />
                                <security:access-denied-handler ref="myAccessDeniedHandler"/>
</security:http>



Now you can
 customize to handler url

Note:  Spring security class
 AccessDeniedHandler provide to perform some business logics before redirect


No comments:

Post a Comment