001package com.nimbusds.openid.connect.sdk; 002 003 004import net.jcip.annotations.Immutable; 005 006import org.apache.commons.lang3.StringUtils; 007 008import com.nimbusds.oauth2.sdk.id.Identifier; 009 010 011/** 012 * Nonce. This is a random, unique string value to associate a user-session 013 * with an ID Token and to mitigate replay attacks. 014 * 015 * <p>Example generation of a nonce with eight random mixed-case alphanumeric 016 * characters: 017 * 018 * <pre> 019 * Nonce nonce = new Nonce(8); 020 * </pre> 021 * 022 * <p>Related specifications: 023 * 024 * <ul> 025 * <li>OpenID Connect Core 1.0, section 3.1.2.1. and 15.5.2. 026 * </ul> 027 */ 028@Immutable 029public final class Nonce extends Identifier { 030 031 032 /** 033 * Creates a new nonce with the specified value. 034 * 035 * @param value The nonce value. Must not be {@code null} or empty 036 * string. 037 */ 038 public Nonce(final String value) { 039 040 super(value); 041 } 042 043 044 /** 045 * Creates a new nonce with a randomly generated value of the specified 046 * byte length, Base64URL-encoded. 047 * 048 * @param byteLength The byte length of the value to generate. Must be 049 * greater than one. 050 */ 051 public Nonce(final int byteLength) { 052 053 super(byteLength); 054 } 055 056 057 /** 058 * Creates a new nonce with a randomly generated 256-bit (32-byte) 059 * value, Base64URL-encoded. 060 */ 061 public Nonce() { 062 063 super(); 064 } 065 066 067 @Override 068 public boolean equals(final Object object) { 069 070 return object instanceof Nonce && 071 this.toString().equals(object.toString()); 072 } 073 074 075 /** 076 * Parses a nonce from the specified string. 077 * 078 * @param s The string to parse, {@code null} or empty if no nonce is 079 * specified. 080 * 081 * @return The nonce, {@code null} if the parsed string was 082 * {@code null} or empty. 083 */ 084 public static Nonce parse(final String s) { 085 086 if (StringUtils.isBlank(s)) 087 return null; 088 089 return new Nonce(s); 090 } 091}