Announcement Announcement Module
Collapse
No announcement yet.
username password flow 2 legged Page Title Module
Move Remove Collapse
X
Conversation Detail Module
Collapse
  • Filter
  • Time
  • Show
Clear All
new posts

  • username password flow 2 legged

    hello to everyone,

    i am trying to develop username and password flow over server ,i am going over spring security oauth2 sparklr and tonr application,how can i convert this to username password flow,i will use it over android,and android client will connect to server and gets a data,can you help me ,or is tthere any developed code

    thank you so much

  • #2
    i want to disable user login page is shown below
    how can i disable,oauth2 is really hard , how can i change this to username password flow
    <http access-denied-page="/login.jsp" access-decision-manager-ref="accessDecisionManager" xmlns="http://www.springframework.org/schema/security">
    <intercept-url pattern="/photos" access="ROLE_USER,SCOPE_READ" />
    <intercept-url pattern="/photos/**" access="ROLE_USER,SCOPE_READ" />
    <intercept-url pattern="/trusted/**" access="ROLE_USER,SCOPE_TRUST" />
    <intercept-url pattern="/oauth/token" access="IS_AUTHENTICATED_ANONYMOUSLY" />
    <intercept-url pattern="/oauth/**" access="ROLE_USER" />
    <intercept-url pattern="/request_token_authorized.jsp" access="ROLE_USER,DENY_OAUTH" />
    <intercept-url pattern="/**" access="IS_AUTHENTICATED_ANONYMOUSLY,DENY_OAUTH" />

    <form-login authentication-failure-url="/login.jsp" default-target-url="/index.jsp" login-page="/login.jsp"
    login-processing-url="/login.do" />
    <logout logout-success-url="/index.jsp" logout-url="/logout.do" />
    <anonymous />
    <custom-filter ref="oauth2ProviderFilter" after="EXCEPTION_TRANSLATION_FILTER" />
    </http>

    Comment


    • #3
      You can see username/password grant type enabled on the existing oauth2 sparklr sample app:

      https://github.com/SpringSource/spri...ng-servlet.xml

      Note the <oauth:client-details-service> element. The "my-trusted-client" client is authorized for the username/password grant type.

      Comment


      • #4
        thank you Stoicflame,yes this is the same with mine, how can i connect with username password,i dont want web flow,i will connect it from ANDROID..I need this flow
        my client is shown below thank you very much
        package com.days.twoleggedoauthtestclient2;

        import java.io.BufferedReader;
        import java.io.ByteArrayOutputStream;
        import java.io.File;
        import java.io.FileOutputStream;
        import java.io.IOException;
        import java.io.InputStream;
        import java.io.InputStreamReader;
        import java.io.OutputStream;
        import java.net.URL;
        import oauth.signpost.OAuthConsumer;
        import oauth.signpost.commonshttp.CommonsHttpOAuthConsume r;
        import oauth.signpost.exception.OAuthCommunicationExcepti on;
        import oauth.signpost.exception.OAuthExpectationFailedExc eption;
        import oauth.signpost.exception.OAuthMessageSignerExcepti on;

        import org.apache.commons.io.IOUtils;
        import org.apache.http.HttpResponse;
        import org.apache.http.client.HttpClient;
        import org.apache.http.client.methods.HttpGet;
        import org.apache.http.impl.client.DefaultHttpClient;

        public class App {

        private static final String SERVER_URL = "http://localhost:8080/sparklr";
        // private static final String SERVER_URL_RESOURCE = SERVER_URL + "/rest/jpg/photo/1"; // to view a single photo
        private static final String SERVER_URL_RESOURCE = SERVER_URL + "/rest/photos"; // to view ALL photos
        private static final String CONSUMER_KEY = "tonr-consumer-key";
        private static final String CONSUMER_SECRET = "SHHHHH!!!!!!!!!!";
        private static final String SIGNATURE_METHOD = "HMAC-SHA1";
        private static final String DUMMY ="http://localhost:8080/sparklr/oauth/authorize";
        public static void main(String[] args) throws IOException, OAuthMessageSignerException, OAuthExpectationFailedException, OAuthCommunicationException {
        // create a consumer object and configure it with the access
        // token and token secret obtained from the service provider
        OAuthConsumer consumer = new CommonsHttpOAuthConsumer(CONSUMER_KEY,
        CONSUMER_SECRET);
        // create an HTTP request to a protected resource
        HttpGet request = new HttpGet(SERVER_URL + "/rest/jpg/photo/1");
        // HttpGet request = new HttpGet(DUMMY);
        // sign the request
        consumer.sign(request);

        // send the request
        HttpClient httpClient = new DefaultHttpClient();
        HttpResponse response = httpClient.execute(request);
        InputStream inputStream = response.getEntity().getContent();
        System.out.println(convertinputStreamToString(inpu tStream));
        OutputStream output = new FileOutputStream(new File("c:\\x.jpg"));
        IOUtils.copy(inputStream, output);
        inputStream.close();
        output.close();
        }

        public static String convertinputStreamToString(InputStream ists) throws IOException {

        if (ists != null) {
        StringBuilder sb = new StringBuilder();
        String line;

        try {
        BufferedReader r1 = new BufferedReader(new InputStreamReader(ists, "UTF-8"));
        while ((line = r1.readLine()) != null) {
        sb.append(line).append("\n");
        }
        } finally {
        ists.close();
        }
        return sb.toString();
        } else {
        return "";
        }
        }


        }

        Comment


        • #5
          i cant find any documentation that addresses over sparklr2 username and password flow and how can i connect over it

          Comment


          • #6
            i did it at the end code is:
            public class App {

            private static RestTemplate client=getRestTemplate();

            private static int DEFAULT_PORT = 8080;

            private static String DEFAULT_HOST = "localhost";

            private static int port=DEFAULT_PORT;

            private static String hostName = DEFAULT_HOST;


            public static void main(String[] args) throws IOException {
            try {
            testHappyDayWithForm();
            } catch (Exception ex) {
            Logger.getLogger(App.class.getName()).log(Level.SE VERE, null, ex);
            }
            }


            public static void testHappyDayWithForm() throws Exception {

            MultiValueMap<String, String> formData = new LinkedMultiValueMap<String, String>();
            formData.add("grant_type", "password");
            formData.add("client_id", "my-trusted-client");
            formData.add("scope", "read");
            formData.add("username", "dasfsdf");
            formData.add("password", "24122454");

            ResponseEntity<String> response = postForString("/sparklr/oauth/token", formData);
            System.out.println( response.getStatusCode());
            System.out.println(response.getHeaders().getFirst( "Cache-Control"));

            DefaultOAuth2SerializationService serializationService = new DefaultOAuth2SerializationService();
            OAuth2AccessToken accessToken = serializationService.deserializeJsonAccessToken(ne w ByteArrayInputStream(
            response.getBody().getBytes()));

            // now try and use the token to access a protected resource.

            // first make sure the resource is actually protected.
            //assertNotSame(HttpStatus.OK, serverRunning.getStatusCode("/sparklr/photos?format=json"));

            // now make sure an authorized request is valid.
            HttpHeaders headers = new HttpHeaders();
            headers.set("Authorization", String.format("%s %s", OAuth2AccessToken.BEARER_TYPE, accessToken.getValue()));
            //assertEquals(HttpStatus.OK, serverRunning.getStatusCode("/sparklr/photos?format=json", headers));
            }

            public static ResponseEntity<String> postForString(String path, MultiValueMap<String, String> formData) {
            HttpHeaders headers = new HttpHeaders();
            headers.setAccept(Arrays.asList(MediaType.APPLICAT ION_FORM_URLENCODED));
            System.out.println(getUrl(path));
            return client.exchange(getUrl(path), HttpMethod.POST, new HttpEntity<MultiValueMap<String, String>>(formData,
            headers), String.class);
            }
            public static String getUrl(String path) {
            if (!path.startsWith("/")) {
            path = "/" + path;
            }
            return "http://" + hostName + ":" + port + path;
            }

            public static RestTemplate getRestTemplate() {
            RestTemplate client = new RestTemplate();
            CommonsClientHttpRequestFactory requestFactory = new CommonsClientHttpRequestFactory() {
            @Override
            protected void postProcessCommonsHttpMethod(HttpMethodBase httpMethod) {
            httpMethod.setFollowRedirects(false);
            // We don't want stateful conversations for this test
            httpMethod.getParams().setCookiePolicy(CookiePolic y.IGNORE_COOKIES);
            }
            };
            client.setRequestFactory(requestFactory);
            client.setErrorHandler(new ResponseErrorHandler() {
            // Pass errors through in response entity for status code analysis
            public boolean hasError(ClientHttpResponse response) throws IOException {
            return false;
            }

            public void handleError(ClientHttpResponse response) throws IOException {
            }
            });
            return client;
            }

            Comment


            • #7
              but instead of this,i need to use another client on android,because spring jas is too big,is there any solution?

              Comment

              Working...
              X