Search in sources :

Example 76 with Token

use of com.auth0.json.mgmt.Token in project goobi-workflow by intranda.

the class Login method openIdLogin.

@POST
@Path("/openid")
@Operation(summary = "OpenID connect callback", description = "Verifies an openID claim and starts a session for the user")
@ApiResponse(responseCode = "200", description = "OK")
@ApiResponse(responseCode = "400", description = "Bad request")
@ApiResponse(responseCode = "500", description = "Internal error")
public void openIdLogin(@FormParam("error") String error, @FormParam("id_token") String idToken) throws IOException {
    ConfigurationHelper config = ConfigurationHelper.getInstance();
    String clientID = config.getOIDCClientID();
    String nonce = (String) servletRequest.getSession().getAttribute("openIDNonce");
    if (error == null) {
        // no error - we should have a token. Verify it.
        DecodedJWT jwt = JwtHelper.verifyOpenIdToken(idToken);
        if (jwt != null) {
            // now check if the nonce is the same as in the old session
            if (nonce.equals(jwt.getClaim("nonce").asString()) && clientID.equals(jwt.getClaim("aud").asString())) {
                // all OK, login the user
                HttpSession session = servletRequest.getSession();
                LoginBean userBean = Helper.getLoginBeanFromSession(session);
                // get the user by the configured claim from the JWT
                String login = jwt.getClaim(config.getOIDCIdClaim()).asString();
                log.debug("logging in user " + login);
                User user = UserManager.getUserBySsoId(login);
                if (user == null) {
                    userBean.setSsoError("Could not find user in Goobi database. Please contact your admin to add your SSO ID to the database.");
                    servletResponse.sendRedirect("/goobi/uii/logout.xhtml");
                    return;
                }
                userBean.setSsoError(null);
                user.lazyLoad();
                userBean.setMyBenutzer(user);
                userBean.setRoles(user.getAllUserRoles());
                userBean.setMyBenutzer(user);
                // add the user to the sessionform that holds information about all logged in users
                sessionForm.updateSessionUserName(servletRequest.getSession(), user);
            } else {
                if (!nonce.equals(jwt.getClaim("nonce").asString())) {
                    log.error("nonce does not match. Not logging user in");
                }
                if (!clientID.equals(jwt.getClaim("aud").asString())) {
                    log.error("clientID does not match aud. Not logging user in");
                }
            }
        } else {
            log.error("could not verify JWT");
        }
    } else {
        log.error(error);
    }
    servletResponse.sendRedirect("/goobi/index.xhtml");
}
Also used : User(org.goobi.beans.User) HttpSession(javax.servlet.http.HttpSession) LoginBean(org.goobi.managedbeans.LoginBean) ConfigurationHelper(de.sub.goobi.config.ConfigurationHelper) DecodedJWT(com.auth0.jwt.interfaces.DecodedJWT) Path(javax.ws.rs.Path) POST(javax.ws.rs.POST) Operation(io.swagger.v3.oas.annotations.Operation) ApiResponse(io.swagger.v3.oas.annotations.responses.ApiResponse)

Example 77 with Token

use of com.auth0.json.mgmt.Token in project java-fleetengine-auth by googlemaps.

the class LocalSignerTest method sign_returnsCorrectJwtHeader.

@Test
public void sign_returnsCorrectJwtHeader() throws SigningTokenException {
    LocalSigner localSigner = LocalSigner.create(CLIENT_EMAIL, FAKE_PRIVATE_KEY_ID, FAKE_PRIVATE_KEY);
    FleetEngineToken token = FleetEngineToken.builder().setTokenType(FleetEngineTokenType.SERVER).setCreationTimestamp(Date.from(creation.instant())).setExpirationTimestamp(Date.from(expiration.instant())).setAudience(TEST_AUDIENCE).setAuthorizationClaims(EmptyFleetEngineTokenClaims.INSTANCE).build();
    FleetEngineToken signedToken = localSigner.sign(token);
    DecodedJWT decodedJWT = JWT.decode(signedToken.jwt());
    String header = new String(Base64.getDecoder().decode(decodedJWT.getHeader()), UTF_8);
    Gson gson = new Gson();
    JwtHeader jwtHeader = gson.fromJson(header, JwtHeader.class);
    assertThat(jwtHeader.keyId).isEqualTo(FAKE_PRIVATE_KEY_ID);
}
Also used : Gson(com.google.gson.Gson) DecodedJWT(com.auth0.jwt.interfaces.DecodedJWT) FleetEngineToken(com.google.fleetengine.auth.token.FleetEngineToken) Test(org.junit.Test)

Example 78 with Token

use of com.auth0.json.mgmt.Token in project java-fleetengine-auth by googlemaps.

the class ImpersonatedSignerTest method sign_buildsJwtCorrectly.

@Test
public void sign_buildsJwtCorrectly() {
    FleetEngineToken token = FleetEngineToken.builder().setTokenType(FleetEngineTokenType.SERVER).setCreationTimestamp(Date.from(creation.instant())).setExpirationTimestamp(Date.from(expiration.instant())).setAudience(TEST_AUDIENCE).setAuthorizationClaims(EmptyFleetEngineTokenClaims.INSTANCE).build();
    // Mock impersonated credentials
    ImpersonatedAccountSignerCredentials impersonatedCredentials = mock(ImpersonatedAccountSignerCredentials.class);
    when(impersonatedCredentials.getAccount()).thenReturn(TEST_SERVICE_ACCOUNT);
    when(impersonatedCredentials.sign(any(), any())).thenAnswer(invocation -> {
        byte[] presignedHeaderJwt = invocation.getArgument(0, byte[].class);
        byte[] presignedContentJwt = invocation.getArgument(0, byte[].class);
        return Algorithm.none().sign(presignedHeaderJwt, presignedContentJwt);
    });
    ImpersonatedSigner signer = new ImpersonatedSigner(impersonatedCredentials);
    // Sign the token with the "none" algorithm.
    FleetEngineToken signedToken = signer.sign(token);
    // Check that the payload matches what was expected
    DecodedJWT decodedJWT = JWT.decode(signedToken.jwt());
    String payload = new String(Base64.getDecoder().decode(decodedJWT.getPayload()), UTF_8);
    Gson gson = new Gson();
    JwtPayload jwtPayload = gson.fromJson(payload, JwtPayload.class);
    assertThat(jwtPayload.audience).isEqualTo(TEST_AUDIENCE);
    assertThat(jwtPayload.issuer).isEqualTo(TEST_SERVICE_ACCOUNT);
    assertThat(jwtPayload.subject).isEqualTo(TEST_SERVICE_ACCOUNT);
    assertThat(jwtPayload.issuedAt).isEqualTo(creation.instant().getEpochSecond());
    assertThat(jwtPayload.expiredAt).isEqualTo(expiration.instant().getEpochSecond());
}
Also used : Gson(com.google.gson.Gson) DecodedJWT(com.auth0.jwt.interfaces.DecodedJWT) FleetEngineToken(com.google.fleetengine.auth.token.FleetEngineToken) ImpersonatedAccountSignerCredentials(com.google.fleetengine.auth.token.factory.signer.ImpersonatedSigner.ImpersonatedAccountSignerCredentials) Test(org.junit.Test)

Example 79 with Token

use of com.auth0.json.mgmt.Token in project waynboot-mall by wayn111.

the class TokenService method getLoginUser.

public LoginUserDetail getLoginUser(HttpServletRequest request) {
    // 获取请求携带的令牌
    String token = getToken(request);
    if (StringUtils.isNotEmpty(token)) {
        DecodedJWT decodedJWT = JwtUtil.parseToken(token);
        // 解析对应的权限以及用户信息
        String sign = decodedJWT.getClaim(SysConstants.SIGN_KEY).asString();
        String userKey = getTokenKey(sign);
        return redisCache.getCacheObject(userKey);
    }
    return null;
}
Also used : DecodedJWT(com.auth0.jwt.interfaces.DecodedJWT)

Example 80 with Token

use of com.auth0.json.mgmt.Token in project waynboot-mall by wayn111.

the class JwtUtil method sign.

/**
 * 生成签名
 *
 * @param token 用户唯一标识
 * @param secret 用户的密码
 * @return 加密的token
 */
public static String sign(String token, String secret) {
    Date date = new Date(System.currentTimeMillis() + EXPIRE_TIME);
    Algorithm algorithm = Algorithm.HMAC256(secret);
    return JWT.create().withClaim(SysConstants.SIGN_KEY, token).withIssuedAt(new Date()).withExpiresAt(date).sign(algorithm);
}
Also used : Algorithm(com.auth0.jwt.algorithms.Algorithm) Date(java.util.Date)

Aggregations

DecodedJWT (com.auth0.jwt.interfaces.DecodedJWT)276 Algorithm (com.auth0.jwt.algorithms.Algorithm)147 Test (org.junit.Test)120 JWTVerifier (com.auth0.jwt.JWTVerifier)97 Date (java.util.Date)78 JWTVerificationException (com.auth0.jwt.exceptions.JWTVerificationException)62 IOException (java.io.IOException)59 Claim (com.auth0.jwt.interfaces.Claim)49 HashMap (java.util.HashMap)40 VoidRequest (com.auth0.net.VoidRequest)31 RSAPublicKey (java.security.interfaces.RSAPublicKey)31 Test (org.junit.jupiter.api.Test)30 JWTDecodeException (com.auth0.jwt.exceptions.JWTDecodeException)28 JWTCreator (com.auth0.jwt.JWTCreator)21 RSAPrivateKey (java.security.interfaces.RSAPrivateKey)21 JWT (com.auth0.jwt.JWT)20 ObjectMapper (com.fasterxml.jackson.databind.ObjectMapper)19 UnsupportedEncodingException (java.io.UnsupportedEncodingException)18 Instant (java.time.Instant)18 NoSuchAlgorithmException (java.security.NoSuchAlgorithmException)17