Java Code Examples for com.auth0.jwt.JWT#create()

The following examples show how to use com.auth0.jwt.JWT#create() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: JwtUtils.java    From WeEvent with Apache License 2.0 5 votes vote down vote up
/**
 * @param username
 * @param expiration
 * @return token
 */
public static String encodeToken(String username, String privateSecret, int expiration) {
    try {
        JWTCreator.Builder builder = JWT.create();
        builder.withIssuer(username);
        // set expired date
        Calendar now = Calendar.getInstance();
        now.add(Calendar.SECOND, expiration);
        builder.withExpiresAt(now.getTime());
        return builder.sign(Algorithm.HMAC256(privateSecret));
    } catch (JWTCreationException e) {
        log.error("create jwt token failed", e);
        return "";
    }
}
 
Example 2
Source File: TokenUtil.java    From BlogManagePlatform with Apache License 2.0 5 votes vote down vote up
/**
 * 基本builder
 * @author Frodez
 * @date 2019-12-29
 */
private static Builder baseBuilder() {
	long now = System.currentTimeMillis();
	Builder builder = JWT.create();
	builder.withIssuer(issuer);
	builder.withIssuedAt(new Date(now));
	if (expired) {
		builder.withExpiresAt(new Date(now + expiration));
	}
	return builder;
}
 
Example 3
Source File: AuthenticationFactory.java    From MicroCommunity with Apache License 2.0 5 votes vote down vote up
/**
 * 创建token
 *
 * @return
 */
public static String createAndSaveToken(Map<String, String> info) throws Exception {

    if (!info.containsKey(CommonConstant.LOGIN_USER_ID)) {
        throw new InvalidParameterException("参数中没有包含:" + CommonConstant.LOGIN_USER_ID);
    }

    String jdi = UUID.randomUUID().toString().replace("-", "");
    String jwtSecret = MappingCache.getValue(MappingConstant.KEY_JWT_SECRET);
    if (StringUtil.isNullOrNone(jwtSecret)) {
        jwtSecret = CommonConstant.DEFAULT_JWT_SECRET;
    }
    Algorithm algorithm = Algorithm.HMAC256(jwtSecret);
    JWTCreator.Builder jwt = JWT.create();
    for (String key : info.keySet()) {
        if (CommonConstant.LOGIN_USER_ID.equals(key)) {
            continue;
        }
        jwt.withClaim(key, info.get(key));
    }
    String expireTime = MappingCache.getValue(MappingConstant.KEY_JWT_EXPIRE_TIME);
    if (StringUtil.isNullOrNone(expireTime)) {
        expireTime = CommonConstant.DEFAULT_JWT_EXPIRE_TIME;
    }
    //保存token Id
    JWTCache.setValue(jdi, info.get(CommonConstant.LOGIN_USER_ID), Integer.parseInt(expireTime));
    jwt.withIssuer("java110");
    jwt.withJWTId(jdi);
    return jwt.sign(algorithm);
}
 
Example 4
Source File: RubricsServiceImpl.java    From sakai with Educational Community License v2.0 4 votes vote down vote up
public String generateJsonWebToken(String tool, String siteId) {

        if (StringUtils.isBlank(siteId)) {
            siteId = getCurrentSiteId("generateJsonWebToken");
        }

        String token = null;
        String userId = sessionManager.getCurrentSessionUserId();

        try {
            DateTime now = DateTime.now();

            JWTCreator.Builder jwtBuilder = JWT.create();
            jwtBuilder.withIssuer(JWT_ISSUER)
                    .withAudience(JWT_AUDIENCE)
                    .withSubject(userId)
                    .withClaim(JWT_CUSTOM_CLAIM_TOOL_ID, tool)
                    .withClaim(JWT_CUSTOM_CLAIM_SESSION_ID, sessionManager.getCurrentSession().getId())
                    .withIssuedAt(now.toDate());
            int sessionTimeoutInSeconds = sessionManager.getCurrentSession().getMaxInactiveInterval();
            if (sessionTimeoutInSeconds > 0) {
                jwtBuilder.withExpiresAt(now.plusSeconds(sessionTimeoutInSeconds).toDate());
            } else {
                // if Sakai is configured for sessions to never timeout (negative value), we will set 30 minutes for
                // tokens - the rubrics service will check Sakai session validity if it receives an expired token.
                jwtBuilder.withExpiresAt(now.plusMinutes(30).toDate());
            }

            if (securityService.isSuperUser()) {
                jwtBuilder.withArrayClaim(JWT_CUSTOM_CLAIM_ROLES,
                        new String[]{ RBCS_PERMISSIONS_EDITOR,
                                RBCS_PERMISSIONS_ASSOCIATOR,
                                RBCS_PERMISSIONS_EVALUATOR,
                                RBCS_PERMISSIONS_EVALUEE,
                                RBCS_PERMISSIONS_SUPERUSER });
            } else {
                List<String> roles = new ArrayList<>();
                if (authzGroupService.isAllowed(userId, RBCS_PERMISSIONS_EDITOR, "/site/" + siteId)) {
                    roles.add(RBCS_PERMISSIONS_EDITOR);
                }
                if (authzGroupService.isAllowed(userId, RBCS_PERMISSIONS_ASSOCIATOR, "/site/" + siteId)) {
                    roles.add(RBCS_PERMISSIONS_ASSOCIATOR);
                }
                if (authzGroupService.isAllowed(userId, RBCS_PERMISSIONS_EVALUATOR, "/site/" + siteId)) {
                    roles.add(RBCS_PERMISSIONS_EVALUATOR);
                }
                if (authzGroupService.isAllowed(userId, RBCS_PERMISSIONS_EVALUEE, "/site/" + siteId)) {
                    roles.add(RBCS_PERMISSIONS_EVALUEE);
                }
                jwtBuilder.withArrayClaim(JWT_CUSTOM_CLAIM_ROLES, roles.toArray(new String[]{}));
            }
            jwtBuilder.withClaim(JWT_CUSTOM_CLAIM_CONTEXT_ID, siteId);
            jwtBuilder.withClaim(JWT_CUSTOM_CLAIM_CONTEXT_TYPE, SITE_CONTEXT_TYPE);
            token =  jwtBuilder.sign(Algorithm.HMAC256(serverConfigurationService.getString(
                    RUBRICS_TOKEN_SIGNING_SHARED_SECRET_PROPERTY)));

        } catch (UnsupportedEncodingException e){
            throw new RuntimeException(String.format("An error occurred while generating a JSON Web Token to " +
                    "authorize communication with the Rubrics service. Please verify the %s property is " +
                    "defined in the sakai.properties file.", RUBRICS_TOKEN_SIGNING_SHARED_SECRET_PROPERTY), e);
        }

        return token;
    }
 
Example 5
Source File: JwtCreate.java    From openbd-core with GNU General Public License v3.0 4 votes vote down vote up
@Override
public cfData execute(cfSession _session, cfArgStructData argStruct) throws cfmRunTimeException {
	// Prep variables
	Builder tokenBuilder = JWT.create();
	String token = "";
	Algorithm algo;

	// Grab the parameters
	String secret			= getNamedStringParam(argStruct, "secret", "" );
	String issuer			= getNamedStringParam(argStruct, "issuer", "" );
	String subject			= getNamedStringParam(argStruct, "subject", "" );
	String audience			= getNamedStringParam(argStruct, "audience", "" );
	Integer expiration		= getNamedIntParam(argStruct, "expiration", -1 );
	String algorithm 		= getNamedStringParam(argStruct, "algorithm", "HMAC256" );
	cfData privateClaims 	= getNamedParam(argStruct, "private");
	
	if (!privateClaims.isStruct())
		throwException(_session, "Parameter isn't of type STRUCTURE");

	try {
		// Set the algorithm, default to HMAC256 if no match
		switch(algorithm) {
		case "HMAC384":
			algo = Algorithm.HMAC384(secret);
			break;
			
		case "HMAC512":
			algo = Algorithm.HMAC512(secret);
			break;
			
		default:
			algo = Algorithm.HMAC256(secret);
			break;
		}
		
	    // Set the public claims
		tokenBuilder.withIssuer(issuer);
	    
	    if (subject.length() > 0) {
			tokenBuilder.withSubject(subject);
		}
	    
	    if (audience.length() > 0) {
			tokenBuilder.withAudience(audience);
		}
	    
	    if (expiration > -1) {
	    		tokenBuilder.withExpiresAt(new Date(expiration));
		}
	    
	    // Set the private claims
	    cfStructData struct = (cfStructData) privateClaims;

	    Object[] thekeys = struct.keys();
	    for ( int i = 0; i < thekeys.length; i++ ) {
	    		String key2 = (String)thekeys[ i ];
	    		cfData val = struct.getData( key2 );
			
	    		if( val.getDataTypeName() == "boolean" ) {
	    			tokenBuilder.withClaim(key2, val.getBoolean());
	    			
	    		} else {
	    			if( cfData.isSimpleValue(val) ){
	    				tokenBuilder.withClaim(key2, val.getString());
	    			} else {
	    				// Let's turn our complex data into json
	    				StringBuilder buffer 			= new StringBuilder(5000);
	    				
	    				// Use the existing openbd json serializer
	    				serializejson jsonserializer 	= new serializejson();
	    				DateType datetype 				= DateType.LONG;
	    				CaseType caseConversion 			= CaseType.MAINTAIN;
	    				
	    				jsonserializer.encodeJSON(buffer, val, false, caseConversion, datetype);
	    				tokenBuilder.withClaim(key2, buffer.toString());
	    			}
	    		}
	    	}
		
		// Sign and stringify final token
		token = tokenBuilder.sign(algo);
	    
	} catch (Exception e) {
		throwException(_session, e.getMessage());
	}	

	return new cfStringData(token);
}
 
Example 6
Source File: RubricsServiceImpl.java    From sakai with Educational Community License v2.0 4 votes vote down vote up
public String generateJsonWebToken(String tool, String siteId) {

        if (StringUtils.isBlank(siteId)) {
            siteId = getCurrentSiteId("generateJsonWebToken");
        }

        String token = null;
        String userId = sessionManager.getCurrentSessionUserId();

        try {
            DateTime now = DateTime.now();

            JWTCreator.Builder jwtBuilder = JWT.create();
            jwtBuilder.withIssuer(JWT_ISSUER)
                    .withAudience(JWT_AUDIENCE)
                    .withSubject(userId)
                    .withClaim(JWT_CUSTOM_CLAIM_TOOL_ID, tool)
                    .withClaim(JWT_CUSTOM_CLAIM_SESSION_ID, sessionManager.getCurrentSession().getId())
                    .withIssuedAt(now.toDate());
            int sessionTimeoutInSeconds = sessionManager.getCurrentSession().getMaxInactiveInterval();
            if (sessionTimeoutInSeconds > 0) {
                jwtBuilder.withExpiresAt(now.plusSeconds(sessionTimeoutInSeconds).toDate());
            } else {
                // if Sakai is configured for sessions to never timeout (negative value), we will set 30 minutes for
                // tokens - the rubrics service will check Sakai session validity if it receives an expired token.
                jwtBuilder.withExpiresAt(now.plusMinutes(30).toDate());
            }

            if (securityService.isSuperUser()) {
                jwtBuilder.withArrayClaim(JWT_CUSTOM_CLAIM_ROLES,
                        new String[]{ RBCS_PERMISSIONS_EDITOR,
                                RBCS_PERMISSIONS_ASSOCIATOR,
                                RBCS_PERMISSIONS_EVALUATOR,
                                RBCS_PERMISSIONS_EVALUEE,
                                RBCS_PERMISSIONS_SUPERUSER });
            } else {
                List<String> roles = new ArrayList<>();
                if (authzGroupService.isAllowed(userId, RBCS_PERMISSIONS_EDITOR, "/site/" + siteId)) {
                    roles.add(RBCS_PERMISSIONS_EDITOR);
                }
                if (authzGroupService.isAllowed(userId, RBCS_PERMISSIONS_ASSOCIATOR, "/site/" + siteId)) {
                    roles.add(RBCS_PERMISSIONS_ASSOCIATOR);
                }
                if (authzGroupService.isAllowed(userId, RBCS_PERMISSIONS_EVALUATOR, "/site/" + siteId)) {
                    roles.add(RBCS_PERMISSIONS_EVALUATOR);
                }
                if (authzGroupService.isAllowed(userId, RBCS_PERMISSIONS_EVALUEE, "/site/" + siteId)) {
                    roles.add(RBCS_PERMISSIONS_EVALUEE);
                }
                jwtBuilder.withArrayClaim(JWT_CUSTOM_CLAIM_ROLES, roles.toArray(new String[]{}));
            }
            jwtBuilder.withClaim(JWT_CUSTOM_CLAIM_CONTEXT_ID, siteId);
            jwtBuilder.withClaim(JWT_CUSTOM_CLAIM_CONTEXT_TYPE, SITE_CONTEXT_TYPE);
            token =  jwtBuilder.sign(Algorithm.HMAC256(serverConfigurationService.getString(
                    RUBRICS_TOKEN_SIGNING_SHARED_SECRET_PROPERTY)));

        } catch (UnsupportedEncodingException e){
            throw new RuntimeException(String.format("An error occurred while generating a JSON Web Token to " +
                    "authorize communication with the Rubrics service. Please verify the %s property is " +
                    "defined in the sakai.properties file.", RUBRICS_TOKEN_SIGNING_SHARED_SECRET_PROPERTY), e);
        }

        return token;
    }