org.apigw.monitoring.svc.impl.MonitoredTokenServices.java Source code

Java tutorial

Introduction

Here is the source code for org.apigw.monitoring.svc.impl.MonitoredTokenServices.java

Source

/**
 *   Copyright 2013 Stockholm County Council
 *
 *   This file is part of APIGW
 *
 *   APIGW is free software; you can redistribute it and/or modify
 *   it under the terms of version 2.1 of the GNU Lesser General Public
 *   License as published by the Free Software Foundation.
 *
 *   APIGW is distributed in the hope that it will be useful,
 *   but WITHOUT ANY WARRANTY; without even the implied warranty of
 *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *   GNU Lesser General Public License for more details.
 *
 *   You should have received a copy of the GNU Lesser General Public
 *   License along with APIGW; if not, write to the
 *   Free Software Foundation, Inc., 59 Temple Place, Suite 330,
 *   Boston, MA 02111-1307  USA
 *
 */

package org.apigw.monitoring.svc.impl;

import org.apigw.authserver.svc.TokenServices;
import org.apigw.authserver.types.exception.LegalGuardianValidationException;
import org.apigw.monitoring.svc.OAuthMonitoringService;
import org.apigw.monitoring.svc.exception.ApigwMonitoringException;
import org.apigw.monitoring.types.enums.RequestState;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.oauth2.common.OAuth2AccessToken;
import org.springframework.security.oauth2.provider.AuthorizationRequest;
import org.springframework.security.oauth2.provider.OAuth2Authentication;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Collection;
import java.util.HashSet;
import java.util.Set;

/**
 * Created by martin on 02/01/15.
 */
@Service
public class MonitoredTokenServices implements TokenServices {

    private static final Logger logger = LoggerFactory.getLogger(MonitoredTokenServices.class);

    private TokenServices tokenServices;

    @Autowired
    private OAuthMonitoringService monitoringService;

    @Override
    public void setRefreshTokenValiditySeconds(long refreshTokenValiditySeconds) {
        tokenServices.setRefreshTokenValiditySeconds(refreshTokenValiditySeconds);
    }

    @Override
    public void setAccessTokenValiditySeconds(long accessTokenValiditySeconds) {
        tokenServices.setAccessTokenValiditySeconds(accessTokenValiditySeconds);
    }

    @Override
    public void setReuseRefreshToken(boolean reuseRefreshToken) {
        tokenServices.setReuseRefreshToken(reuseRefreshToken);
    }

    @Override
    public void setSupportRefreshToken(boolean supportRefreshToken) {
        tokenServices.setSupportRefreshToken(supportRefreshToken);
    }

    @Override
    @Transactional
    public OAuth2AccessToken createAccessToken(String citizenResidentIdentificationNumber, String clientId,
            Collection<String> scope) throws AuthenticationException {
        logger.debug("createAccessToken from trusted client - start");
        String tokenValue = null;
        Set<String> scopeSet = new HashSet<>();
        try {
            OAuth2AccessToken accessToken = tokenServices.createAccessToken(citizenResidentIdentificationNumber,
                    clientId, scope);
            tokenValue = accessToken.getValue();
            scopeSet = accessToken.getScope();
            monitorCreateAccessToken(clientId, scopeSet, tokenValue, RequestState.SUCCESS, "TRUSTED",
                    citizenResidentIdentificationNumber, "TRUSTED");
            logger.debug("createAccessToken from trusted client - end");
            return accessToken;
        } catch (ApigwMonitoringException e) {
            throw e;
        } catch (RuntimeException e) {
            logger.error("error creating access token from trusted client", e);
            monitorCreateAccessToken(clientId, scopeSet, tokenValue, RequestState.SERVER_FAILURE, e.getMessage(),
                    citizenResidentIdentificationNumber, "TRUSTED");
            throw e;
        }
    }

    @Override
    @Transactional
    public OAuth2AccessToken createAccessToken(String legalGuardianResidentIdentificationNumber,
            String citizenResidentIdentificationNumber, String clientId, Collection<String> scope)
            throws AuthenticationException, LegalGuardianValidationException {
        logger.debug("createAccessToken from trusted client for legalGuardian - start");
        String tokenValue = null;
        Set<String> scopeSet = new HashSet<>();
        String user = legalGuardianResidentIdentificationNumber + "/" + citizenResidentIdentificationNumber;
        try {
            OAuth2AccessToken accessToken = tokenServices.createAccessToken(
                    legalGuardianResidentIdentificationNumber, citizenResidentIdentificationNumber, clientId,
                    scope);
            tokenValue = accessToken.getValue();
            scopeSet = accessToken.getScope();
            monitorCreateAccessToken(clientId, scopeSet, tokenValue, RequestState.SUCCESS, "TRUSTED", user,
                    "TRUSTED");
            logger.debug("createAccessToken from trusted client for legalGuardian - end");
            return accessToken;
        } catch (ApigwMonitoringException e) {
            throw e;
        } catch (RuntimeException e) {
            logger.error("error creating access token from trusted client for legalGuardian", e);
            monitorCreateAccessToken(clientId, scopeSet, tokenValue, RequestState.SERVER_FAILURE, e.getMessage(),
                    user, "TRUSTED");
            throw e;
        }
    }

    @Override
    @Transactional
    public OAuth2AccessToken createAccessToken(OAuth2Authentication authentication) throws AuthenticationException {
        logger.debug("createAccessToken - start");
        String ssn = null;
        User user = (User) authentication.getPrincipal();
        if (user != null) {
            ssn = user.getUsername();
        }
        String clientId = authentication.getAuthorizationRequest().getClientId();
        String code = authentication.getAuthorizationRequest().getAuthorizationParameters().get("code");
        String tokenValue = null;
        Set<String> scope = new HashSet<>();
        try {
            OAuth2AccessToken accessToken = tokenServices.createAccessToken(authentication);
            tokenValue = accessToken.getValue();
            scope = accessToken.getScope();
            monitorCreateAccessToken(clientId, scope, tokenValue, RequestState.SUCCESS, null, ssn, code);
            logger.debug("createAccessToken - end");
            return accessToken;
        } catch (ApigwMonitoringException e) {
            throw e;
        } catch (RuntimeException e) {
            logger.error("error creating access token", e);
            monitorCreateAccessToken(clientId, scope, null, RequestState.SERVER_FAILURE, e.getMessage(), ssn, code);
            throw e;
        }
    }

    @Override
    @Transactional
    public boolean revokeToken(String tokenValue) {
        logger.debug("revokeToken - start");
        String ssn = null;
        String clientId = null;
        try {
            OAuth2Authentication auth = tokenServices.loadAuthentication(tokenValue);
            OAuth2AccessToken accessToken = tokenServices.readAccessToken(tokenValue);
            Set<String> scope = accessToken.getScope();
            User user = (User) auth.getUserAuthentication().getPrincipal();
            if (user != null) {
                ssn = user.getUsername();
            }
            clientId = auth.getAuthorizationRequest().getClientId();
            boolean tokenRevoked = tokenServices.revokeToken(tokenValue);
            if (tokenRevoked) {
                monitorRevokeToken(clientId, scope, tokenValue, RequestState.SUCCESS,
                        "Appen r inte lngre godknd fr anvndning", ssn);
            } else {
                monitorRevokeToken(clientId, scope, tokenValue, RequestState.SERVER_FAILURE,
                        "Godknnande kunde ej tas bort", ssn);
            }
            logger.debug("revokeToken - end");
            return tokenRevoked;
        } catch (ApigwMonitoringException e) {
            throw e;
        } catch (RuntimeException e) {
            monitorRevokeToken(clientId, null, tokenValue, RequestState.SERVER_FAILURE, e.getMessage(), ssn);
            throw e;
        }
    }

    @Override
    public OAuth2AccessToken readAccessToken(String accessToken) {
        return tokenServices.readAccessToken(accessToken);
    }

    private void monitorCreateAccessToken(String clientId, Set<String> scope, String token, RequestState state,
            String message, String user, String code) {
        try {
            monitoringService.logCreateAccessToken(System.currentTimeMillis(), token, clientId, scope, code,
                    state.toString(), message, user);
        } catch (ApigwMonitoringException e) {
            logger.error(
                    "Failed to monitor createAccessToken clientId[{}], scope[{}], token[{}], state[{}], message[{}]: {}",
                    clientId, scope, token, state, message, e);
            throw e;
        }
    }

    private void monitorRevokeToken(String clientId, Set<String> scope, String token, RequestState state,
            String message, String user) {
        try {
            monitoringService.logRevokeAccessToken(System.currentTimeMillis(), token, clientId, scope,
                    state.toString(), message, user);
        } catch (ApigwMonitoringException e) {
            logger.error(
                    "Failed to monitor revokeToken clientId[{}], scope[{}], token[{}], state[{}], message[{}]: {}",
                    clientId, scope, token, state, message, e);
            throw e;
        }
    }

    @Override
    public OAuth2AccessToken refreshAccessToken(String refreshToken, AuthorizationRequest request)
            throws AuthenticationException {
        return tokenServices.refreshAccessToken(refreshToken, request);
    }

    @Override
    public OAuth2AccessToken getAccessToken(OAuth2Authentication authentication) {
        return tokenServices.getAccessToken(authentication);
    }

    @Override
    public Collection<OAuth2AccessToken> findTokensByUserName(String userName) {
        return tokenServices.findTokensByUserName(userName);
    }

    @Override
    public Collection<OAuth2AccessToken> findTokensByClientId(String clientId) {
        return tokenServices.findTokensByClientId(clientId);
    }

    @Override
    public String getClientId(String tokenValue) {
        return tokenServices.getClientId(tokenValue);
    }

    @Override
    public OAuth2Authentication loadAuthentication(String accessToken) throws AuthenticationException {
        return tokenServices.loadAuthentication(accessToken);
    }

    public void setTokenServices(TokenServices tokenServices) {
        this.tokenServices = tokenServices;
    }
}