如何在Grails中使用spring security rest插件进行Authenticated

时间:2015-01-29 16:49:12

标签: rest grails spring-security grails-plugin grails-2.4

我正在使用Grails版本2.4.3。我正在创建一个支持RESTful API的应用程序。由于应该对这些API的访问进行身份验证,因此我尝试了Spring Security REST插件。我检查了this example并且我能理解的是,/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客户端但不起作用。 然后我尝试使用有效的JSON数据向/api/login/发送AJAX请求 ,但在控制台上获得401。这里有什么问题?这是正确的登录终点吗?如何使用JQuery进行身份验证?

2 个答案:

答案 0 :(得分: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;
    }

答案 1 :(得分: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");
        }
    })  });