3

我正在使用 Grails 版本 2.4.3 。我正在创建一个支持 RESTful API 的应用程序。由于应该对这些 API 的访问进行身份验证,因此我尝试了 Spring Security REST 插件。我查看了这个示例,我能理解的是,/api/login控制器是接收 JSON 格式的用户凭据的身份验证点,并且在成功身份验证后它提供访问令牌作为响应。我尝试使用POSTMAN Rest Client发送/api/login/带有有效 JSON 数据的 POST 请求。但它给了我以下错误。

401 Unauthorized , Similar to 403 Forbidden, but specifically for use when authentication is possible but has failed or not yet been provided. The response must include a WWW-Authenticate header field containing a challenge applicable to the requested resource.

我也尝试使用 IntellijIDEA 的 REST 客户端,但不起作用。然后我尝试/api/login/使用有效的 JSON 数据发送 AJAX 请求,但在控制台上得到 401。这里有什么问题?这是正确的登录端点吗?如何使用 JQuery 进行身份验证?

4

2 回答 2

0

您可以尝试使用此代码进行身份验证,我在请求标头中发送用户 ID 和密码,您可以随意尝试:- 注入以下服务:-

def springSecurityService
def authenticationManager

并使用以下代码

def login = {
            final String authorization = request.getHeader("Authorization");
            if (authorization != null && authorization.startsWith("Basic")) {
                boolean authResult = authenticateUser(authorization)
                if (authResult) {
                    render response.status
                } else {
                    render authFailed(response)
                }

            } else {
                render authFailed(response)
            }
        }
   protected boolean authenticateUser(String authorization) {
        // Authorization: Basic base64credentials
        def base64Credentials = authorization.substring("Basic".length()).trim();
        byte[] credentials = base64Credentials.decodeBase64()
        String actualCredential = new String(credentials)
        // credentials format like username:password
        final String[] values = actualCredential.split(":", 2);
        UsernamePasswordAuthenticationToken authRequest = new UsernamePasswordAuthenticationToken(values[0], values[1]);

        try {
            def authentication = authenticationManager.authenticate(authRequest);
            def securityContext = SecurityContextHolder.getContext();
            securityContext.setAuthentication(authentication);
            def session = request.session;
            session.setAttribute("SPRING_SECURITY_CONTEXT", securityContext);
        }
        catch (BadCredentialsException exception) {
            return false

        }
        return true

    }

    protected HttpServletResponse authFailedResponse(HttpServletResponse response) {
        response.setStatus(401)
        response.setHeader("WWW-Authenticate", "Basic realm=\"nmrs_m7VKmomQ2YM3:\"")
        return response;
    }
于 2015-01-29T18:18:13.737 回答
0

试试这个

$.ajax({
        url: " http://localhost:8080/AppName/api/login",
        type: "POST",
        crossDomain: true,
        data: JSON.stringify({"username":"yourusername" , "password":"yourpassword"}),
        contentType:  'application/json; charset=utf-8',
        dataType: "json",
        success: function (response) {
            console.log(response);


        },
        error: function (xhr, status) {
            alert("error");
        }
    })  }); 
于 2015-02-03T18:00:24.777 回答