3

I'm using Grails version 2.4.3 . I am creating an application that supports RESTful APIs. Since access to these APIs should be authenticated , I tried out the Spring Security REST plugin. I checked out 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. But it gives me the following error.

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.

I also tried using IntellijIDEA's REST Client but doesn't work. Then i tried by sending AJAX Request to /api/login/ with valid JSON data , but getting 401 on console. What is the problem here? Is this the correct login end point? How can i get authenticated using JQuery?

2 Answers2

0

You can try this code for authentication,I am sending user id and password in request header you can try as you wish :- inject following services:-

def springSecurityService
def authenticationManager

and use following code

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;
    }
praveen_programmer
  • 1,072
  • 11
  • 25
  • Thanks.. But where i have to use this code? Is `/api/login` a dynamic controller created by the plugin? Can you please explain how i could use this code? –  Jan 29 '15 at 19:15
  • Also in the same example , when i tried usin [php curl](http://www.lornajane.net/posts/2011/posting-json-data-with-php-curl) , it is working fine and I'm getting the expected response.. Then what's wrong with the JQuery , and REST client requests? –  Jan 29 '15 at 19:38
  • @Jrd You can use it in your controller inside your method. – praveen_programmer Jan 30 '15 at 05:01
0

Try this

$.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");
        }
    })  }); 
Sarath Kn
  • 2,680
  • 19
  • 24
  • 2
    To sent JSON using POSTMAN , choose the `raw` tab -> select JSON and paste your json data in the textarea – Sarath Kn Feb 03 '15 at 18:04
  • 1
    i am gettin similar issues..does my request is correct? POST /GhumVer3/api/login HTTP/1.1 Host: localhost:8080 Content-Type: application/json Cache-Control: no-cache Postman-Token: 02c8faa5-d1a9-9192-b26a-cd98186551f6 {"username":"test" , "password":"test123"} – Vish Mar 11 '15 at 07:35
  • What did you try and how? Please explain.. or add some code – Sarath Kn Mar 12 '15 at 12:58
  • hey i have added code here :https://github.com/alvarosanchez/grails-spring-security-rest/issues/181#issuecomment-78252753 – Vish Mar 13 '15 at 05:11