当前位置: 首页 > 知识库问答 >
问题:

Spring Security性:测试和理解REST身份验证

宋明亮
2023-03-14
    null

有没有人能用这段代码告诉我,我应该通过REST发送哪些数据来进行身份验证并访问后续的@Security服务。任何帮助都会很好。多谢.

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() {
    }
}

我试着使用下面的Curl,但每次都得到302。我想要的是获得cookie,以及不同的状态取决于身份验证是否成功。

akshay@akshay-desktop:~/Downloads/idea136/bin$ curl -i -X POST -d j_username=email@email.de -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 j_username=email@email.de -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

如果还需要什么,请告诉我。多谢.

共有1个答案

金骞尧
2023-03-14

在获得302并保存cookie后尝试此Curl命令

curl-i--header“accept:application/json”-x GET-b/home/cookies.txt http://localhost:8080/

希望这有帮助

 类似资料:
  • 问题内容: 我正在开发Flask应用程序,并使用Flask-security进行用户身份验证(反过来又在下面使用Flask-login)。 我有一条需要身份验证的路由。我正在尝试编写一个单元测试,该测试对经过身份验证的用户返回适当的响应。 在单元测试中,我正在创建一个用户并以该用户身份登录,如下所示: 在测试内返回正确的用户。但是,请求的视图始终返回的。 所述路线定义为: 我可以肯定我只是不完全了

  • 问题内容: 这是我的情况: 一个Web应用程序对许多应用程序执行某种SSO 登录的用户,而不是单击链接,该应用就会向正确的应用发布包含用户信息(名称,pwd [无用],角色)的帖子 我正在其中一个应用程序上实现SpringSecurity以从其功能中受益(会话中的权限,其类提供的方法等) 因此,我需要开发一个 自定义过滤器 -我猜想-能够从请求中检索用户信息,通过自定义 DetailsUserSe

  • 问题内容: 背景: 我正在为REST Web服务设计身份验证方案。这并不是“真正”需要安全的(它更多是一个个人项目),但我想使其与练习/学习经验一样安全。我不想使用SSL,因为我不想麻烦,而在大多数情况下,它不需要设置它。 要解决这个问题: S3和OAuth都依赖于对请求URL以及一些选定的标头进行签名。他们都没有在POST或PUT请求的请求主体上签名。这难道不容易受到中间人攻击,这种中间人攻击会

  • 我有一个REST服务,它依赖于外部系统来验证令牌,但需要自己进行授权(使用like@Secured进行API级访问)。 要求: UI使用外部系统生成令牌 一种可能的解决方案是使用过滤器: > UI使用外部系统生成令牌 UI使用令牌对我的服务进行REST调用 我的服务有一个过滤器,它使用令牌调用外部系统 有效令牌的外部系统发回用户详细信息 我对成功呼叫集的服务与SecurityContextHold

  • 我有一个这样的应用程序工作流程 (A) 用户代理(浏览器) 假设应用服务器(B)是一个SAML服务提供者,user@domain使用Web浏览器SSO配置文件从浏览器(A)到应用服务器(B)进行身份验证。 在(B)上运行的应用程序如何向user@domain.com的REST服务(C)进行身份验证?(假设B和C都是同一IdP上的SAML SP。) 如果浏览器只是对B和C进行AJAX调用,那么就很简