簡體   English   中英

Spring安全性:以編程方式登錄

[英]Spring security: programmatically log in

我們正在開發一個帶有jQuery mobile的移動應用程序,並且想要在spring 3.1.x后端以編程方式對用戶進行身份驗證,並使用spring security進行正確設置。

POST請求被發送到包含用戶名和密碼的后端(使用jQuery的$ .post),然后服務器驗證憑據是否正確並登錄用戶。

服務器似乎在SecurityContext中正確設置了身份驗證,但是當我們向服務器發出第二個請求($ .get到需要登錄的頁面)時,安全細節似乎不會被記住,並且匿名令牌似乎是在上下文中。

這是控制器中處理登錄的方法(為簡潔起見,刪除了密碼檢查):

@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安全文檔和其他在線資源工作。 關於什么可能出錯的任何想法?

我對你的配置感到困惑。 您已經實現了自己的登錄控制器,但您似乎正在使用Spring Security的表單登錄。 我最近使用Spring Security + jquery實現了ajax登錄。 我只是實現了自己的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"/>

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM