Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
172 views
in Technique[技术] by (71.8m points)

java - Spring Security : Testing & understanding REST authentication

  • I am working on Spring-MVC in which I am using Spring-Security for login/logout and session management. It works just fine when used in normal browsers. I am trying to integrate REST authentication for the application, for which I refereed to Answer on SO . I made some modifications so that I can use it in browser also and over REST also.

    • Now, The code runs just fine, but I don't know why, and moreover if I want to authenticate an user over REST, how do I achieve with this code? Unfortunately there are no errors to ask solution for.

    Can anyone tell me with this code, what data should I send over REST for authentication and access subsequent @Secured services. Any help would be nice. Thanks a lot.

Security-application-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" 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="8080" https="8443"/>
</security:port-mappings>
<security:logout logout-url="/logout" logout-success-url="/" success-handler-ref="myLogoutHandler"/>
</security:http>

<!-- 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"/>
            <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>

AuthenticationFilter :

public class AuthenticationFilter extends UsernamePasswordAuthenticationFilter{

    @Override
    protected boolean requiresAuthentication(HttpServletRequest request,HttpServletResponse response){
        return (StringUtils.hasText(obtainUsername(request)) && StringUtils.hasText(obtainPassword(request)));
    }

    @Override
    protected void successfulAuthentication(HttpServletRequest request,HttpServletResponse response,
                                            FilterChain chain, Authentication authResult) throws IOException, ServletException{
        System.out.println("Successfule authenticaiton");
        super.successfulAuthentication(request,response,chain,authResult);
        chain.doFilter(request,response);

    }
}

AuthenticationSuccessHandler :

public class AuthenticationSuccessHandler extends SimpleUrlAuthenticationSuccessHandler{

    @PostConstruct
    public void afterPropertiesSet(){
        setRedirectStrategy(new NoRedirectStrategy());
    }

    protected class NoRedirectStrategy implements RedirectStrategy{

        @Override
        public void sendRedirect(HttpServletRequest request, HttpServletResponse response, String url) throws IOException {
            // Checking redirection issues
        }
    }
}

MyLogoutHandler :

public class MyLogoutHandler implements LogoutHandler {

     @Override
    public void logout(HttpServletRequest request,HttpServletResponse response,Authentication authentication){

     }
}

LoginServiceImpl :

@Transactional
@Service("userDetailsService")
public class LoginServiceImpl implements UserDetailsService{

    @Autowired private PersonDAO personDAO;
    @Autowired private Assembler assembler;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException,DataAccessException {
        Person person = personDAO.findPersonByUsername(username.toLowerCase());
            if(person == null) { throw new UsernameNotFoundException("Wrong username or password");} 
        return assembler.buildUserFromUserEntity(person);
    }

    public LoginServiceImpl() {
    }
}

I tried using Curl as below, but I get 302 everytime. What I would like is to get the cookie, and different status depending upon if authentication was successful or not.

akshay@akshay-desktop:~/Downloads/idea136/bin$ curl -i -X POST -d [email protected] -d j_password=password -c /home/cookies.txt http://localhost:8080/j_spring_security_check 
HTTP/1.1 302 Found
Server: Apache-Coyote/1.1
Set-Cookie: JSESSIONID=7F7B5B7056E75C138E550C1B900FAB4B; Path=/; HttpOnly
Location: http://localhost:8080/canvas/list
Content-Length: 0
Date: Thu, 26 Mar 2015 15:33:21 GMT

akshay@akshay-desktop:~/Downloads/idea136/bin$ curl -i -X POST -d [email protected] -d j_password=password -c /home/cookies.txt http://localhost:8080/j_spring_security_check 
HTTP/1.1 302 Found
Server: Apache-Coyote/1.1
Set-Cookie: JSESSIONID=BB6ACF38F20FE962924103DF5F419A55; Path=/; HttpOnly
Location: http://localhost:8080/canvas/list
Content-Length: 0
Date: Thu, 26 Mar 2015 15:34:02 GMT

If there is anything else required, kindly let me know. Thanks a lot.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

try this Curl command after getting 302 and saving cookies

curl -i --header "Accept:application/json" -X GET -b /home/cookies.txt http://localhost:8080/

Hope this helps


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...