Spring Security:测试与安全了解REST身份验证 [英] Spring Security : Testing & understanding REST authentication
问题描述
-
我正在使用Spring-MVC,我使用Spring-Security进行
登录/注销和会话管理。它在
普通浏览器中使用时效果很好。我正在尝试为
应用程序集成REST身份验证,我将其命名为回答问题。我做了一些
的修改,这样我就可以在浏览器中使用它,也可以在REST
上使用它。
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.
- 现在,代码运行得很好,但我不知道为什么,而且如果我
想要通过REST验证用户,我如何用这个
代码实现?不幸的是,没有错误要求解决方案。
任何人都可以告诉我这段代码,我应该发送什么数据REST用于身份验证和访问后续的@Secured服务。任何帮助都会很好。非常感谢。
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:
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:
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:
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:
MyLogoutHandler :
public class MyLogoutHandler implements LogoutHandler {
@Override
public void logout(HttpServletRequest request,HttpServletResponse response,Authentication authentication){
}
}
LoginServiceImpl:
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,以及取决于身份验证是否成功的不同状态。
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 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
如果还有其他需要,请告诉我。非常感谢。
If there is anything else required, kindly let me know. Thanks a lot.
推荐答案
获得302并保存cookie后尝试此Curl命令
try this Curl command after getting 302 and saving cookies
curl -i --headerAccept:application / json-X GET -b /home/cookies.txt
http: // localhost:8080 /
curl -i --header "Accept:application/json" -X GET -b /home/cookies.txt http://localhost:8080/
希望这会有所帮助
这篇关于Spring Security:测试与安全了解REST身份验证的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!