有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

JavaSpring安全性:测试和理解REST身份验证

  • 我正在从事SpringMVC的工作,其中我将SpringSecurity用于 登录/注销和会话管理。它用在汽车上效果很好 普通浏览器。我正在尝试为应用程序集成REST身份验证 我向Answer on SO推荐的申请。我做了一些 修改后,我可以在浏览器中使用它,也可以在REST上使用它 还有

    • 现在,代码运行得很好,但我不知道为什么,而且如果 想要通过REST对用户进行身份验证,我该如何实现 密码不幸的是,并没有需要解决的错误

    有人能告诉我,使用此代码,我应该通过REST发送哪些数据以进行身份验证并访问后续的@Secured服务吗<任何帮助都会很好。非常感谢

安全应用程序上下文。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

如果还需要什么,请告诉我。非常感谢


共 (3) 个答案

  1. # 1 楼答案

    @我们是博格?您是否收到REST URL的http 401质询? 在浏览器上尝试url,并验证是否看到弹出窗口询问登录id和密码

    如果使用java客户机进行测试,可以在客户机代码中设置基本身份验证头,如下所示

    CredentialsProvider provider = new BasicCredentialsProvider();
    UsernamePasswordCredentials credentials = new     UsernamePasswordCredentials("user1", "user1Pass");
    provider.setCredentials(AuthScope.ANY, credentials);
    HttpClient client = HttpClientBuilder.create().setDefaultCredentialsProvider(provider).build();
    
    HttpResponse response = client.execute(new HttpGet(URL_SECURED_BY_BASIC_AUTHENTICATION));
    int statusCode = response.getStatusLine().getStatusCode();
    assertThat(statusCode, equalTo(HttpStatus.SC_OK));
    
  2. # 2 楼答案

    您可以使用基于表单的登录来使用浏览器登录,使用http基本身份验证来登录REST端点。对于xml配置,分别是和

    同样的Spring documentation

  3. # 3 楼答案

    获取302并保存cookies后,请尝试此Curl命令

    curl-i标题“Accept:application/json”-X GET-b/home/cookies。txt http://localhost:8080/

    希望这有帮助