com.brunomcustodio.dojo.keycloak.auth.AuthServiceEndpointsImpl.java Source code

Java tutorial

Introduction

Here is the source code for com.brunomcustodio.dojo.keycloak.auth.AuthServiceEndpointsImpl.java

Source

// Copyright 2014 Bruno M. Custdio
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

package com.brunomcustodio.dojo.keycloak.auth;

import com.brunomcustodio.dojo.keycloak.auth.data.UserCredentials;
import com.brunomcustodio.dojo.keycloak.auth.data.UserToken;
import com.brunomcustodio.dojo.keycloak.auth.comm.KeycloakClient;
import com.brunomcustodio.dojo.keycloak.auth.comm.KeycloakAccessGrant;
import com.google.gson.FieldNamingPolicy;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import org.apache.commons.configuration.Configuration;
import org.apache.commons.configuration.ConfigurationException;
import org.apache.commons.configuration.PropertiesConfiguration;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import retrofit.RestAdapter;
import retrofit.RetrofitError;
import retrofit.converter.GsonConverter;

import javax.ejb.Singleton;
import javax.ws.rs.core.Response;

@Singleton
public class AuthServiceEndpointsImpl implements AuthServiceEndpoints {
    private static final Logger LOGGER = LoggerFactory.getLogger(AuthServiceEndpoints.class);

    private final String bauth;
    private final String realm;
    private final KeycloakClient client;

    public AuthServiceEndpointsImpl() throws ConfigurationException {
        Configuration config = new PropertiesConfiguration("auth.properties");

        bauth = BasicAuth.createHeader(config.getString("keycloak.client"), config.getString("keycloak.secret"));
        realm = config.getString("keycloak.realm");

        Gson gson = new GsonBuilder().setFieldNamingPolicy(FieldNamingPolicy.LOWER_CASE_WITH_UNDERSCORES).create();

        RestAdapter.Builder builder = new RestAdapter.Builder();
        builder.setConverter(new GsonConverter(gson));
        builder.setEndpoint(config.getString("keycloak.root"));
        RestAdapter ra = builder.build();

        client = ra.create(KeycloakClient.class);
    }

    @Override
    public Response login(UserCredentials credentials) {
        try {
            return handleLogin(credentials);
        } catch (RetrofitError exception) {
            return handleLoginError(exception);
        }
    }

    private Response handleLogin(UserCredentials credentials) {
        KeycloakAccessGrant r = client.getAccessGrant(bauth, realm, credentials.getUsername(),
                credentials.getPassword());
        UserToken token = new UserToken(r.getAccessToken(), r.getExpiresIn());
        return Response.status(200).entity(token).build();
    }

    private Response handleLoginError(RetrofitError exception) {
        if (exception.getKind() == RetrofitError.Kind.HTTP) {
            LOGGER.debug(exception.getMessage(), exception);
            return Response.status(400).build(); // BAD REQUEST
        } else {
            LOGGER.error(exception.getMessage(), exception);
            return Response.status(502).build(); // BAD GATEWAY
        }
    }
}