如何使用 Grails 中的 spring security rest 插件进行身份验证

How to get Authenticated with spring security rest plugin in Grails

我使用的是 Grails 2.4.3 版。我正在创建一个支持 RESTful API 的应用程序。由于对这些 API 的访问应该经过身份验证,因此我试用了 Spring Security REST 插件。我查看了 this example and what I could understand is , the /api/login controller is the authentication point which receives the user credentials in JSON format and after successful authentication it provides the acces token as response. I tried sending a POST request to /api/login/ with valid JSON data using the POSTMAN Rest Client。但它给了我以下错误。

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/ 发送 AJAX 请求和有效的 JSON 数据 ,但在控制台上收到 401。这里有什么问题?这是正确的登录端点吗?我如何使用 JQuery 进行身份验证?

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

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;
    }

试试这个

$.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");
        }
    })  });