Search in sources :

Example 21 with Role

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

the class JwtUtils 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 22 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 23 with Role

use of com.auth0.json.mgmt.Role 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 24 with Role

use of com.auth0.json.mgmt.Role in project framework by galasa-dev.

the class JwtAuthFilter method doFilter.

@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
    if (!(request instanceof HttpServletRequest)) {
        chain.doFilter(request, response);
        return;
    }
    HttpServletRequest servletRequest = (HttpServletRequest) request;
    HttpServletResponse servletResponse = (HttpServletResponse) response;
    if ("/auth".equals(servletRequest.getServletPath())) {
        // dont do this for the auth url
        chain.doFilter(request, response);
        return;
    }
    Principal principal = servletRequest.getUserPrincipal();
    if (principal != null) {
        // already authenticated
        chain.doFilter(request, response);
        return;
    }
    String authorization = servletRequest.getHeader("Authorization");
    if (authorization == null) {
        chain.doFilter(request, response);
        return;
    }
    StringTokenizer st = new StringTokenizer(authorization);
    if (!st.hasMoreTokens()) {
        chain.doFilter(request, response);
        return;
    }
    String bearer = st.nextToken();
    if (!"bearer".equalsIgnoreCase(bearer)) {
        chain.doFilter(request, response);
        return;
    }
    if (!st.hasMoreTokens()) {
        chain.doFilter(request, response);
        return;
    }
    String sJwt = st.nextToken();
    Algorithm algorithm = Algorithm.HMAC256(this.configurationProperties.getProperty(SECRET_KEY));
    JWTVerifier verifier = JWT.require(algorithm).withIssuer("galasa").build();
    try {
        DecodedJWT jwt = verifier.verify(sJwt);
        String subject = jwt.getSubject();
        String role = jwt.getClaim("role").asString();
        JwtRequestWrapper wrapper = new JwtRequestWrapper(subject, role, servletRequest);
        chain.doFilter(wrapper, servletResponse);
        return;
    } catch (AlgorithmMismatchException e) {
        chain.doFilter(request, response);
        invalidAuth(servletRequest, servletResponse, "Incorrect Algorithim " + e);
        return;
    } catch (SignatureVerificationException e) {
        chain.doFilter(request, response);
        invalidAuth(servletRequest, servletResponse, "Non valid signature " + e);
    } catch (TokenExpiredException e) {
        chain.doFilter(request, response);
        invalidAuth(servletRequest, servletResponse, "Jwt has expired " + e);
    } catch (InvalidClaimException e) {
        chain.doFilter(request, response);
        invalidAuth(servletRequest, servletResponse, "Invalid Claims " + e);
    }
// chain.doFilter(servletRequest, servletResponse);
}
Also used : HttpServletResponse(javax.servlet.http.HttpServletResponse) InvalidClaimException(com.auth0.jwt.exceptions.InvalidClaimException) Algorithm(com.auth0.jwt.algorithms.Algorithm) AlgorithmMismatchException(com.auth0.jwt.exceptions.AlgorithmMismatchException) HttpServletRequest(javax.servlet.http.HttpServletRequest) StringTokenizer(java.util.StringTokenizer) TokenExpiredException(com.auth0.jwt.exceptions.TokenExpiredException) SignatureVerificationException(com.auth0.jwt.exceptions.SignatureVerificationException) JWTVerifier(com.auth0.jwt.JWTVerifier) DecodedJWT(com.auth0.jwt.interfaces.DecodedJWT) Principal(java.security.Principal)

Example 25 with Role

use of com.auth0.json.mgmt.Role in project alf.io by alfio-event.

the class BaseOpenIdAuthenticationManager method updateRoles.

private void updateRoles(Set<Role> roles, String username) {
    authorityRepository.revokeAll(username);
    var rolesToAdd = roles.stream().map(r -> new MapSqlParameterSource("username", username).addValue("role", r.getRoleName())).toArray(MapSqlParameterSource[]::new);
    jdbcTemplate.batchUpdate(authorityRepository.grantAll(), rolesToAdd);
}
Also used : JWT(com.auth0.jwt.JWT) UriComponentsBuilder(org.springframework.web.util.UriComponentsBuilder) java.util(java.util) HttpUtils(alfio.util.HttpUtils) NamedParameterJdbcTemplate(org.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplate) SimpleGrantedAuthority(org.springframework.security.core.authority.SimpleGrantedAuthority) MapSqlParameterSource(org.springframework.jdbc.core.namedparam.MapSqlParameterSource) OpenIdAlfioAuthentication(alfio.config.authentication.support.OpenIdAlfioAuthentication) StringUtils(org.apache.commons.lang3.StringUtils) HttpRequest(java.net.http.HttpRequest) APPLICATION_FORM_URLENCODED(alfio.util.HttpUtils.APPLICATION_FORM_URLENCODED) Json(alfio.util.Json) HttpClient(java.net.http.HttpClient) URI(java.net.URI) TypeReference(com.fasterxml.jackson.core.type.TypeReference) Claim(com.auth0.jwt.interfaces.Claim) AuthorityRepository(alfio.repository.user.AuthorityRepository) HttpResponse(java.net.http.HttpResponse) HttpSession(javax.servlet.http.HttpSession) APPLICATION_JSON(alfio.util.HttpUtils.APPLICATION_JSON) OrganizationRepository(alfio.repository.user.OrganizationRepository) PasswordGenerator(alfio.util.PasswordGenerator) UserOrganizationRepository(alfio.repository.user.join.UserOrganizationRepository) Organization(alfio.model.user.Organization) User(alfio.model.user.User) OpenIdAlfioUser(alfio.config.authentication.support.OpenIdAlfioUser) Collectors(java.util.stream.Collectors) GrantedAuthority(org.springframework.security.core.GrantedAuthority) Role(alfio.model.user.Role) PasswordEncoder(org.springframework.security.crypto.password.PasswordEncoder) UserRepository(alfio.repository.user.UserRepository) UserManager(alfio.manager.user.UserManager) Log4j2(lombok.extern.log4j.Log4j2) UriComponents(org.springframework.web.util.UriComponents) MapSqlParameterSource(org.springframework.jdbc.core.namedparam.MapSqlParameterSource)

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