Search in sources :

Example 46 with Role

use of com.auth0.json.mgmt.Role in project toy by gmoon92.

the class JwtUtil method decode.

public User decode(String tokenOfIncludeSchema) {
    String token = obtainTokenWithoutSchema(tokenOfIncludeSchema);
    verify(token);
    DecodedJWT jwt = JWT.decode(token);
    String username = jwt.getClaim("username").asString();
    Role role = Role.valueOf(jwt.getClaim("role").asString());
    return User.create(username, "", role);
}
Also used : Role(com.gmoon.springsecurityjwt.user.Role) DecodedJWT(com.auth0.jwt.interfaces.DecodedJWT)

Example 47 with Role

use of com.auth0.json.mgmt.Role in project Automated-Parking-Lot by ParkingLotDevOps.

the class CustomAuthorizationFilter method doFilterInternal.

@Override
protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
    if (request.getServletPath().equals("/api/login") || request.getServletPath().equals("/api/user/save") || request.getServletPath().equals("/api/token/refresh")) {
        filterChain.doFilter(request, response);
    } else {
        String authorizationHeader = request.getHeader("Authorization");
        if (authorizationHeader != null && authorizationHeader.startsWith("Bearer ")) {
            try {
                String 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(token);
                String username = decodedJWT.getSubject();
                String[] roles = decodedJWT.getClaim("roles").asArray(String.class);
                Collection<SimpleGrantedAuthority> authorities = new ArrayList<>();
                stream(roles).forEach(role -> {
                    authorities.add(new SimpleGrantedAuthority(role));
                });
                UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(username, null, authorities);
                SecurityContextHolder.getContext().setAuthentication(authenticationToken);
                filterChain.doFilter(request, response);
            } catch (Exception exception) {
                log.error("Error logginn in : {}", exception.getMessage());
                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);
            }
        } else {
            filterChain.doFilter(request, response);
        }
    }
}
Also used : ArrayList(java.util.ArrayList) UsernamePasswordAuthenticationToken(org.springframework.security.authentication.UsernamePasswordAuthenticationToken) Algorithm(com.auth0.jwt.algorithms.Algorithm) ServletException(javax.servlet.ServletException) IOException(java.io.IOException) SimpleGrantedAuthority(org.springframework.security.core.authority.SimpleGrantedAuthority) JWTVerifier(com.auth0.jwt.JWTVerifier) DecodedJWT(com.auth0.jwt.interfaces.DecodedJWT) HashMap(java.util.HashMap) Map(java.util.Map) ObjectMapper(com.fasterxml.jackson.databind.ObjectMapper)

Example 48 with Role

use of com.auth0.json.mgmt.Role in project iet-hf-2022-k-k-k-k-k-k by BME-MIT-IET.

the class JwtAuthorizationFilter method doFilterInternal.

@Override
protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
    if (request.getServletPath().equals("/api/login") || request.getServletPath().equals("/api/hasRightForPage") || request.getServletPath().equals("/api/person/register")) {
        filterChain.doFilter(request, response);
    } else {
        String authorizationHeader = request.getHeader(HttpHeaders.AUTHORIZATION);
        if (authorizationHeader != null && authorizationHeader.startsWith("Bearer ")) {
            try {
                DecodedJWT decodedJWT = JwtUtil.getDecodedJWT(authorizationHeader);
                String username = decodedJWT.getSubject();
                String[] roles = decodedJWT.getClaim("roles").asArray(String.class);
                Collection<SimpleGrantedAuthority> authorities = new ArrayList<>();
                stream(roles).forEach(role -> {
                    authorities.add(new SimpleGrantedAuthority(role));
                });
                UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(username, null, authorities);
                SecurityContextHolder.getContext().setAuthentication(authenticationToken);
                filterChain.doFilter(request, response);
            } catch (Exception e) {
                response.setHeader("error", e.getMessage());
                response.setStatus(HttpStatus.FORBIDDEN.value());
                response.setContentType(MediaType.APPLICATION_JSON_VALUE);
                Map<String, String> error = new HashMap<>();
                error.put("error_message", e.getMessage());
                new ObjectMapper().writeValue(response.getOutputStream(), error);
            }
        } else {
            filterChain.doFilter(request, response);
        }
    }
}
Also used : SimpleGrantedAuthority(org.springframework.security.core.authority.SimpleGrantedAuthority) ArrayList(java.util.ArrayList) UsernamePasswordAuthenticationToken(org.springframework.security.authentication.UsernamePasswordAuthenticationToken) DecodedJWT(com.auth0.jwt.interfaces.DecodedJWT) HashMap(java.util.HashMap) Map(java.util.Map) ServletException(javax.servlet.ServletException) IOException(java.io.IOException) ObjectMapper(com.fasterxml.jackson.databind.ObjectMapper)

Example 49 with Role

use of com.auth0.json.mgmt.Role in project eagle-oj-api by Eagle-OJ.

the class JWTUtil method decode.

public static boolean decode(String token, String secret) {
    try {
        Algorithm algorithm = Algorithm.HMAC256(secret);
        JWTVerifier verifier = JWT.require(algorithm).build();
        DecodedJWT decodedJWT = verifier.verify(token);
        int uid = decodedJWT.getClaim("uid").asInt();
        int role = decodedJWT.getClaim("role").asInt();
        Set<String> permission = new HashSet<>(decodedJWT.getClaim("permission").asList(String.class));
        SessionHelper.init(token, uid, role, permission);
        return true;
    } catch (Exception e) {
        return false;
    }
}
Also used : Algorithm(com.auth0.jwt.algorithms.Algorithm) JWTVerifier(com.auth0.jwt.JWTVerifier) DecodedJWT(com.auth0.jwt.interfaces.DecodedJWT) JWTDecodeException(com.auth0.jwt.exceptions.JWTDecodeException) HashSet(java.util.HashSet)

Example 50 with Role

use of com.auth0.json.mgmt.Role in project eagle-oj-api by Eagle-OJ.

the class JWTUtil method sign.

public static String sign(int uid, int role, Set<String> permission, String secret) {
    try {
        Date date = new Date(System.currentTimeMillis() + EXPIRE);
        Algorithm algorithm = Algorithm.HMAC256(secret);
        return JWT.create().withClaim("uid", uid).withClaim("role", role).withArrayClaim("permission", permission.toArray(new String[1])).withExpiresAt(date).sign(algorithm);
    } catch (Exception e) {
        e.printStackTrace();
        return null;
    }
}
Also used : Algorithm(com.auth0.jwt.algorithms.Algorithm) Date(java.util.Date) JWTDecodeException(com.auth0.jwt.exceptions.JWTDecodeException)

Aggregations

Algorithm (com.auth0.jwt.algorithms.Algorithm)20 DecodedJWT (com.auth0.jwt.interfaces.DecodedJWT)17 IOException (java.io.IOException)17 java.util (java.util)14 JWT (com.auth0.jwt.JWT)13 Maps (io.gravitee.common.util.Maps)12 DEFAULT_JWT_ISSUER (io.gravitee.rest.api.service.common.JWTHelper.DefaultValues.DEFAULT_JWT_ISSUER)12 Duration (java.time.Duration)12 Instant (java.time.Instant)12 GraviteeContext (io.gravitee.rest.api.service.common.GraviteeContext)10 JWTHelper (io.gravitee.rest.api.service.common.JWTHelper)10 HttpServletResponse (javax.servlet.http.HttpServletResponse)10 Authentication (org.springframework.security.core.Authentication)10 ObjectMapper (com.fasterxml.jackson.databind.ObjectMapper)9 HashMap (java.util.HashMap)9 Collectors (java.util.stream.Collectors)9 Cookie (javax.servlet.http.Cookie)9 SecurityContextHolder (org.springframework.security.core.context.SecurityContextHolder)9 UserDetails (io.gravitee.rest.api.idp.api.authentication.UserDetails)8 CookieGenerator (io.gravitee.rest.api.security.cookies.CookieGenerator)8