001/* 002 * oauth2-oidc-sdk 003 * 004 * Copyright 2012-2016, Connect2id Ltd and contributors. 005 * 006 * Licensed under the Apache License, Version 2.0 (the "License"); you may not use 007 * this file except in compliance with the License. You may obtain a copy of the 008 * License at 009 * 010 * http://www.apache.org/licenses/LICENSE-2.0 011 * 012 * Unless required by applicable law or agreed to in writing, software distributed 013 * under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR 014 * CONDITIONS OF ANY KIND, either express or implied. See the License for the 015 * specific language governing permissions and limitations under the License. 016 */ 017 018package com.nimbusds.openid.connect.sdk; 019 020 021import net.jcip.annotations.Immutable; 022 023import org.apache.commons.lang3.StringUtils; 024 025import com.nimbusds.oauth2.sdk.id.Identifier; 026 027 028/** 029 * Nonce. This is a random, unique string value to associate a user-session 030 * with an ID Token and to mitigate replay attacks. 031 * 032 * <p>Example generation of a nonce with eight random mixed-case alphanumeric 033 * characters: 034 * 035 * <pre> 036 * Nonce nonce = new Nonce(8); 037 * </pre> 038 * 039 * <p>Related specifications: 040 * 041 * <ul> 042 * <li>OpenID Connect Core 1.0, section 3.1.2.1. and 15.5.2. 043 * </ul> 044 */ 045@Immutable 046public final class Nonce extends Identifier { 047 048 049 /** 050 * Creates a new nonce with the specified value. 051 * 052 * @param value The nonce value. Must not be {@code null} or empty 053 * string. 054 */ 055 public Nonce(final String value) { 056 057 super(value); 058 } 059 060 061 /** 062 * Creates a new nonce with a randomly generated value of the specified 063 * byte length, Base64URL-encoded. 064 * 065 * @param byteLength The byte length of the value to generate. Must be 066 * greater than one. 067 */ 068 public Nonce(final int byteLength) { 069 070 super(byteLength); 071 } 072 073 074 /** 075 * Creates a new nonce with a randomly generated 256-bit (32-byte) 076 * value, Base64URL-encoded. 077 */ 078 public Nonce() { 079 080 super(); 081 } 082 083 084 @Override 085 public boolean equals(final Object object) { 086 087 return object instanceof Nonce && 088 this.toString().equals(object.toString()); 089 } 090 091 092 /** 093 * Parses a nonce from the specified string. 094 * 095 * @param s The string to parse, {@code null} or empty if no nonce is 096 * specified. 097 * 098 * @return The nonce, {@code null} if the parsed string was 099 * {@code null} or empty. 100 */ 101 public static Nonce parse(final String s) { 102 103 if (StringUtils.isBlank(s)) 104 return null; 105 106 return new Nonce(s); 107 } 108}