Having trouble implementing Stormpath form Login/Authentication alongside REST oAuth authentication in the same application

廉价感情. 提交于 2020-01-04 04:03:45

问题


We're using stormpath with Java & also trying to combine form Login with REST API authentication on the same application.

I've setup stormpath servlet plugin as described here https://docs.stormpath.com/java/servlet-plugin/quickstart.html... This works very fine.

Now, on the same application, we have APIs where I've implemented oAuth authentication with stormpath see here http://docs.stormpath.com/guides/api-key-management/

The first request for an access-token works fine by sending Basic Base64(keyId:keySecret) in the request header and grant_type = client_credentials in the body. Access tokens are being returned nicely. However trying to authenticate subsequent requests with the header Bearer <the-obtained-access-token> does not even hit the application before returning the following json error message...

{
    "error": "invalid_client",
    "error_description": "access_token is invalid."
}

This is confusing because I've set breakpoints all over the application and I'm pretty sure that the API request doesn't hit the anywhere within the application before stormpath kicks in and returns this error. And even if stormpath somehow intercepts the request before getting to the REST interface, this message doesn't make any sense to me because i'm certainly making the subsequent API calls with a valid access-token obtained from the first call to get access-token.

I have run out of ideas why this could be happening but i'm suspecting that it may have something to do with stormpath config especially with a combination of form Login/Authentication for web views and oAuth Athentication for REST endpoints. With that said, here's what my stormpath.properties looks like. Hope this could help point at anything I may be doing wrong.

stormpath.application.href=https://api.stormpath.com/v1/applications/[app-id]
stormpath.web.filters.authr=com.app.security.AuthorizationFilter
stormpath.web.request.event.listener = com.app.security.AuthenticationListener

stormpath.web.uris./resources/**=anon
stormpath.web.uris./assets/**=anon
stormpath.web.uris./v1.0/**=anon
stormpath.web.uris./** = authc,authr
stormpath.web.uris./**/**=authc,authr

Help with this would be highly appreciated.


回答1:


The problem might be related to an incorrect request.

Is it possible for you to try this code in your app?:

 private boolean verify(String accessToken) throws OauthAuthenticationException {
     HttpRequest request = createRequestForOauth2AuthenticatedOperation(accessToken);
     AccessTokenResult result = Applications.oauthRequestAuthenticator(application)
        .authenticate(request);
     System.out.println(result.getAccount().getEmail() + " was successfully verified, you can allow your protect operation to continue");
     return true;
 }

 private HttpRequest createRequestForOauth2AuthenticatedOperation(String token) {
     try {
         Map<String, String[]> headers = new LinkedHashMap<String, String[]>();
         headers.put("Accept", new String[]{"application/json"});
         headers.put("Authorization", new String[]{"Bearer " + token});
         HttpRequest request = HttpRequests.method(HttpMethod.GET)
             .headers(headers)
             .build();
         return request;
     } catch (Exception e) {
         e.printStackTrace();
         return null;
     }
 }



回答2:


I've prepared an example that demonstrates oauth token creation as well as authorized access to protected pages using access tokens.

It builds off of the servlet example in the Stormpath SDK. The repo can be found here: https://github.com/stormpath/stormpath-java-oauth-servlet-sample

It demonstrates running a servlet application and having an out-of-band program get and use oauth tokens to access protected resources.

The core of the oauth part is in TokenAuthTest.java:

public class TokenAuthTest {
    public static void main(String[] args) throws Exception {

        String command = System.getProperty("command");

        if (command == null || !("getToken".equals(command) || "getPage".equals(command))) {
            System.err.println("Must supply a command:");
            System.err.println("\t-Dcommand=getToken OR");
            System.err.println("\t-Dcommand=getPage OR");
            System.exit(1);
        }

        if ("getToken".equals(command)) {
            getToken();
        } else {
            getPage();
        }
    }

    private static final String APP_URL = "http://localhost:8080";
    private static final String OAUTH_URI = "/oauth/token";
    private static final String PROTECTED_URI = "/dashboard";

    private static void getToken() throws Exception {
        String username = System.getProperty("username");
        String password = System.getProperty("password");

        if (username == null || password == null) {
            System.err.println("Must supply -Dusername=<username> -Dpassword=<password> on the command line");
            System.exit(1);
        }

        PostMethod method = new PostMethod(APP_URL + OAUTH_URI);

        method.setRequestHeader("Origin", APP_URL);
        method.setRequestHeader("Content-type", "application/x-www-form-urlencoded");

        method.addParameter("grant_type", "password");
        method.addParameter("username", username);
        method.addParameter("password", password);

        HttpClient client = new HttpClient();
        client.executeMethod(method);

        BufferedReader br = new BufferedReader(new InputStreamReader(method.getResponseBodyAsStream()));
        String readLine;
        while(((readLine = br.readLine()) != null)) {
            System.out.println(readLine);
        }
    }

    private static void getPage() throws Exception {
        String token = System.getProperty("token");

        if (token == null) {
            System.err.println("Must supply -Dtoken=<access token> on the command line");
            System.exit(1);
        }

        GetMethod method = new GetMethod(APP_URL + PROTECTED_URI);
        HttpClient client = new HttpClient();

        System.out.println("Attempting to retrieve " + PROTECTED_URI + " without token...");

        int returnCode = client.executeMethod(method);
        System.out.println("return code: " + returnCode);

        System.out.println();

        System.out.println("Attempting to retrieve " + PROTECTED_URI + " with token...");

        method.addRequestHeader("Authorization", "Bearer " + token);
        returnCode = client.executeMethod(method);
        System.out.println("return code: " + returnCode);
    }
}


来源:https://stackoverflow.com/questions/33605873/having-trouble-implementing-stormpath-form-login-authentication-alongside-rest-o

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!