Search in sources :

Example 1 with Jwt

use of org.springframework.security.jwt.Jwt in project CzechIdMng by bcvsolutions.

the class TestAppAuthenticationFilter method authorize.

@Override
public boolean authorize(String token, HttpServletRequest request, HttpServletResponse response) {
    try {
        Optional<Jwt> jwt = HttpFilterUtils.parseToken(token);
        if (!jwt.isPresent()) {
            return false;
        }
        Map<String, Object> claims = verifyTokenAndGetClaims(jwt.get());
        String userName = (String) claims.get(HttpFilterUtils.JWT_USER_NAME);
        IdmIdentityDto identity = identityService.getByUsername(userName);
        // not important - either new refreshed token or data are returned to user
        DateTime expiration = null;
        Collection<GrantedAuthority> authorities = null;
        if (shouldGrantAuthoritiesForPath(request.getServletPath())) {
            authorities = grantedAuthoritiesFactory.getGrantedAuthoritiesForIdentity(identity.getId());
        } else {
            authorities = new ArrayList<>();
        }
        IdmJwtAuthentication ija = new IdmJwtAuthentication(identity, expiration, authorities, EntityUtils.getModule(this.getClass()));
        SecurityContextHolder.getContext().setAuthentication(ija);
        return true;
    } catch (Exception e) {
        e.printStackTrace();
    }
    return false;
}
Also used : Jwt(org.springframework.security.jwt.Jwt) GrantedAuthority(org.springframework.security.core.GrantedAuthority) IdmJwtAuthentication(eu.bcvsolutions.idm.core.security.api.domain.IdmJwtAuthentication) IdmIdentityDto(eu.bcvsolutions.idm.core.api.dto.IdmIdentityDto) DateTime(org.joda.time.DateTime) ValidationException(javax.validation.ValidationException)

Example 2 with Jwt

use of org.springframework.security.jwt.Jwt in project CzechIdMng by bcvsolutions.

the class ExtendExpirationFilterTest method getIdmJwtDto.

private IdmJwtAuthenticationDto getIdmJwtDto(MvcResult result) throws IOException {
    String extended = result.getResponse().getHeader(JwtAuthenticationMapper.AUTHENTICATION_TOKEN_NAME);
    Assert.assertNotNull(extended);
    Jwt decoded = JwtHelper.decode(extended);
    decoded.verifySignature(jwtMapper.getVerifier());
    IdmJwtAuthenticationDto extendedDto = jwtMapper.getClaims(decoded);
    return extendedDto;
}
Also used : Jwt(org.springframework.security.jwt.Jwt) IdmJwtAuthenticationDto(eu.bcvsolutions.idm.core.security.api.dto.IdmJwtAuthenticationDto)

Example 3 with Jwt

use of org.springframework.security.jwt.Jwt in project faf-java-server by FAForever.

the class UserService method login.

@SneakyThrows
@SuppressWarnings("unchecked")
public void login(String uniqueId, String jwtString) {
    Jwt jwt = JwtHelper.decodeAndVerify(jwtString, macSigner);
    Map<String, Object> claims = objectMapper.readValue(jwt.getClaims(), Map.class);
    Object userId = claims.get(KEY_USER_ID);
// Requests.verify(!playerService.isPlayerOnline(loginRequest.getLogin()), ErrorCode.USER_ALREADY_CONNECTED, loginRequest.getLogin());
// log.debug("Processing login request from user: {}", loginRequest.getLogin());
// try {
// UsernamePasswordAuthenticationToken token = new UsernamePasswordAuthenticationToken(loginRequest.getLogin(), loginRequest.getPassword());
// 
// Authentication authentication = authenticationManager.authenticate(token);
// FafUserDetails userDetails = (FafUserDetails) authentication.getPrincipal();
// 
// clientConnection.setAuthentication(authentication);
// Player player = userDetails.getPlayer();
// player.setClientConnection(clientConnection);
// geoIpService.lookupCountryCode(clientConnection.getClientAddress()).ifPresent(player::setCountry);
// 
// uniqueIdService.verify(player, loginRequest.getUniqueId());
// chatService.updateIrcPassword(userDetails.getUsername(), loginRequest.getPassword());
// 
// eventPublisher.publishEvent(new PlayerOnlineEvent(this, player));
// } catch (BadCredentialsException e) {
// throw new RequestException(e, ErrorCode.INVALID_LOGIN);
// }
}
Also used : Jwt(org.springframework.security.jwt.Jwt) SneakyThrows(lombok.SneakyThrows)

Example 4 with Jwt

use of org.springframework.security.jwt.Jwt in project sw360portal by sw360.

the class IntegrationTestBase method checkJwtClaims.

protected JsonNode checkJwtClaims(ResponseEntity<String> responseEntity, String expectedAuthority) throws IOException {
    String responseBody = responseEntity.getBody();
    assertThat(HttpStatus.OK, is(responseEntity.getStatusCode()));
    JsonNode responseBodyJsonNode = new ObjectMapper().readTree(responseBody);
    assertThat(responseBodyJsonNode.has("access_token"), is(true));
    String accessToken = responseBodyJsonNode.get("access_token").asText();
    Jwt jwt = JwtHelper.decode(accessToken);
    String jwtClaims = jwt.getClaims();
    JsonNode jwtClaimsJsonNode = new ObjectMapper().readTree(jwtClaims);
    assertThat(jwtClaimsJsonNode.get("aud").get(0).asText(), is("sw360-REST-API"));
    assertThat(jwtClaimsJsonNode.get("client_id").asText(), is("trusted-sw360-client"));
    JsonNode scopeNode = jwtClaimsJsonNode.get("scope");
    assertThat(scopeNode.get(0).asText(), is("all"));
    assertThat(scopeNode.size(), is(1));
    JsonNode authoritiesJsonNode = jwtClaimsJsonNode.get("authorities");
    assertThat(authoritiesJsonNode.get(0).asText(), is(expectedAuthority));
    return jwtClaimsJsonNode;
}
Also used : Jwt(org.springframework.security.jwt.Jwt) JsonNode(com.fasterxml.jackson.databind.JsonNode) ObjectMapper(com.fasterxml.jackson.databind.ObjectMapper)

Example 5 with Jwt

use of org.springframework.security.jwt.Jwt in project cloudbreak by hortonworks.

the class CachedRemoteTokenService method getSSOAuthentication.

private OAuth2Authentication getSSOAuthentication(String accessToken) {
    try {
        SignatureVerifier verifier = isAssymetricKey(jwtSignKey) ? new RsaVerifier(jwtSignKey) : new MacSigner(jwtSignKey);
        Jwt jwt = JwtHelper.decodeAndVerify(accessToken, verifier);
        Map<String, Object> claims = objectMapper.readValue(jwt.getClaims(), new MapTypeReference());
        Object userClaim = claims.get("user");
        Map<String, Object> tokenMap = new HashMap<>();
        Map<String, Object> userMap = objectMapper.readValue(userClaim.toString(), new MapTypeReference());
        String exp = claims.get("exp").toString();
        tokenMap.put("exp", Long.valueOf(exp));
        Object email = userMap.get("email");
        tokenMap.put("user_id", email);
        tokenMap.put("user_name", email);
        tokenMap.put("scope", Arrays.asList("cloudbreak.networks.read", "periscope.cluster", "cloudbreak.usages.user", "cloudbreak.recipes", "openid", "cloudbreak.templates.read", "cloudbreak.usages.account", "cloudbreak.events", "cloudbreak.stacks.read", "cloudbreak.blueprints", "cloudbreak.networks", "cloudbreak.templates", "cloudbreak.credentials.read", "cloudbreak.securitygroups.read", "cloudbreak.securitygroups", "cloudbreak.stacks", "cloudbreak.credentials", "cloudbreak.recipes.read", "cloudbreak.blueprints.read"));
        OAuth2AccessToken oAuth2AccessToken = jwtAccessTokenConverter.extractAccessToken(accessToken, tokenMap);
        if (oAuth2AccessToken.isExpired()) {
            throw new InvalidTokenException("The token has expired");
        }
        OAuth2Authentication oAuth2Authentication = jwtAccessTokenConverter.extractAuthentication(tokenMap);
        if (oAuth2Authentication != null) {
            LOGGER.info("JWT token verified for: {}", oAuth2Authentication.getPrincipal());
        }
        return oAuth2Authentication;
    } catch (IOException e) {
        LOGGER.error("Failed to parse the JWT token", e);
        throw new InvalidTokenException("The specified JWT token is invalid", e);
    }
}
Also used : InvalidTokenException(org.springframework.security.oauth2.common.exceptions.InvalidTokenException) HashMap(java.util.HashMap) Jwt(org.springframework.security.jwt.Jwt) IOException(java.io.IOException) RsaVerifier(org.springframework.security.jwt.crypto.sign.RsaVerifier) MacSigner(org.springframework.security.jwt.crypto.sign.MacSigner) OAuth2AccessToken(org.springframework.security.oauth2.common.OAuth2AccessToken) OAuth2Authentication(org.springframework.security.oauth2.provider.OAuth2Authentication) SignatureVerifier(org.springframework.security.jwt.crypto.sign.SignatureVerifier)

Aggregations

Jwt (org.springframework.security.jwt.Jwt)11 IOException (java.io.IOException)3 InvalidTokenException (org.springframework.security.oauth2.common.exceptions.InvalidTokenException)3 ObjectMapper (com.fasterxml.jackson.databind.ObjectMapper)2 IdmJwtAuthenticationDto (eu.bcvsolutions.idm.core.security.api.dto.IdmJwtAuthenticationDto)2 AuthenticationException (org.springframework.security.core.AuthenticationException)2 MacSigner (org.springframework.security.jwt.crypto.sign.MacSigner)2 SignatureVerifier (org.springframework.security.jwt.crypto.sign.SignatureVerifier)2 OAuth2AccessToken (org.springframework.security.oauth2.common.OAuth2AccessToken)2 Server (com.faforever.server.config.ServerProperties.Ice.Server)1 JsonNode (com.fasterxml.jackson.databind.JsonNode)1 IdmIdentityDto (eu.bcvsolutions.idm.core.api.dto.IdmIdentityDto)1 ResultCodeException (eu.bcvsolutions.idm.core.api.exception.ResultCodeException)1 IdmJwtAuthentication (eu.bcvsolutions.idm.core.security.api.domain.IdmJwtAuthentication)1 HashMap (java.util.HashMap)1 Map (java.util.Map)1 ServletException (javax.servlet.ServletException)1 ValidationException (javax.validation.ValidationException)1 SneakyThrows (lombok.SneakyThrows)1 DateTime (org.joda.time.DateTime)1