用Apache Shiro保护REST API

12

我正在尝试将Shiro集成到我的Spring MVC应用程序中。 认证由LDAP服务器支持,我能够成功地对LDAP服务器进行身份验证并获取cookie。

我无法执行的是在随后的请求中使用此cookie并获得结果。尝试使用cookie会将我重定向到需要重新进行身份验证的HTTP 302。例如: 使用标头Cookie:JSESSIONID = abcd在(rest/assets/list)上发送GET请求会重定向到(rest/login

这是保护API的正确策略吗? 该API由AngularJS应用程序使用,并且在添加CRUD功能之前,我希望启用基于用户组的身份验证。

任何指针都将非常有用。

源代码如下:

applicationContext.xml文件如下:

 <beans xmlns="http://www.springframework.org/schema/beans"
   xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
   xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">


<bean id="cacheManager" class="org.apache.shiro.cache.ehcache.EhCacheManager"/>

<bean id="lifecycleBeanPostProcessor" class="org.apache.shiro.spring.LifecycleBeanPostProcessor"/>

<bean class="org.springframework.aop.framework.autoproxy.DefaultAdvisorAutoProxyCreator" depends-on="lifecycleBeanPostProcessor"/>

<bean class="org.apache.shiro.spring.security.interceptor.AuthorizationAttributeSourceAdvisor">
    <property name="securityManager" ref="securityManager"/>
</bean>

<bean id="ldapRealm" class="com.directv.nmsupport.security.LDAPRealm">
    <property name="contextFactory" ref="ldapContextFactory" />
    <property name="userDnTemplate" value="uid={0},ou=DirecTV,ou=People,dc=swengdtv,dc=net" />
</bean>

<bean id="ldapContextFactory" class="org.apache.shiro.realm.ldap.JndiLdapContextFactory">
    <property name="url" value="ldap://teon:389"/>
</bean>

<bean id="securityManager" class="org.apache.shiro.web.mgt.DefaultWebSecurityManager">
    <property name="realm" ref="ldapRealm"/>
    <property name="cacheManager" ref="cacheManager"/>
    <property name="sessionManager" ref="sessionManager" />
</bean>

<bean id="sessionManager" class="org.apache.shiro.web.session.mgt.DefaultWebSessionManager">
    <property name="sessionIdCookieEnabled" value="true" />
</bean>

<bean id="shiroFilter" class="org.apache.shiro.spring.web.ShiroFilterFactoryBean">
    <property name="securityManager" ref="securityManager"/>
    <property name="loginUrl" value="/rest/login"/>
    <property name="filterChainDefinitions">
        <value>
            /rest/login = anon
            /rest/** = user
        </value>
    </property>
</bean>
</beans>

LDAPRealm.java 代码如下:

public class LDAPRealm extends JndiLdapRealm {

@Override
protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
    String username = (String) getAvailablePrincipal(principals);
    return super.doGetAuthorizationInfo(principals);    //To change body of overridden methods use File | Settings | File Templates.
}

@Override
protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
    return super.doGetAuthenticationInfo(token);    //To change body of overridden methods use File | Settings | File Templates.
}

}

LoginController.java是什么?

@Controller
public class LoginController {

@RequestMapping(value = "/login", method = RequestMethod.POST)
public void login(@RequestBody UserCredentials user) {
    UsernamePasswordToken token = new UsernamePasswordToken(user.getUsername(), user.getPassword());
    token.setRememberMe(true);
    SecurityUtils.getSecurityManager().authenticate(token);
    Subject subject = SecurityUtils.getSubject();
    subject.getSession(true);
}

@RequestMapping(value="/logout")
public void logout() {
    Subject subject = SecurityUtils.getSubject();
    SecurityUtils.getSecurityManager().logout(subject);
}

}

Apache Shiro 的日志记录是:

17:47:54.428 ["http-bio-8080"-exec-7] DEBUG o.a.shiro.realm.ldap.JndiLdapRealm - Authenticating user 'afulara' through LDAP
17:47:54.428 ["http-bio-8080"-exec-7] DEBUG o.a.s.r.ldap.JndiLdapContextFactory - Initializing LDAP context using URL [ldap://teon:389] and principal [uid=afulara,ou=DirecTV,ou=People,dc=swengdtv,dc=net] with pooling disabled
17:47:54.431 ["http-bio-8080"-exec-7] DEBUG o.a.shiro.realm.AuthenticatingRealm - Looked up AuthenticationInfo [afulara] from doGetAuthenticationInfo
17:47:54.431 ["http-bio-8080"-exec-7] DEBUG o.a.shiro.realm.AuthenticatingRealm - AuthenticationInfo caching is disabled for info [afulara].  Submitted token: [org.apache.shiro.authc.UsernamePasswordToken - afulara, rememberMe=true].
17:47:54.431 ["http-bio-8080"-exec-7] DEBUG o.a.s.authc.AbstractAuthenticator - Authentication successful for token [org.apache.shiro.authc.UsernamePasswordToken - afulara, rememberMe=true].  Returned account [afulara]
17:48:20.927 ["http-bio-8080"-exec-9] DEBUG o.a.shiro.web.servlet.SimpleCookie - Found 'JSESSIONID' cookie value [02b41ee8-e9e3-43e5-8ee3-aae72322fede]
17:48:24.204 ["http-bio-8080"-exec-10] DEBUG o.a.shiro.web.servlet.SimpleCookie - Found 'JSESSIONID' cookie value [02b41ee8-e9e3-43e5-8ee3-aae72322fede]
17:48:24.210 ["http-bio-8080"-exec-10] WARN  o.s.web.servlet.PageNotFound - Request method 'GET' not supported

1
跟进一下。我从未让它正常工作,转而使用了Spring Security,并发现它得到了更多社区和谷歌搜索的支持,并已完成此活动。 - Adil F
1
然后使用“回答自己的问题”功能。这样人们就可以快速知道您的问题已经解决了。 - dnang
7
我认为这并不是正确的策略。根据REST原则,您不应该与客户端创建会话。更好的保护REST API的方式是基本身份验证和OAuth。 - vincenzo iafelice
2个回答

3
REST的理念是无状态的,因此,如果您与客户端创建会话,则会违反RESTful API的原则。我建议使用Spring Security,您可以在此处找到一个简单的示例:http://spring.io/guides/gs/securing-web/。这将花费您大约5-10分钟,然后您可以在项目中使用它。
此外,还有一个连接到LDAP系统的简单指南:http://spring.io/guides/gs/authenticating-ldap/ 更新:看到您在问题中的评论,我建议您使用自己得出的结果来回答您的问题。

0

由于有人要求我将我的答案作为单独的答案发布,因此在这里发布。

我没有使用Apache Shiro。

PS:并不是说Apache Shiro不好。只是我发现Spring Security更容易满足我的特定需求。你的情况可能会有所不同。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接