java - Spring 安全 : programmatically log in

标签 java spring mobile spring-security

我们正在使用 jQuery Mobile 开发移动应用程序,并希望在正确设置了 Spring Security 的 Spring 3.1.x 后端上以编程方式对用户进行身份验证。

将包含用户名和密码的 POST 请求发送到后端(使用 jQuery 的 $.post),然后服务器验证凭据是否正确并登录用户。

服务器似乎在 SecurityContext 中正确设置了身份验证,但是当我们向服务器发出第二个请求($.get 到需要登录的页面)时,似乎没有记住安全细节和匿名 token 似乎在上下文中。

这是 Controller 中处理登录的方法(为简洁起见删除了密码检查):

@RequestMapping(value = "/login", method = RequestMethod.POST, produces = "application/json")
@ResponseBody
public Map<String, String> login(@RequestParam String username, @RequestParam String password, HttpServletRequest request) {
    Map<String, String> response = new HashMap<String, String>();

    User u = userService.findByAccountName(username);

    if (u != null && u.hasRole("inspector")) {
        UsernamePasswordAuthenticationToken token = new UsernamePasswordAuthenticationToken(username, password);
        try {
            Authentication auth = authenticationManager.authenticate(token);
            SecurityContextHolder.getContext().setAuthentication(auth);

            response.put("status", "true");
            return response;
        } catch (BadCredentialsException ex) {
            response.put("status", "false");
            response.put("error", "Bad credentials");
            return response;
        }
    } else {
        response.put("status", "false");
        response.put("error", "Invalid role");
        return response;
    }
}

这是我们从上下文中获取用户详细信息的另一种方法:

@RequestMapping(value = "/project", method = RequestMethod.GET)
@ResponseBody
public String getProjects(HttpSession session) {

    Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
    User u = userService.findByAccountName(((UserDetails) authentication.getPrincipal()).getUsername());
...

Spring 安全配置:

<global-method-security pre-post-annotations="enabled"/>
<http use-expressions="true" auto-config="true">

    <form-login login-processing-url="/static/j_spring_security_check" login-page="/"
                authentication-failure-url="/?login_error=t"/>

    ...
    <intercept-url pattern="/api/**" access="permitAll"/>
    ...
    <remember-me key="biKey" token-validity-seconds="2419200"/>
    <logout logout-url="/logout"/>
</http>

<authentication-manager alias="authenticationManager">
    <authentication-provider user-service-ref="udm">
        <password-encoder hash="md5"/>
    </authentication-provider>
</authentication-manager>

这应该根据 spring 安全文档和其他在线资源工作。关于可能出错的任何想法?

最佳答案

我对你的配置感到困惑。您已经实现了自己的登录 Controller ,但您似乎正在使用 Spring Security 的表单登录。我最近用 Spring Security + jquery 实现了 ajax 登录。我没有编写自己的 Controller ,而是简单地实现了自己的 AuthenticationSuccessHandler 和 AuthenticationFailureHandler 来返回我需要的 json 响应。只需扩展 SimpleUrlAuthenticationSuccessHandler 和 SimpleUrlAuthenticationFailureHandler 覆盖每个类中的 onAuthenticationSuccess 和 onAuthenticationFailure 方法,就像....一样简单。

public void onAuthenticationSuccess(HttpServletRequest request,
        HttpServletResponse response, Authentication authentication)
        throws IOException, ServletException {
    response.getWriter().println("{\"success\": true}");
}

public void onAuthenticationFailure(HttpServletRequest request,
        HttpServletResponse response, AuthenticationException exception)
        throws IOException, ServletException {
    response.getWriter().println("{\"success\": false}");
}

然后你可以配置 form-login 元素,比如...

<form-login login-processing-url="/static/j_spring_security_check" login-page="/"
            authentication-success-handler-ref="ajaxAuthenticationSuccessHandler"
            authentication-failure-handler-ref="ajaxAuthenticationFailureHandler"
            authentication-failure-url="/?login_error=t"/>

关于java - Spring 安全 : programmatically log in,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10811623/

相关文章:

java - CORBA(orbd)联网配置?

java - Java 中的 HTTP 响应代码

java - dlmread 为大型文本文件返回单列

java - 如何正确使用 div 标签作为 jspx 文件中的根元素?

java - Hibernate:如何强制 Hibernate 设置集合类型?

.htaccess - 带有 .htaccess 的移动重定向,用于 www.example.com 或 example.com

spring - 从 Spring Web 应用程序中检索 servlet 上下文路径

java - 配置数据源失败

html - 如何定位小于特定屏幕尺寸的设备

ios - 移动应用程序与网络应用程序 - Apple 不再接受网络应用程序?