Search in sources :

Example 51 with User

use of com.auth0.flickr2.domain.User in project toy by gmoon92.

the class JwtVerifyFilter method doFilterInternal.

@Override
protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain chain) throws IOException, ServletException {
    String token = getToken(request);
    try {
        User user = jwtUtils.decode(token);
        Authentication authentication = new UsernamePasswordAuthenticationToken(user, null, user.getAuthorities());
        SecurityContextHolder.getContext().setAuthentication(authentication);
        chain.doFilter(request, response);
    } catch (JWTVerificationException e) {
        SecurityContextHolder.clearContext();
        getAuthenticationEntryPoint().commence(request, response, new JwtVerifyException(e));
    }
}
Also used : JWTVerificationException(com.auth0.jwt.exceptions.JWTVerificationException) JwtVerifyException(com.gmoon.resourceserver.jwt.exception.JwtVerifyException) User(com.gmoon.resourceserver.user.User) Authentication(org.springframework.security.core.Authentication) UsernamePasswordAuthenticationToken(org.springframework.security.authentication.UsernamePasswordAuthenticationToken)

Example 52 with User

use of com.auth0.flickr2.domain.User in project toy by gmoon92.

the class JwtUtil method generate.

public String generate(User user) {
    try {
        ZonedDateTime today = ZonedDateTime.now();
        String token = JWT.create().withIssuer(apiVersion).withClaim("username", user.getUsername()).withClaim("role", user.getRole().name()).withIssuedAt(Date.from(today.toInstant())).withExpiresAt(Date.from(today.plusDays(DAY_OF_EXPIRATION).toInstant())).sign(algorithm);
        return String.format("%s %s", AuthenticationSchema.BEARER.getName(), token);
    } catch (JWTCreationException e) {
        throw new JWTCreationException("Invalid Signing configuration or Couldn't convert Claims.", e);
    }
}
Also used : ZonedDateTime(java.time.ZonedDateTime) JWTCreationException(com.auth0.jwt.exceptions.JWTCreationException)

Example 53 with User

use of com.auth0.flickr2.domain.User in project toy by gmoon92.

the class JwtVerifyFilter method doFilterInternal.

@Override
protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain chain) throws IOException, ServletException {
    String token = request.getHeader(JwtAuthenticationFilter.HEADER_NAME);
    try {
        User user = jwtUtil.decode(token);
        Authentication authentication = new UsernamePasswordAuthenticationToken(user, null, user.getAuthorities());
        SecurityContextHolder.getContext().setAuthentication(authentication);
        chain.doFilter(request, response);
    } catch (JWTVerificationException e) {
        SecurityContextHolder.clearContext();
        getAuthenticationEntryPoint().commence(request, response, new JwtVerifyException(e));
    }
}
Also used : JWTVerificationException(com.auth0.jwt.exceptions.JWTVerificationException) JwtVerifyException(com.gmoon.springsecurityjwt.jwt.exception.JwtVerifyException) User(com.gmoon.springsecurityjwt.user.User) Authentication(org.springframework.security.core.Authentication) UsernamePasswordAuthenticationToken(org.springframework.security.authentication.UsernamePasswordAuthenticationToken)

Example 54 with User

use of com.auth0.flickr2.domain.User in project learn-center-rest by elbar-org.

the class AuthTokenServiceImpl method refreshToken.

@Override
public void refreshToken(HttpServletRequest request, HttpServletResponse response) throws IOException {
    String authorizationHeader = request.getHeader(HttpHeaders.AUTHORIZATION);
    if (authorizationHeader != null && authorizationHeader.startsWith("Bearer ")) {
        try {
            String refreshToken = authorizationHeader.substring("Bearer ".length());
            DecodedJWT jwt = JWTUtils.getVerifier().verify(refreshToken);
            String userCode = jwt.getSubject();
            AuthUser user = authUserRepository.findByCode(UUID.fromString(userCode));
            Date accessDate = JWTUtils.getExpiry();
            String accessToken = JWT.create().withSubject(user.getCode().toString()).withExpiresAt(accessDate).withIssuer(request.getRequestURL().toString()).withClaim("roles", authUserRepository.getRolesByCode(UUID.fromString(userCode))).sign(JWTUtils.getAlgorithm());
            AuthTokenCreateDTO tokenCreateDTO = new AuthTokenCreateDTO(UUID.fromString(userCode), accessToken, accessDate, AuthTokenTypeEnum.ACCESS_TOKEN.name());
            create(tokenCreateDTO);
            AuthTokenGetDTO tokenGetDTO1 = new AuthTokenGetDTO(AuthTokenTypeEnum.ACCESS_TOKEN.name(), accessToken);
            AuthTokenGetDTO tokenGetDTO2 = new AuthTokenGetDTO(AuthTokenTypeEnum.REFRESH_TOKEN.name(), refreshToken);
            List<AuthTokenGetDTO> tokenGetDTOList = new ArrayList<>();
            tokenGetDTOList.add(tokenGetDTO1);
            tokenGetDTOList.add(tokenGetDTO2);
            response.setContentType(MediaType.APPLICATION_JSON_VALUE);
            new ObjectMapper().writeValue(response.getOutputStream(), tokenGetDTOList);
        } catch (Exception e) {
            response.setHeader("error", e.getMessage());
            response.setStatus(HttpStatus.FORBIDDEN.value());
            Map<String, String> error = new HashMap<>();
            error.put("error_message", e.getMessage());
            response.setContentType(MediaType.APPLICATION_JSON_VALUE);
            new ObjectMapper().writeValue(response.getOutputStream(), error);
        }
    } else {
        throw new RuntimeException("Refresh token is missing");
    }
}
Also used : AuthUser(elbar.company.learn_center_rest.entity.auth.user.AuthUser) IOException(java.io.IOException) AuthTokenCreateDTO(elbar.company.learn_center_rest.dto.auth.token.AuthTokenCreateDTO) AuthTokenGetDTO(elbar.company.learn_center_rest.dto.auth.token.AuthTokenGetDTO) DecodedJWT(com.auth0.jwt.interfaces.DecodedJWT) ObjectMapper(com.fasterxml.jackson.databind.ObjectMapper)

Example 55 with User

use of com.auth0.flickr2.domain.User 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)

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