Search in sources :

Example 81 with SignedJWT

use of com.nimbusds.jwt.SignedJWT in project spring-security by spring-projects.

the class NimbusReactiveJwtDecoderTests method signedJwt.

private SignedJWT signedJwt(SecretKey secretKey, MacAlgorithm jwsAlgorithm, JWTClaimsSet claimsSet) throws Exception {
    SignedJWT signedJWT = new SignedJWT(new JWSHeader(JWSAlgorithm.parse(jwsAlgorithm.getName())), claimsSet);
    JWSSigner signer = new MACSigner(secretKey);
    signedJWT.sign(signer);
    return signedJWT;
}
Also used : MACSigner(com.nimbusds.jose.crypto.MACSigner) SignedJWT(com.nimbusds.jwt.SignedJWT) JWSSigner(com.nimbusds.jose.JWSSigner) JWSHeader(com.nimbusds.jose.JWSHeader)

Example 82 with SignedJWT

use of com.nimbusds.jwt.SignedJWT in project oxAuth by GluuFederation.

the class CrossEncryptionTest method decryptAndValidateSignatureWithNimbus.

private void decryptAndValidateSignatureWithNimbus(String jweString) throws ParseException, JOSEException {
    JWK jwk = JWK.parse(recipientJwkJson);
    RSAPrivateKey rsaPrivateKey = ((RSAKey) jwk).toRSAPrivateKey();
    JWEObject jweObject = JWEObject.parse(jweString);
    jweObject.decrypt(new RSADecrypter(rsaPrivateKey));
    SignedJWT signedJWT = jweObject.getPayload().toSignedJWT();
    assertNotNull("Payload not a signed JWT", signedJWT);
    RSAKey senderJWK = (RSAKey) JWK.parse(senderJwkJson);
    assertTrue(signedJWT.verify(new RSASSAVerifier(senderJWK)));
    assertEquals("testing", signedJWT.getJWTClaimsSet().getSubject());
    System.out.println("Nimbus decrypt and nested jwt signature verification succeed: " + signedJWT.getJWTClaimsSet().toJSONObject());
}
Also used : RSAKey(com.nimbusds.jose.jwk.RSAKey) RSASSAVerifier(com.nimbusds.jose.crypto.RSASSAVerifier) SignedJWT(com.nimbusds.jwt.SignedJWT) RSAPrivateKey(java.security.interfaces.RSAPrivateKey) JWK(com.nimbusds.jose.jwk.JWK) RSADecrypter(com.nimbusds.jose.crypto.RSADecrypter)

Example 83 with SignedJWT

use of com.nimbusds.jwt.SignedJWT in project zeppelin by apache.

the class KnoxJwtRealm method validateToken.

protected boolean validateToken(String token) {
    try {
        SignedJWT signed = SignedJWT.parse(token);
        boolean sigValid = validateSignature(signed);
        if (!sigValid) {
            LOGGER.warn("Signature of JWT token could not be verified. Please check the public key");
            return false;
        }
        boolean expValid = validateExpiration(signed);
        if (!expValid) {
            LOGGER.warn("Expiration time validation of JWT token failed.");
            return false;
        }
        String currentUser = (String) org.apache.shiro.SecurityUtils.getSubject().getPrincipal();
        if (currentUser == null) {
            return true;
        }
        String cookieUser = signed.getJWTClaimsSet().getSubject();
        return cookieUser.equals(currentUser);
    } catch (ParseException ex) {
        LOGGER.info("ParseException in validateToken", ex);
        return false;
    }
}
Also used : SignedJWT(com.nimbusds.jwt.SignedJWT) ParseException(java.text.ParseException)

Example 84 with SignedJWT

use of com.nimbusds.jwt.SignedJWT in project incubator-atlas by apache.

the class AtlasKnoxSSOAuthenticationFilter method doFilter.

/*
     * doFilter of AtlasKnoxSSOAuthenticationFilter is the first in the filter list so in this it check for the request
     * if the request is from browser and sso is enabled then it process the request against knox sso
     * else if it's ssoenable and the request is with local login string then it show's the appropriate msg
     * else if ssoenable is false then it contiunes with further filters as it was before sso
     */
@Override
public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
    HttpServletResponse httpResponse = (HttpServletResponse) servletResponse;
    AtlasResponseRequestWrapper responseWrapper = new AtlasResponseRequestWrapper(httpResponse);
    responseWrapper.setHeader("X-Frame-Options", "DENY");
    if (!ssoEnabled) {
        filterChain.doFilter(servletRequest, servletResponse);
        return;
    }
    HttpServletRequest httpRequest = (HttpServletRequest) servletRequest;
    if (LOG.isDebugEnabled()) {
        LOG.debug("Knox doFilter {}", httpRequest.getRequestURI());
    }
    if (httpRequest.getSession() != null && httpRequest.getSession().getAttribute("locallogin") != null) {
        servletRequest.setAttribute("ssoEnabled", false);
        filterChain.doFilter(servletRequest, servletResponse);
        return;
    }
    if (jwtProperties == null || isAuthenticated()) {
        filterChain.doFilter(servletRequest, servletResponse);
        return;
    }
    if (LOG.isDebugEnabled()) {
        LOG.debug("Knox ssoEnabled  {} {}", ssoEnabled, httpRequest.getRequestURI());
    }
    // if jwt properties are loaded and is current not authenticated then it will go for sso authentication
    // Note : Need to remove !isAuthenticated() after knoxsso solve the bug from cross-origin script
    HttpServletResponse httpServletResponse = (HttpServletResponse) servletResponse;
    String serializedJWT = getJWTFromCookie(httpRequest);
    // if we get the hadoop-jwt token from the cookies then will process it further
    if (serializedJWT != null) {
        SignedJWT jwtToken = null;
        try {
            jwtToken = SignedJWT.parse(serializedJWT);
            boolean valid = validateToken(jwtToken);
            // if the public key provide is correct and also token is not expired the process token
            if (valid) {
                String userName = jwtToken.getJWTClaimsSet().getSubject();
                LOG.info("SSO login user : {} ", userName);
                // if we get the userName from the token then log into atlas using the same user
                if (userName != null && !userName.trim().isEmpty()) {
                    List<GrantedAuthority> grantedAuths = AtlasAuthenticationProvider.getAuthoritiesFromUGI(userName);
                    final UserDetails principal = new User(userName, "", grantedAuths);
                    final Authentication finalAuthentication = new UsernamePasswordAuthenticationToken(principal, "", grantedAuths);
                    WebAuthenticationDetails webDetails = new WebAuthenticationDetails(httpRequest);
                    ((AbstractAuthenticationToken) finalAuthentication).setDetails(webDetails);
                    authenticationProvider.setSsoEnabled(ssoEnabled);
                    Authentication authentication = authenticationProvider.authenticate(finalAuthentication);
                    SecurityContextHolder.getContext().setAuthentication(authentication);
                }
                filterChain.doFilter(servletRequest, httpServletResponse);
            } else {
                // if the token is not valid then redirect to knox sso
                redirectToKnox(httpRequest, httpServletResponse, filterChain);
            }
        } catch (ParseException e) {
            LOG.warn("Unable to parse the JWT token", e);
            redirectToKnox(httpRequest, httpServletResponse, filterChain);
        }
    } else {
        redirectToKnox(httpRequest, httpServletResponse, filterChain);
    }
}
Also used : User(org.springframework.security.core.userdetails.User) GrantedAuthority(org.springframework.security.core.GrantedAuthority) HttpServletResponse(javax.servlet.http.HttpServletResponse) UsernamePasswordAuthenticationToken(org.springframework.security.authentication.UsernamePasswordAuthenticationToken) SignedJWT(com.nimbusds.jwt.SignedJWT) HttpServletRequest(javax.servlet.http.HttpServletRequest) AbstractAuthenticationToken(org.springframework.security.authentication.AbstractAuthenticationToken) UserDetails(org.springframework.security.core.userdetails.UserDetails) Authentication(org.springframework.security.core.Authentication) WebAuthenticationDetails(org.springframework.security.web.authentication.WebAuthenticationDetails) ParseException(java.text.ParseException)

Example 85 with SignedJWT

use of com.nimbusds.jwt.SignedJWT in project tomee by apache.

the class TokenUtils method generateJWTString.

public static String generateJWTString(String jsonResource) throws Exception {
    byte[] byteBuffer = new byte[16384];
    currentThread().getContextClassLoader().getResource(jsonResource).openStream().read(byteBuffer);
    JSONParser parser = new JSONParser(DEFAULT_PERMISSIVE_MODE);
    JSONObject jwtJson = (JSONObject) parser.parse(byteBuffer);
    long currentTimeInSecs = (System.currentTimeMillis() / 1000);
    long expirationTime = currentTimeInSecs + 1000;
    jwtJson.put(Claims.iat.name(), currentTimeInSecs);
    jwtJson.put(Claims.auth_time.name(), currentTimeInSecs);
    jwtJson.put(Claims.exp.name(), expirationTime);
    SignedJWT signedJWT = new SignedJWT(new JWSHeader.Builder(RS256).keyID("/privateKey.pem").type(JWT).build(), parse(jwtJson));
    signedJWT.sign(new RSASSASigner(readPrivateKey("privateKey.pem")));
    return signedJWT.serialize();
}
Also used : JSONObject(net.minidev.json.JSONObject) RSASSASigner(com.nimbusds.jose.crypto.RSASSASigner) JSONParser(net.minidev.json.parser.JSONParser) SignedJWT(com.nimbusds.jwt.SignedJWT)

Aggregations

SignedJWT (com.nimbusds.jwt.SignedJWT)204 Test (org.junit.Test)84 JWTClaimsSet (com.nimbusds.jwt.JWTClaimsSet)75 Date (java.util.Date)66 HttpServletRequest (javax.servlet.http.HttpServletRequest)64 HttpServletResponse (javax.servlet.http.HttpServletResponse)54 JWSHeader (com.nimbusds.jose.JWSHeader)53 Properties (java.util.Properties)49 ServletException (javax.servlet.ServletException)46 ParseException (java.text.ParseException)31 RSASSASigner (com.nimbusds.jose.crypto.RSASSASigner)28 JOSEException (com.nimbusds.jose.JOSEException)25 JWSSigner (com.nimbusds.jose.JWSSigner)21 Cookie (javax.servlet.http.Cookie)21 ArrayList (java.util.ArrayList)15 PrepareForTest (org.powermock.core.classloader.annotations.PrepareForTest)14 SignedJWTInfo (org.wso2.carbon.apimgt.impl.jwt.SignedJWTInfo)13 Test (org.junit.jupiter.api.Test)12 OAuth2TokenValidator (org.springframework.security.oauth2.core.OAuth2TokenValidator)12 Cache (javax.cache.Cache)11