Using Oltu Framework to Build Demo Project for OAuth

Apache's Oltu is the framework that implements OAuth

Reference article:

http://jinnianshilongnian.iteye.com/blog/2038646

https://blog.csdn.net/jing12062011/article/details/78147306

 

1. Build Maven Project Framework

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"

      xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">

      <modelVersion>4.0.0</modelVersion>

      <groupId>com.inspur</groupId>

      <artifactId>OAuth-Demo</artifactId>

      <version>0.0.1-SNAPSHOT</version>



      <properties>

           <oauth2.version>1.0.2</oauth2.version>

      </properties>



      <parent>

           <groupId>org.springframework.boot</groupId>

           <artifactId>spring-boot-starter-parent</artifactId>

           <version>2.0.0.RELEASE</version>

      </parent>



      <dependencies>

           <dependency>

                 <groupId>org.springframework.boot</groupId>

                 <artifactId>spring-boot-starter-web</artifactId>

           </dependency>

           <!-- OAuth2 Framework for the Agreement -->

           <dependency>

                 <groupId>org.apache.oltu.oauth2</groupId>

                 <artifactId>org.apache.oltu.oauth2.client</artifactId>

                 <version>${oauth2.version}</version>

           </dependency>

           <dependency>

                 <groupId>org.apache.oltu.oauth2</groupId>

                 <artifactId>org.apache.oltu.oauth2.common</artifactId>

                 <version>${oauth2.version}</version>

           </dependency>

           <dependency>

                 <groupId>org.apache.oltu.oauth2</groupId>

                 <artifactId>org.apache.oltu.oauth2.authzserver</artifactId>

                 <version>${oauth2.version}</version>

           </dependency>

           <dependency>

                 <groupId>org.apache.oltu.oauth2</groupId>

                 <artifactId>org.apache.oltu.oauth2.resourceserver</artifactId>

                 <version>${oauth2.version}</version>

           </dependency>

           <!-- Hot Deployment -->

           <dependency>

                 <groupId>org.springframework.boot</groupId>

                 <artifactId>spring-boot-devtools</artifactId>

           </dependency>

      </dependencies>



      <build>

           <plugins>

                 <plugin>

                      <artifactId>maven-compiler-plugin</artifactId>

                      <configuration>

                            <source>1.8</source>

                            <target>1.8</target>

                      </configuration>

                 </plugin>

           </plugins>

      </build>

</project>

 

2. Create project directory structure

 

 

3. Write Controller using Authorization Number mode

3.1 Service Consumers

/**

 * Service Consumer Controller Layer

 * @Title OauthClientController

 * @author LinkedBear

 * @Time 2018 August 1, 2001 2:10:14 p.m.

 */

@Controller

public class OauthClientController {

    //Step 1: Service consumers need to apply for authorization numbers from users

    @RequestMapping("/applyCode")

    public String applyCode(HttpServletRequest request) {

        System.out.println("----------Step 1: Service consumers need to apply for authorization numbers from users-----------");

       

        //Step 2's jump URL (Request Code)

        String accessCodeUrl = "getAuthorization";

        //Required and fixed to code

        String responseType = "code";

        //Required

        String clientId = "client";

        //The url you want to access in step 3

        String redirectUri = "http://localhost:8080/applyToken";

       

        //Create OAuth Client Object

        //OAuthClient client = new OAuthClient(new URLConnectionClient());

        //Build an OAuth request

        String locationUri = "";

        try {

            OAuthClientRequest oauthRequest = OAuthClientRequest.authorizationLocation(accessCodeUrl)

                    .setRedirectURI(redirectUri)

                    .setClientId(clientId)

                    .setResponseType(responseType)

                    .buildQueryMessage();

            locationUri = oauthRequest.getLocationUri();

            System.out.println("The first step redirects the address:" + locationUri);

        } catch (Exception e) {

            e.printStackTrace();

        }

       

        //redirect

        return "redirect:http://localhost:8080/" + locationUri;

    }

   

   

   

    //Step 3: Service consumers should initiate a request to the authentication authorization server with their local ID and authorization number

    @RequestMapping("/applyToken")

    public String applyToken(HttpServletRequest request) {

        System.out.println("----------Step 3: Service consumers should initiate a request to the Authentication Authorization Server to take the machine with them ID And authorization number-----------");

       

        //Step 4 jump URL (request Token)

        //Key: This is to send a request back to json, so it is not a redirection, no url splicing below, it can only be written here completely

        String accessTokenUrl = "http://localhost:8080/getToken";

        String clientId = "client";

        //Fields used to identify clients

        String clientSecurt = "clientSecurt";

        //The url you want to access in step 5

        String redirectUri = "http://localhost:8080/callbackCode";

       

        String code = request.getParameter("code");

        System.out.println("Authorization number returned by the user:" + code);

       

        //Create OAuth Client Object

        OAuthClient client = new OAuthClient(new URLConnectionClient());

        //Build an OAuth request

        String locationUri = "";

        try {

            //Requests here have different invocation methods because they carry authorization numbers and request access to Token

            OAuthClientRequest oauthCodeRequest = OAuthClientRequest.tokenLocation(accessTokenUrl)

                    .setGrantType(GrantType.AUTHORIZATION_CODE)

                    .setRedirectURI(redirectUri)

                    .setClientId(clientId)

                    .setClientSecret(clientSecurt)

                    .setCode(code)

                    .buildQueryMessage();

            locationUri = oauthCodeRequest.getLocationUri();

            System.out.println("Step 3 Redirect Address:" + locationUri);

            //Send a request and get a response

            OAuthJSONAccessTokenResponse tokenResponse = client.accessToken(oauthCodeRequest, HttpMethod.POST);

            //Access Token

            String token = tokenResponse.getAccessToken();

            System.out.println("Accessed Token: " + token);

           

            //redirect

            return "redirect:http://localhost:8080/applyResource?accessToken=" + token;

        } catch (Exception e) {

            e.printStackTrace();

            return null;

        }

    }

   

   

   

    //Step 5: Service consumers hold Token access request service providers

    @RequestMapping("/applyResource")

    @ResponseBody

    public Map<String, Object> applyResource(String accessToken) {

        System.out.println("----------Step 5: Service consumers hold Token Access Request Service Provider-----------");

       

        //Resource Address to Request

        String realResourceUrl = "http://localhost:8080/getResource";

       

        //Create OAuth Client Object

        OAuthClient client = new OAuthClient(new URLConnectionClient());

        try {

            //Build real resource access requests with Token's past

            OAuthClientRequest oauthTokenRequest = new OAuthBearerClientRequest(realResourceUrl)

                    .setAccessToken(accessToken)

                    .buildQueryMessage();

            System.out.println("Prepare to send a request to the service provider.");

            //Request Resources

            OAuthResourceResponse resourceResponse = client.resource(oauthTokenRequest,

                    HttpMethod.GET, OAuthResourceResponse.class);

            String resource = resourceResponse.getBody();

            System.out.println("Requested Resources" + resource);

            return JSONUtils.parseJSON(resource);

        } catch (Exception e) {

            return null;

        }

    }

}

 

 

3.2 Users

/**

 * User Controller Layer

 * @Title OauthUserController

 * @author LinkedBear

 * @Time 2018 August 1, 2001 2:30:29 p.m.

 */

@Controller

public class OauthUserController {

    public static final String AUTHORIZATION_CODE = "123";

   

    //Step 2: The user receives a request from the consumer of the service, verifies it, responds, and returns the authorization number

    @SuppressWarnings("unused")

    @RequestMapping("/getAuthorization")

    public Object getAuthorization(HttpServletRequest request) {

        System.out.println("----------Step 2: The user receives a request from the consumer of the service and verifies it to respond-----------");

       

        try {

            //Build OAuth Authorization Request

            OAuthAuthzRequest authzRequest = new OAuthAuthzRequest(request);

            //Reject empty client request

            if (StringUtils.isEmpty(authzRequest.getClientId())) {

                return null;

            }

           

            //Take responseType, the value of Authorization Code mode is fixed bit "code"

            String responseType = authzRequest.getResponseType();

            //Build the OAuth response, where 302 redirects are required

            OAuthAuthorizationResponseBuilder responseBuilder =

                    OAuthASResponse.authorizationResponse(request, HttpServletResponse.SC_FOUND);

            //Set Authorization Number

            responseBuilder.setCode(AUTHORIZATION_CODE);

           

            //Get the redirection address of the service consumer and build the OAuth response

            String redirectUri = authzRequest.getRedirectURI();

            OAuthResponse oauthResponse = responseBuilder.location(redirectUri)

                    .buildQueryMessage();

            //Redirected url when built

            String locationUri = oauthResponse.getLocationUri();

            System.out.println("Step 2 Redirect Address:" + locationUri);

           

            return "redirect:" + locationUri;

        } catch (Exception e) {

            e.printStackTrace();

            return null;

        }

    }

}

 

 

3.3 Authentication Authorization Server

/**

 * Authentication Authorization Server Controller Layer

 * @Title OauthAuthenticationController

 * @author LinkedBear

 * @Time 2018 August 1, 2001 2:10:57 p.m.

 */

@Controller

public class OauthAuthenticationController {

    //Step 4: Access Licensing Server receives requests from service consumers, verifies and grants access to Token and updates to Token

    @PostMapping("/getToken")

    public ResponseEntity<Object> getToken(HttpServletRequest request) {

        System.out.println("----------Step 4: Access Licensing Server receives requests from service consumers, verifies and grants access Token And updates Token-----------");

       

        try {

            //Build OAuth authorization request, where Code already exists

            OAuthTokenRequest authzTokenRequest = new OAuthTokenRequest(request);

            //Obtain Authorization Number

            String code = authzTokenRequest.getCode();

            //Authorization number does not match, reject directly

            if (!OauthUserController.AUTHORIZATION_CODE.equals(code)) {

                return null;

            }

           

            //Generate Token

            OAuthIssuerImpl tokenCreater = new OAuthIssuerImpl(new MD5Generator());

            String token = tokenCreater.accessToken();

            System.out.println("generate Token: " + token);

           

            //Build an OAuth response

            OAuthResponse oauthResponse = OAuthASResponse.tokenResponse(HttpServletResponse.SC_OK)

                    .setAccessToken(token)

                    .setTokenType(TokenType.BEARER.name())

                    .buildJSONMessage();

            //The data returned is a set of json s

            return new ResponseEntity<Object>(oauthResponse.getBody(), HttpStatus.valueOf(oauthResponse.getResponseStatus()));

        } catch (Exception e) {

            e.printStackTrace();

            return null;

        }

    }

}

 

3.4 Service Providers

/**

 * Service Provider Controller Layer

 * @Title OauthServerController

 * @author LinkedBear

 * @Time 2018 August 1, 2001 2:09:35 p.m.

 */

@Controller

public class OauthServerController {

    //Step 6: The service provider verifies the Token and returns the resource

    @RequestMapping("/getResource")

    @ResponseBody

    public ResponseEntity<Map<String, Object>> getResource(HttpServletRequest request) {

        System.out.println("----------Step 6: Service Provider Validation Token,Return resources-----------");

       

        try {

            //The last step is to take the resource, so the request to build is different, with a parameter attached

            OAuthAccessResourceRequest resourceRequest = new OAuthAccessResourceRequest(request, ParameterStyle.QUERY);

            String token = resourceRequest.getAccessToken();

            //You also need to verify Token here.

            System.out.println("Unverified Token. . . " + token);

           

            Map<String, Object> map = new HashMap<>();

            map.put("data", Math.random());

            map.put("creater", "LinkedBear");

            return new ResponseEntity<Map<String, Object>>(map, HttpStatus.OK);

        } catch (Exception e) {

            e.printStackTrace();

            return null;

        }

    }

}

 

3.5 Run Results

---------------Step 1: Service consumers should apply for authorization numbers from users-----------

First step redirect address: getAuthorization? Response_type=code&redirect_uri=http%3A%2F%2Flocalhost%3A8080%2FapplyToken&client_id=client

-----------------------------------------

Step 2 Redirect Address: http://localhost:8080/applyToken?code=123

-------------------------------------------------------

Authorization number returned by user: 123

Step 3 Redirect address: http://localhost:8080/getToken? Code=123&grant_type=authorization_code&redirect_uri=http%3A%2F%2Flocalhost%3A8080%2FcallbackCode&client_secret=clientSecurt&client_id=client

---------- Step 4: Access authorization server receives requests from service consumers, verifies and grants access to Token and updates to Token-----------

Generate Token:b9bbc794d09cac19f11951972fd7d5b1

Get access to Token:b9bbc794d09cac19f11951972fd7d5b1

------------ Step 5: Service consumers hold Token access requests to service providers-----------

Prepare to send a request to the service provider.

------------ Step 6: Service Provider verifies Token and returns resources-----------

Token is not verified.b9bbc794d09cac19f11951972fd7d5b1

The requested resource {"data": 0.089760065502468, "creater": "LinkedBear"}

Tags: Apache Maven Spring JSON

Posted on Wed, 15 Jan 2020 11:14:22 -0500 by MNSarahG