Search in sources :

Example 6 with Tokens

use of com.auth0.Tokens in project auth0-java-mvc-common by auth0.

the class RequestProcessorTest method shouldReturnTokensOnProcessIfCodeRequestPassesIdTokenVerification.

@Test
public void shouldReturnTokensOnProcessIfCodeRequestPassesIdTokenVerification() throws Exception {
    doNothing().when(tokenVerifier).verify(eq("backIdToken"), eq(verifyOptions));
    Map<String, Object> params = new HashMap<>();
    params.put("code", "abc123");
    params.put("state", "1234");
    MockHttpServletRequest request = getRequest(params);
    request.setCookies(new Cookie("com.auth0.state", "1234"));
    TokenRequest codeExchangeRequest = mock(TokenRequest.class);
    TokenHolder tokenHolder = mock(TokenHolder.class);
    when(tokenHolder.getIdToken()).thenReturn("backIdToken");
    when(tokenHolder.getAccessToken()).thenReturn("backAccessToken");
    when(tokenHolder.getRefreshToken()).thenReturn("backRefreshToken");
    when(codeExchangeRequest.execute()).thenReturn(tokenHolder);
    when(client.exchangeCode("abc123", "https://me.auth0.com:80/callback")).thenReturn(codeExchangeRequest);
    RequestProcessor handler = new RequestProcessor.Builder(client, "code", verifyOptions).withIdTokenVerifier(tokenVerifier).build();
    Tokens tokens = handler.process(request, response);
    verify(tokenVerifier).verify("backIdToken", verifyOptions);
    verifyNoMoreInteractions(tokenVerifier);
    assertThat(tokens, is(notNullValue()));
    assertThat(tokens.getIdToken(), is("backIdToken"));
    assertThat(tokens.getAccessToken(), is("backAccessToken"));
    assertThat(tokens.getRefreshToken(), is("backRefreshToken"));
}
Also used : Cookie(javax.servlet.http.Cookie) HashMap(java.util.HashMap) MockHttpServletRequest(org.springframework.mock.web.MockHttpServletRequest) TokenRequest(com.auth0.net.TokenRequest) TokenHolder(com.auth0.json.auth.TokenHolder) Test(org.junit.jupiter.api.Test)

Example 7 with Tokens

use of com.auth0.Tokens in project auth0-java-mvc-common by auth0.

the class RequestProcessorTest method shouldReturnTokensOnProcessIfIdTokenCodeRequestPassesIdTokenVerification.

@Test
public void shouldReturnTokensOnProcessIfIdTokenCodeRequestPassesIdTokenVerification() throws Exception {
    doNothing().when(tokenVerifier).verify(eq("frontIdToken"), eq(verifyOptions));
    Map<String, Object> params = new HashMap<>();
    params.put("code", "abc123");
    params.put("state", "1234");
    params.put("id_token", "frontIdToken");
    params.put("expires_in", "8400");
    params.put("token_type", "frontTokenType");
    MockHttpServletRequest request = getRequest(params);
    request.setCookies(new Cookie("com.auth0.state", "1234"));
    TokenRequest codeExchangeRequest = mock(TokenRequest.class);
    TokenHolder tokenHolder = mock(TokenHolder.class);
    when(tokenHolder.getIdToken()).thenReturn("backIdToken");
    when(tokenHolder.getExpiresIn()).thenReturn(4800L);
    when(tokenHolder.getTokenType()).thenReturn("backTokenType");
    when(codeExchangeRequest.execute()).thenReturn(tokenHolder);
    when(client.exchangeCode("abc123", "https://me.auth0.com:80/callback")).thenReturn(codeExchangeRequest);
    RequestProcessor handler = new RequestProcessor.Builder(client, "id_token code", verifyOptions).withIdTokenVerifier(tokenVerifier).build();
    Tokens tokens = handler.process(request, response);
    // Should not verify the ID Token twice
    verify(tokenVerifier).verify("frontIdToken", verifyOptions);
    verify(tokenVerifier, never()).verify("backIdToken", verifyOptions);
    verifyNoMoreInteractions(tokenVerifier);
    assertThat(tokens, is(notNullValue()));
    assertThat(tokens.getIdToken(), is("frontIdToken"));
    assertThat(tokens.getType(), is("frontTokenType"));
    assertThat(tokens.getExpiresIn(), is(8400L));
}
Also used : Cookie(javax.servlet.http.Cookie) HashMap(java.util.HashMap) MockHttpServletRequest(org.springframework.mock.web.MockHttpServletRequest) TokenRequest(com.auth0.net.TokenRequest) TokenHolder(com.auth0.json.auth.TokenHolder) Test(org.junit.jupiter.api.Test)

Example 8 with Tokens

use of com.auth0.Tokens in project Gestion_Employee_SpringBoot_Angular by ibrahimesseddyq.

the class AuthFilter method successfulAuthentication.

@Override
protected void successfulAuthentication(HttpServletRequest request, HttpServletResponse response, FilterChain chain, Authentication authentication) throws IOException, ServletException {
    User user = (User) authentication.getPrincipal();
    Algorithm algorithm = Algorithm.HMAC256("secret".getBytes());
    String accessToken = JWT.create().withSubject(user.getUsername()).withExpiresAt(new Date(System.currentTimeMillis() + 6 * 60 * 60 * 1000)).withIssuer(request.getRequestURI().toString()).withClaim("roles", user.getAuthorities().stream().map(GrantedAuthority::getAuthority).collect(Collectors.toList())).sign(algorithm);
    String refreshToken = JWT.create().withSubject(user.getUsername()).withExpiresAt(new Date(System.currentTimeMillis() + 8 * 60 * 60 * 1000)).withIssuer(request.getRequestURI().toString()).withClaim("roles", user.getAuthorities().stream().map(GrantedAuthority::getAuthority).collect(Collectors.toList())).sign(algorithm);
    // response.setHeader("access_token",accessToken);
    // response.setHeader("refresh_token",refreshToken);
    Map<String, String> tokens = new HashMap<>();
    tokens.put("access_token", accessToken);
    tokens.put("refresh_token", refreshToken);
    response.setContentType(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 9 with Tokens

use of com.auth0.Tokens in project Automated-Parking-Lot by ParkingLotDevOps.

the class RoleToUserForm method refreshToken.

@GetMapping("/token/refresh")
public void refreshToken(HttpServletRequest request, HttpServletResponse response) throws IOException {
    String authorizationHeader = request.getHeader("Authorization");
    if (authorizationHeader != null && authorizationHeader.startsWith("Bearer ")) {
        try {
            String refresh_token = authorizationHeader.substring("Bearer ".length());
            // TODO : de mutat in fisier de configurare
            Algorithm algorithm = Algorithm.HMAC256("secret".getBytes());
            JWTVerifier verifier = JWT.require(algorithm).build();
            DecodedJWT decodedJWT = verifier.verify(refresh_token);
            String username = decodedJWT.getSubject();
            AppUser user = appUserService.getUser(username);
            String access_token = JWT.create().withSubject(user.getEmail()).withExpiresAt(new Date(System.currentTimeMillis() + 30 * 60 * 1000)).withIssuer(request.getRequestURL().toString()).withClaim("roles", user.getRoles().stream().map(Role::getName).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);
        } catch (Exception exception) {
            response.setHeader("error", exception.getMessage());
            response.setStatus(403);
            Map<String, String> error = new HashMap<>();
            error.put("error", exception.getMessage());
            response.setContentType("application/json");
            new ObjectMapper().writeValue(response.getOutputStream(), error);
        }
    }
}
Also used : AppUser(b3.spl.splb.model.AppUser) Algorithm(com.auth0.jwt.algorithms.Algorithm) JWTVerifier(com.auth0.jwt.JWTVerifier) DecodedJWT(com.auth0.jwt.interfaces.DecodedJWT) ObjectMapper(com.fasterxml.jackson.databind.ObjectMapper) IOException(java.io.IOException)

Example 10 with Tokens

use of com.auth0.Tokens 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)

Aggregations

DecodedJWT (com.auth0.jwt.interfaces.DecodedJWT)13 HashMap (java.util.HashMap)8 Test (org.junit.jupiter.api.Test)7 Algorithm (com.auth0.jwt.algorithms.Algorithm)6 TokenHolder (com.auth0.json.auth.TokenHolder)4 TokenRequest (com.auth0.net.TokenRequest)4 ObjectMapper (com.fasterxml.jackson.databind.ObjectMapper)4 Date (java.util.Date)4 JWT (com.auth0.jwt.JWT)3 JWTVerifier (com.auth0.jwt.JWTVerifier)3 ServiceAuthorizationException (com.nexblocks.authguard.service.exceptions.ServiceAuthorizationException)3 AccountBO (com.nexblocks.authguard.service.model.AccountBO)3 User (org.springframework.security.core.userdetails.User)3 JWTVerificationException (com.auth0.jwt.exceptions.JWTVerificationException)2 Claim (com.auth0.jwt.interfaces.Claim)2 JsonPath (com.jayway.jsonpath.JsonPath)2 ReadContext (com.jayway.jsonpath.ReadContext)2 JwtConfig (com.nexblocks.authguard.service.config.JwtConfig)2 StrategyConfig (com.nexblocks.authguard.service.config.StrategyConfig)2 AuthResponseBO (com.nexblocks.authguard.service.model.AuthResponseBO)2