【问题标题】:How to get Authenticated with spring security rest plugin in Grails如何在 Grails 中使用 spring security rest 插件进行身份验证
【发布时间】:2015-03-28 23:56:39
【问题描述】:

我正在使用 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 进行身份验证?

【问题讨论】:

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


    【解决方案1】:

    试试这个

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

    【讨论】:

    • 要使用 POSTMAN 发送 JSON,请选择 raw 选项卡 -> 选择 JSON 并将您的 json 数据粘贴到文本区域
    • 我遇到了类似的问题。我的要求是否正确? POST /GhumVer3/api/login HTTP/1.1 主机:localhost:8080 内容类型:application/json 缓存控制:无缓存 Postman-Token:02c8faa5-d1a9-9192-b26a-cd98186551f6 {"username":"test" , "密码":"test123"}
    • 您尝试了什么以及如何尝试?请解释..或添加一些代码
    【解决方案2】:

    您可以尝试使用此代码进行身份验证,我在请求标头中发送用户 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;
        }
    

    【讨论】:

    • 谢谢.. 但是我必须在哪里使用此代码? /api/login 是插件创建的动态控制器吗?你能解释一下我如何使用这个代码吗?
    • 同样在同一个例子中,当我尝试使用 php curl 时,它工作正常,我得到了预期的响应。那么 JQuery 和 REST 客户端请求有什么问题?跨度>
    • @Jrd 您可以在方法中的控制器中使用它。
    猜你喜欢
    • 2015-07-30
    • 2014-09-06
    • 2014-07-03
    • 2013-11-13
    • 2015-03-13
    • 2019-05-29
    • 2013-12-16
    • 2011-11-20
    • 2012-11-27
    相关资源
    最近更新 更多