mercredi 22 avril 2015

Spring MVC : Controller redirecting to JSP page instead of giving Object via REST

I am working on a Spring-MVC application in which I am trying to access secured services over a QT application. I am successfully able to login and gain access to secured resources, but when I call a controller method which is designed to give back an array of the Objects requested, it sends back the entire JSP page via REST. Why is this happening and how can I remedy this situation??

Controller code :

@PreAuthorize("hasRole('ROLE_USER')")
    @RequestMapping(value = "/canvas/jsonlist", method = RequestMethod.GET)
    public @ResponseBody Canvas[] listJsonCanvas() {
        System.out.println("From rest authentication the username is "+this.personService.returnLoggedInUsersEmail());
        List<Canvas> canvasList = this.canvasService.listCanvasPerson();
        return canvasList.toArray(new Canvas[canvasList.size()]);
    }

Output is JSP page, so I am not pasting it here.

Security-application-context.xml :

 <import resource="servlet-context.xml" />

    <!-- Global Security settings -->
    <security:global-method-security pre-post-annotations="enabled" />
    <security:http pattern="/resources/**" security="none"/>

    <security:http create-session="ifRequired" use-expressions="true" auto-config="false" disable-url-rewriting="true">
        <security:form-login login-page="/login" login-processing-url="/j_spring_security_check" default-target-url="/canvas/list" always-use-default-target="false" authentication-failure-url="/denied.jsp" />
        <security:remember-me key="_spring_security_remember_me" user-service-ref="userDetailsService" token-validity-seconds="1209600" data-source-ref="dataSource"/>
        <security:logout delete-cookies="JSESSIONID" invalidate-session="true" logout-url="/j_spring_security_logout"/>
<!--    <security:intercept-url pattern="/**" requires-channel="https"/> -->
    <security:port-mappings>
        <security:port-mapping http="80" https="443"/>
    </security:port-mappings>
    <security:logout logout-url="/logout" logout-success-url="/" success-handler-ref="myLogoutHandler"/>

     <security:session-management session-fixation-protection="migrateSession">
         <security:concurrency-control session-registry-ref="sessionRegistry" max-sessions="1" expired-url="/login"/>
     </security:session-management>

    </security:http>

    <bean id="sessionRegistry" class="org.springframework.security.core.session.SessionRegistryImpl" />

    <!-- Rest authentication, don't edit, delete, add-->
    <bean id="springSecurityFilterChain" class="org.springframework.security.web.FilterChainProxy">

    <security:filter-chain-map path-type="ant">
        <security:filter-chain filters="persistencefilter,authenticationfilter" pattern="/login"/>
        <security:filter-chain filters="persistencefilter,logoutfilter" pattern="/logout"/>
        <security:filter-chain pattern="/rest/**" filters="persistencefilter,restfilter" />
    </security:filter-chain-map>
    </bean>

    <bean id="persistencefilter" class="org.springframework.security.web.context.SecurityContextPersistenceFilter"/>

    <bean id="authenticationfilter" class="com.journaldev.spring.utility.AuthenticationFilter">
        <property name="authenticationManager" ref="authenticationManager"/>
        <property name="authenticationSuccessHandler" ref="myAuthSuccessHandler"/>
        <property name="passwordParameter" value="pass"/>
        <property name="usernameParameter" value="user"/>
        <property name="postOnly" value="false"/>
    </bean>

    <bean id="myAuthSuccessHandler" class="com.journaldev.spring.utility.AuthenticationSuccessHandler"/>

    <bean id="myLogoutHandler" class="com.journaldev.spring.utility.MyLogoutHandler"/>

    <bean id="logoutfilter" class="org.springframework.security.web.authentication.logout.LogoutFilter">

        <constructor-arg index="0" value="/"/>
        <constructor-arg index="1">
            <list>
                <bean class="org.springframework.security.web.authentication.logout.SecurityContextLogoutHandler">
                    <property name="invalidateHttpSession" value="true"/>
                    <property name="clearAuthentication" value="true"/>
                </bean>
                <bean id="myLogoutHandler" class="com.journaldev.spring.utility.MyLogoutHandler"/>
            </list>
        </constructor-arg>
    </bean>

    <bean id="httpRequestAccessDecisionManager" class="org.springframework.security.access.vote.AffirmativeBased">
        <property name="allowIfAllAbstainDecisions" value="false"/>
        <property name="decisionVoters">
            <list>
                <ref bean="roleVoter"/>
            </list>
        </property>
    </bean>

    <bean id="roleVoter" class="org.springframework.security.access.vote.RoleVoter"/>

    <bean id="restfilter" class="org.springframework.security.web.access.intercept.FilterSecurityInterceptor">
        <property name="authenticationManager" ref="authenticationManager"/>
        <property name="accessDecisionManager" ref="httpRequestAccessDecisionManager"/>
        <property name="securityMetadataSource">
            <security:filter-invocation-definition-source>
                <security:intercept-url pattern="/rest/**" access="ROLE_USER"/>
            </security:filter-invocation-definition-source>
        </property>
    </bean>
    <!-- Rest authentication ends here-->

    <!-- queries to be run on data -->
    <beans:bean id="rememberMeAuthenticationProvider" class="org.springframework.security.web.authentication.rememberme.PersistentTokenBasedRememberMeServices">
        <beans:property name="key" value="_spring_security_remember_me" />
        <beans:property name="tokenRepository" ref="jdbcTokenRepository"/>
        <beans:property name="userDetailsService" ref="LoginServiceImpl"/>
    </beans:bean>

    <!--Database management for remember-me -->
    <beans:bean id="jdbcTokenRepository"
                class="org.springframework.security.web.authentication.rememberme.JdbcTokenRepositoryImpl">
        <beans:property name="createTableOnStartup" value="false"/>
        <beans:property name="dataSource" ref="dataSource" />
    </beans:bean>

    <!-- Remember me ends here -->
    <security:authentication-manager alias="authenticationManager">
        <security:authentication-provider user-service-ref="LoginServiceImpl">
           <security:password-encoder  ref="encoder"/>
        </security:authentication-provider>
    </security:authentication-manager>

    <beans:bean id="encoder"
                class="org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder">
        <beans:constructor-arg name="strength" value="11" />
    </beans:bean>

    <beans:bean id="daoAuthenticationProvider"
                class="org.springframework.security.authentication.dao.DaoAuthenticationProvider">
                <beans:property name="userDetailsService" ref="LoginServiceImpl"/>
               <beans:property name="passwordEncoder" ref="encoder"/>
    </beans:bean>
</beans>

Debug output :

DEBUG: org.springframework.web.servlet.DispatcherServlet - Rendering view [org.springframework.web.servlet.view.JstlView: name 'login'; URL [/WEB-INF/views/login.jsp]] in DispatcherServlet with name 'appServlet'
DEBUG: org.springframework.security.access.intercept.aopalliance.MethodSecurityInterceptor - Previously Authenticated: org.springframework.security.authentication.UsernamePasswordAuthenticationToken@99f857e1: Principal: org.springframework.security.core.userdetails.User@dde5c0af: Username: email@email.de; Password: [PROTECTED]; Enabled: true; AccountNonExpired: true; credentialsNonExpired: true; AccountNonLocked: true; Granted Authorities: ROLE_USER; Credentials: [PROTECTED]; Authenticated: true; Details: org.springframework.security.web.authentication.WebAuthenticationDetails@957e: RemoteIpAddress: 127.0.0.1; SessionId: null; Granted Authorities: ROLE_USER
DEBUG: org.springframework.web.servlet.view.JstlView - Added model object 'person' of type [com.journaldev.spring.model.Person] to request in view with name 'login'
DEBUG: org.springframework.web.servlet.view.JstlView - Added model object 'org.springframework.validation.BindingResult.person' of type [org.springframework.validation.BeanPropertyBindingResult] to request in view with name 'login'
DEBUG: org.springframework.security.access.vote.AffirmativeBased - Voter: org.springframework.security.access.prepost.PreInvocationAuthorizationAdviceVoter@5d046f29, returned: 1
DEBUG: org.springframework.security.access.intercept.aopalliance.MethodSecurityInterceptor - Authorization successful
DEBUG: org.springframework.security.access.intercept.aopalliance.MethodSecurityInterceptor - RunAsManager did not change Authentication object
DEBUG: org.springframework.web.servlet.view.JstlView - Forwarding to resource [/WEB-INF/views/login.jsp] in InternalResourceView 'login'
From rest authentication the username is email@email.de
DEBUG: org.springframework.web.servlet.DispatcherServlet - Rendering view [org.springframework.web.servlet.view.JstlView: name 'canvas'; URL [/WEB-INF/views/canvas.jsp]] in DispatcherServlet with name 'appServlet'
DEBUG: org.springframework.web.servlet.view.JstlView - Added model object 'canvases' of type [com.journaldev.spring.model.Canvas] to request in view with name 'canvas'
DEBUG: org.springframework.web.servlet.view.JstlView - Added model object 'org.springframework.validation.BindingResult.canvases' of type [org.springframework.validation.BeanPropertyBindingResult] to request in view with name 'canvas'
DEBUG: org.springframework.web.servlet.view.JstlView - Added model object 'mcanvas' of type [com.journaldev.spring.model.GroupCanvas] to request in view with name 'canvas'
DEBUG: org.springframework.web.servlet.view.JstlView - Added model object 'org.springframework.validation.BindingResult.mcanvas' of type [org.springframework.validation.BeanPropertyBindingResult] to request in view with name 'canvas'
DEBUG: org.springframework.web.servlet.view.JstlView - Added model object 'listGroups' of type [java.util.ArrayList] to request in view with name 'canvas'
DEBUG: org.springframework.web.servlet.view.JstlView - Added model object 'username' of type [java.lang.String] to request in view with name 'canvas'
DEBUG: org.springframework.web.servlet.view.JstlView - Added model object 'firstname' of type [java.lang.String] to request in view with name 'canvas'
DEBUG: org.springframework.web.servlet.view.JstlView - Forwarding to resource [/WEB-INF/views/canvas.jsp] in InternalResourceView 'canvas'
DEBUG: org.springframework.web.servlet.DispatcherServlet - Successfully completed request

Incase someone needs the QT code, here it is :

LoginAndAccessSecuresResource :

 QString url_str = "http://localhost:8080/j_spring_security_check";
    QString canvasUrl = "http://localhost:8080/canvas/jsonlist";

QNetworkAccessManager *manager = new QNetworkAccessManager();
    manager->setCookieJar (new QNetworkCookieJar(manager));
    connect (manager,SIGNAL(finished(QNetworkReply*)),this,SLOT(slotRequestFinished(QNetworkReply*)));
    QNetworkRequest request;
    request.setUrl (url_str);
    request.setRawHeader("User-Agent", "MyOwnBrowser 1.0");
    QByteArray postData;
    postData.append ("j_username=email@email.de");
    postData.append ("&j_password=password");
    manager->post (request,postData);
    request.setUrl (canvasUrl);
    request.setRawHeader("User-Agent", "MyOwnBrowser 1.0");
    manager->get (request);

If there is any more information required, kindly let me know, more than happy to provide it. Thanks a lot. :-)

Aucun commentaire:

Enregistrer un commentaire