use of org.maxkey.authz.oauth2.common.OAuth2AccessToken in project developer-be by EdgeGallery.
the class AccessTokenFilter method doFilterInternal.
@Override
protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
if (request.getRequestURI() == null || !(request.getRequestURI().equals("/health"))) {
String accessTokenStr = request.getHeader(Consts.ACCESS_TOKEN_STR);
if (StringUtils.isEmpty(accessTokenStr)) {
LOGGER.error("Access token is empty");
response.sendError(HttpStatus.UNAUTHORIZED.value(), "Access token is empty");
return;
}
OAuth2AccessToken accessToken = jwtTokenStore.readAccessToken(accessTokenStr);
if (accessToken == null) {
LOGGER.error("Invalid access token, token string is null");
response.sendError(HttpStatus.UNAUTHORIZED.value(), "Invalid access token, token string is null.");
return;
}
if (accessToken.isExpired()) {
LOGGER.error("Access token expired");
response.sendError(HttpStatus.UNAUTHORIZED.value(), "Access token expired");
return;
}
Map<String, Object> additionalInfoMap = accessToken.getAdditionalInformation();
if (additionalInfoMap == null) {
LOGGER.error("Invalid access token, additional info map is null.");
String msg = "Invalid access token, additional info map is null.";
response.sendError(HttpStatus.UNAUTHORIZED.value(), msg);
return;
}
String userIdFromToken = additionalInfoMap.get("userId").toString();
String userNameFromToken = additionalInfoMap.get("userName").toString();
String userAuthFromToken = additionalInfoMap.get("authorities").toString();
AccessUserUtil.setUser(userIdFromToken, userNameFromToken, userAuthFromToken, accessTokenStr);
String userIdFromRequest = request.getParameter("userId");
if (!StringUtils.isEmpty(userIdFromRequest) && !userIdFromRequest.equals(userIdFromToken)) {
LOGGER.error("Illegal userId");
response.sendError(HttpStatus.UNAUTHORIZED.value(), "Illegal userId");
return;
}
String userNameFromRequest = request.getParameter("userName");
if (!StringUtils.isEmpty(userNameFromRequest) && !userNameFromRequest.equals(userNameFromToken)) {
LOGGER.error("Illegal userName");
response.sendError(HttpStatus.UNAUTHORIZED.value(), "Illegal userName");
return;
}
OAuth2Authentication auth = jwtTokenStore.readAuthentication(accessToken);
if (auth == null) {
LOGGER.error("Invalid access token, authentication info is null.");
String msg = "Invalid access token, authentication info is null.";
response.sendError(HttpStatus.UNAUTHORIZED.value(), msg);
return;
}
SecurityContextHolder.getContext().setAuthentication(auth);
}
try {
filterChain.doFilter(request, response);
} finally {
AccessUserUtil.unload();
}
}
use of org.maxkey.authz.oauth2.common.OAuth2AccessToken in project alexa-oauth-sample by alexa-samples.
the class ReciprocalAuthorizationEndpoint method postReciprocalCode.
@RequestMapping(value = "/api/reciprocal/authorize", method = RequestMethod.POST)
public void postReciprocalCode(@RequestBody @RequestParam final Map<String, String> parameters) {
Authentication auth = SecurityContextHolder.getContext().getAuthentication();
String grantType = parameters.get("grant_type");
// It is not the client_id we got from partner, but the client id we vend out to partner (partnerId).
String partnerId = parameters.get("client_id");
String authorizationCode = parameters.get("code");
if (!StringUtils.equals(grantType, GRANT_TYPE)) {
throw new UnsupportedGrantTypeException("Only reciprocal_authorization_code is supported in this endpoint");
}
OAuthPartner partner = partnerDetailsRepository.loadPartnerByPartnerId(partnerId);
if (partner == null) {
throw new NoSuchClientException("Invalid partner id: " + partnerId);
}
OAuth2ProtectedResourceDetails resourceDetails = partner.toProtectedResourceDetails();
AuthorizationCodeAccessTokenProvider tokenProvider = new AuthorizationCodeAccessTokenProvider();
tokenProvider.setStateMandatory(false);
OAuth2AccessToken accessToken = tokenProvider.obtainAccessToken(resourceDetails, createAccessTokenRequest(authorizationCode));
partnerTokenRepository.saveAccessToken(resourceDetails, auth, accessToken);
}
use of org.maxkey.authz.oauth2.common.OAuth2AccessToken in project OpenID-Connect-Java-Spring-Server by mitreid-connect.
the class IntrospectingTokenService method parseToken.
/**
* Validate a token string against the introspection endpoint,
* then parse it and store it in the local cache if caching is enabled.
*
* @param accessToken Token to pass to the introspection endpoint
* @return TokenCacheObject containing authentication and token if the token was valid, otherwise null
*/
private TokenCacheObject parseToken(String accessToken) {
// find out which URL to ask
String introspectionUrl;
RegisteredClient client;
try {
introspectionUrl = introspectionConfigurationService.getIntrospectionUrl(accessToken);
client = introspectionConfigurationService.getClientConfiguration(accessToken);
} catch (IllegalArgumentException e) {
logger.error("Unable to load introspection URL or client configuration", e);
return null;
}
// Use the SpringFramework RestTemplate to send the request to the
// endpoint
String validatedToken = null;
RestTemplate restTemplate;
MultiValueMap<String, String> form = new LinkedMultiValueMap<>();
final String clientId = client.getClientId();
final String clientSecret = client.getClientSecret();
if (SECRET_BASIC.equals(client.getTokenEndpointAuthMethod())) {
// use BASIC auth if configured to do so
restTemplate = new RestTemplate(factory) {
@Override
protected ClientHttpRequest createRequest(URI url, HttpMethod method) throws IOException {
ClientHttpRequest httpRequest = super.createRequest(url, method);
httpRequest.getHeaders().add("Authorization", String.format("Basic %s", Base64.encode(String.format("%s:%s", clientId, clientSecret))));
return httpRequest;
}
};
} else {
// Alternatively use form based auth
restTemplate = new RestTemplate(factory);
form.add("client_id", clientId);
form.add("client_secret", clientSecret);
}
form.add("token", accessToken);
try {
validatedToken = restTemplate.postForObject(introspectionUrl, form, String.class);
} catch (RestClientException rce) {
logger.error("validateToken", rce);
return null;
}
if (validatedToken != null) {
// parse the json
JsonElement jsonRoot = new JsonParser().parse(validatedToken);
if (!jsonRoot.isJsonObject()) {
// didn't get a proper JSON object
return null;
}
JsonObject tokenResponse = jsonRoot.getAsJsonObject();
if (tokenResponse.get("error") != null) {
// report an error?
logger.error("Got an error back: " + tokenResponse.get("error") + ", " + tokenResponse.get("error_description"));
return null;
}
if (!tokenResponse.get("active").getAsBoolean()) {
// non-valid token
logger.info("Server returned non-active token");
return null;
}
// create an OAuth2Authentication
OAuth2Authentication auth = new OAuth2Authentication(createStoredRequest(tokenResponse), createUserAuthentication(tokenResponse));
// create an OAuth2AccessToken
OAuth2AccessToken token = createAccessToken(tokenResponse, accessToken);
if (token.getExpiration() == null || token.getExpiration().after(new Date())) {
// Store them in the cache
TokenCacheObject tco = new TokenCacheObject(token, auth);
if (cacheTokens && (cacheNonExpiringTokens || token.getExpiration() != null)) {
authCache.put(accessToken, tco);
}
return tco;
}
}
// when the token is invalid for whatever reason
return null;
}
use of org.maxkey.authz.oauth2.common.OAuth2AccessToken in project pig by pig-mesh.
the class PigRedisTokenStore method findTokensByClientId.
@Override
public Collection<OAuth2AccessToken> findTokensByClientId(String clientId) {
byte[] key = serializeKey(CLIENT_ID_TO_ACCESS + clientId);
List<byte[]> byteList;
try (RedisConnection conn = getConnection()) {
byteList = getZByteLists(key, conn);
}
if (byteList.size() == 0) {
return Collections.emptySet();
}
List<OAuth2AccessToken> accessTokens = new ArrayList<>(byteList.size());
for (byte[] bytes : byteList) {
OAuth2AccessToken accessToken = deserializeAccessToken(bytes);
accessTokens.add(accessToken);
}
return Collections.unmodifiableCollection(accessTokens);
}
use of org.maxkey.authz.oauth2.common.OAuth2AccessToken in project pig by pig-mesh.
the class PigRedisTokenStore method getAccessToken.
@Override
public OAuth2AccessToken getAccessToken(OAuth2Authentication authentication) {
String key = authenticationKeyGenerator.extractKey(authentication);
byte[] serializedKey = serializeKey(AUTH_TO_ACCESS + key);
byte[] bytes;
try (RedisConnection conn = getConnection()) {
bytes = conn.get(serializedKey);
}
OAuth2AccessToken accessToken = deserializeAccessToken(bytes);
if (accessToken != null) {
OAuth2Authentication storedAuthentication = readAuthentication(accessToken.getValue());
if ((storedAuthentication == null || !key.equals(authenticationKeyGenerator.extractKey(storedAuthentication)))) {
// Keep the stores consistent (maybe the same user is
// represented by this authentication but the details have
// changed)
storeAccessToken(accessToken, authentication);
}
}
return accessToken;
}
Aggregations