通过REST在Spring MVC中进行身份验证

时间:2012-11-28 16:14:17

标签: spring rest authentication spring-mvc spring-security

我一直在寻找通过REST控制器(URL params)对用户进行身份验证的方法。 最接近这一点的是:

@Controller
@RequestMapping(value="/api/user")
public class UserController extends BaseJSONController{

    static Logger sLogger = Logger.getLogger(UserController.class);

    @RequestMapping(value = "/login", method = RequestMethod.POST)
    public @ResponseBody String login(@RequestParam(value="username") String user, @RequestParam(value="password") String pass) throws JSONException {
        Authentication userAuth = new UsernamePasswordAuthenticationToken(user, pass);
        MyCellebriteAuthenticationProvider MCAP = new MyCellebriteAuthenticationProvider();

        if (MCAP.authenticate(userAuth) == null){
            response.put("isOk", false);
        }
        else{
            SecurityContextHolder.getContext().setAuthentication(userAuth);
            response.put("isOk", true);
            response.put("token", "1234");
        }
        return response.toString();
    }

}

但是,这不会创建cookie。 是否有任何想法或更好的方法来实现我想要实现的目标?

1 个答案:

答案 0 :(得分:3)

首先,您不应手动执行此操作:

SecurityContextHolder.getContext().setAuthentication(userAuth)

最好使用负责身份验证的特殊过滤器,设置安全上下文并在处理请求后清除它。默认情况下,Spring Security使用线程本地存储安全上下文,因此如果在客户端调用后未将其删除,则另一个客户端可以自动以其他人身份登录。请记住,服务器线程经常被不同客户端的不同请求重用。

其次,我建议对RESTful Web服务使用基本身份验证或摘要身份验证。两者都得到Spring Security的支持。更多文档http://static.springsource.org/spring-security/site/docs/3.1.x/reference/basic.html

最后,请记住,RESTful Web服务应该是无状态的。

还要记住Spring Security文档是你的朋友。 : - )