Search in sources :

Example 56 with User

use of com.auth0.flickr2.domain.User in project Automated-Parking-Lot by ParkingLotDevOps.

the class CustomAuthenticationFilter method successfulAuthentication.

@Override
protected void successfulAuthentication(HttpServletRequest request, HttpServletResponse response, FilterChain chain, Authentication authentication) throws IOException, ServletException {
    User user = (User) authentication.getPrincipal();
    // TODO : de adaugat cheia intr-un fisier de configurare
    Algorithm algorithm = Algorithm.HMAC256("secret".getBytes());
    String access_token = JWT.create().withSubject(request.getParameter("email")).withExpiresAt(new Date(System.currentTimeMillis() + 30 * 10 * 1000)).withIssuer(request.getRequestURL().toString()).withClaim("roles", user.getAuthorities().stream().map(GrantedAuthority::getAuthority).collect(Collectors.toList())).sign(algorithm);
    String refresh_token = JWT.create().withSubject(request.getParameter("email")).withExpiresAt(new Date(System.currentTimeMillis() + 24 * 60 * 60 * 1000)).withIssuer(request.getRequestURL().toString()).withClaim("roles", user.getAuthorities().stream().map(GrantedAuthority::getAuthority).collect(Collectors.toList())).sign(algorithm);
    Map<String, String> tokens = new HashMap<>();
    tokens.put("access_token", access_token);
    tokens.put("refresh_token", refresh_token);
    response.setContentType("application/json");
    new ObjectMapper().writeValue(response.getOutputStream(), tokens);
}
Also used : User(org.springframework.security.core.userdetails.User) HashMap(java.util.HashMap) Algorithm(com.auth0.jwt.algorithms.Algorithm) Date(java.util.Date) ObjectMapper(com.fasterxml.jackson.databind.ObjectMapper)

Example 57 with User

use of com.auth0.flickr2.domain.User in project tanafaso-backend by tanafaso.

the class ApiAuthenticationController method validateAppleAuthCode.

private boolean validateAppleAuthCode(AppleAuthenticationRequest request) {
    Map<String, Object> appleApiRequestHeader = new HashMap<>();
    appleApiRequestHeader.put("alg", "ES256");
    appleApiRequestHeader.put("kid", appleSignInKeyId);
    appleApiRequestHeader.put("typ", "JWT");
    InputStreamReader appleAuthPrivateKeyInputStreamReader;
    try {
        appleAuthPrivateKeyInputStreamReader = new InputStreamReader(new ClassPathResource(appleAuthPrivateKeyFile).getInputStream());
    } catch (IOException e) {
        logger.error("Couldn't read the apple authorization private key file.", e);
        return false;
    }
    ECPrivateKey privateKey;
    try {
        PemObject pemObject;
        pemObject = new PemReader(appleAuthPrivateKeyInputStreamReader).readPemObject();
        PKCS8EncodedKeySpec spec = new PKCS8EncodedKeySpec(pemObject.getContent());
        KeyFactory factory;
        factory = KeyFactory.getInstance("EC");
        privateKey = (ECPrivateKey) factory.generatePrivate(spec);
    } catch (Exception e) {
        logger.error("Could not convert Apple private key into an EC key.", e);
        return false;
    }
    String signedJwt = JWT.create().withHeader(appleApiRequestHeader).withIssuer(appleTeamId).withIssuedAt(new Date(System.currentTimeMillis())).withExpiresAt(new Date(System.currentTimeMillis() + TimeUnit.MINUTES.toMillis(10))).withAudience("https://appleid.apple.com").withSubject("com.tanafaso.azkar").sign(Algorithm.ECDSA256(privateKey));
    HttpHeaders headers = new HttpHeaders();
    headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);
    MultiValueMap<String, String> map = new LinkedMultiValueMap<String, String>();
    map.add("client_id", "com.tanafaso.azkar");
    map.add("client_secret", signedJwt);
    map.add("code", request.getAuthCode());
    map.add("grant_type", "authorization_code");
    HttpEntity<MultiValueMap<String, String>> appleApiRequestHttpEntity = new HttpEntity<>(map, headers);
    logger.info("Sending to Apple auth code verification API.");
    ResponseEntity<AppleIdToken> appleIdToken = restTemplate.postForEntity("https://appleid.apple.com/auth/token", appleApiRequestHttpEntity, AppleIdToken.class);
    if (appleIdToken.getStatusCode() == HttpStatus.OK) {
        DecodedJWT decodedJwt = JWT.decode(appleIdToken.getBody().getIdToken());
        boolean emailIsVerified = decodedJwt.getClaim("email_verified").asString().equals("true");
        String potentiallyVerifiedEmail = decodedJwt.getClaim("email").asString().toLowerCase();
        if (emailIsVerified && potentiallyVerifiedEmail.equals(request.getEmail())) {
            return true;
        }
        logger.info("Failed to verify user signing in with apple: email={}, firstName={}, " + "lastName={}, emailIsVerified={}, appleApiReturnedEmail={}", request.getEmail(), request.getFirstName(), request.getLastName(), emailIsVerified, potentiallyVerifiedEmail);
        return false;
    }
    logger.info("Failed to verify user signing in with apple as apple API returned status code: " + "{} for email={}, firstName={}, lastName={}", appleIdToken.getStatusCode().toString(), request.getEmail(), request.getFirstName(), request.getLastName());
    return false;
}
Also used : ECPrivateKey(java.security.interfaces.ECPrivateKey) HttpHeaders(org.springframework.http.HttpHeaders) InputStreamReader(java.io.InputStreamReader) HttpEntity(org.springframework.http.HttpEntity) HashMap(java.util.HashMap) LinkedMultiValueMap(org.springframework.util.LinkedMultiValueMap) IOException(java.io.IOException) ClassPathResource(org.springframework.core.io.ClassPathResource) MessagingException(javax.mail.MessagingException) UnsupportedEncodingException(java.io.UnsupportedEncodingException) IOException(java.io.IOException) Date(java.util.Date) PemObject(org.bouncycastle.util.io.pem.PemObject) PemReader(org.bouncycastle.util.io.pem.PemReader) PKCS8EncodedKeySpec(java.security.spec.PKCS8EncodedKeySpec) PemObject(org.bouncycastle.util.io.pem.PemObject) DecodedJWT(com.auth0.jwt.interfaces.DecodedJWT) KeyFactory(java.security.KeyFactory) MultiValueMap(org.springframework.util.MultiValueMap) LinkedMultiValueMap(org.springframework.util.LinkedMultiValueMap)

Example 58 with User

use of com.auth0.flickr2.domain.User in project UPE_2021_2_Propague by netrometro.

the class AuthenticationCustomFilter method successfulAuthentication.

@Override
protected void successfulAuthentication(HttpServletRequest request, HttpServletResponse response, FilterChain chain, Authentication autenticacao) throws IOException, ServletException {
    User user = (User) autenticacao.getPrincipal();
    Algorithm algoritmo = Algorithm.HMAC256("secret".getBytes());
    String tokenAcesso = JWT.create().withSubject(user.getUsername()).withExpiresAt(new Date(System.currentTimeMillis() + 10 * 60 * 1000)).withIssuer(request.getRequestURL().toString()).withClaim("tipos", user.getAuthorities().stream().map(GrantedAuthority::getAuthority).collect(Collectors.toList())).sign(algoritmo);
    String tokenRefresh = JWT.create().withSubject(user.getUsername()).withExpiresAt(new Date(System.currentTimeMillis() + 30 * 60 * 1000)).withIssuer(request.getRequestURL().toString()).sign(algoritmo);
    Map<String, String> tokens = new HashMap<>();
    tokens.put("token_acesso", tokenAcesso);
    tokens.put("token_refresh", tokenRefresh);
    tokens.put("email_usuario", user.getUsername());
    response.setContentType(MediaType.APPLICATION_JSON_VALUE);
    new ObjectMapper().writeValue(response.getOutputStream(), tokens);
}
Also used : User(org.springframework.security.core.userdetails.User) HashMap(java.util.HashMap) Algorithm(com.auth0.jwt.algorithms.Algorithm) Date(java.util.Date) ObjectMapper(com.fasterxml.jackson.databind.ObjectMapper)

Example 59 with User

use of com.auth0.flickr2.domain.User in project iris-client by iris-connect.

the class JWTAuthorizationFilter method authenticate.

/**
 * This method is called if the user supplied a jwt token.
 *
 * @param token JSON Web Token
 * @return
 */
private UserAccountAuthentication authenticate(String token) {
    DecodedJWT jwt = jwtVerifier.verify(token);
    var userName = jwt.getSubject();
    var userAccount = userService.findByUsername(userName);
    if (userAccount.isPresent() && jwtVerifier.isTokenWhitelisted(token)) {
        var authority = new SimpleGrantedAuthority(jwt.getClaim(JWT_CLAIM_USER_ROLE).asString());
        return new UserAccountAuthentication(userAccount.get(), true, List.of(authority));
    }
    return null;
}
Also used : SimpleGrantedAuthority(org.springframework.security.core.authority.SimpleGrantedAuthority) DecodedJWT(com.auth0.jwt.interfaces.DecodedJWT)

Example 60 with User

use of com.auth0.flickr2.domain.User in project openware by open-inc.

the class UserService method jwtToUser.

public User jwtToUser(String token) {
    if (jwtVerifier == null)
        return null;
    try {
        DecodedJWT userJWT = jwtVerifier.verify(token);
        Claim userid = userJWT.getClaim("uid");
        if (!userid.isNull())
            return getUserByUID(userid.asString());
        Claim username = userJWT.getClaim("username");
        if (!username.isNull())
            return getUserByUsername(username.asString());
        Claim usermail = userJWT.getClaim("usermail");
        if (!usermail.isNull())
            return getActiveUsers().stream().filter(new Predicate<User>() {

                @Override
                public boolean test(User t) {
                    return t.getEmail().toLowerCase().equals(usermail.asString().toLowerCase());
                }
            }).findFirst().get();
        return null;
    } catch (JWTVerificationException e) {
        return null;
    }
}
Also used : JWTVerificationException(com.auth0.jwt.exceptions.JWTVerificationException) User(de.openinc.model.user.User) DecodedJWT(com.auth0.jwt.interfaces.DecodedJWT) Claim(com.auth0.jwt.interfaces.Claim) Predicate(java.util.function.Predicate)

Aggregations

Algorithm (com.auth0.jwt.algorithms.Algorithm)64 DecodedJWT (com.auth0.jwt.interfaces.DecodedJWT)60 IOException (java.io.IOException)51 Test (org.junit.Test)46 JWT (com.auth0.jwt.JWT)42 Instant (java.time.Instant)39 java.util (java.util)37 Duration (java.time.Duration)36 TechnicalException (io.gravitee.repository.exceptions.TechnicalException)35 Maps (io.gravitee.common.util.Maps)34 DEFAULT_JWT_ISSUER (io.gravitee.rest.api.service.common.JWTHelper.DefaultValues.DEFAULT_JWT_ISSUER)34 User (io.gravitee.repository.management.model.User)33 ConfigurableEnvironment (org.springframework.core.env.ConfigurableEnvironment)32 UserRepository (io.gravitee.repository.management.api.UserRepository)30 io.gravitee.rest.api.model (io.gravitee.rest.api.model)30 JWTVerifier (com.auth0.jwt.JWTVerifier)28 MetadataPage (io.gravitee.common.data.domain.MetadataPage)28 MembershipRepository (io.gravitee.repository.management.api.MembershipRepository)28 Membership (io.gravitee.repository.management.model.Membership)28 UserStatus (io.gravitee.repository.management.model.UserStatus)28