Token in Rust
In Rust, the term "token" can refer to different concepts depending on the context in which it is used. Below, we explore the concept of tokens in the context of Rust macros and web development.
Tokens in Rust Macros
In the context of Rust macros, tokens are the fundamental building blocks that represent the raw input data provided to macros. These tokens encapsulate code elements along with their associated metadata. When working with attribute macros, tokens are parsed to extract and apply attributes, which enables dynamic code transformations. For instance, tokens can be processed to modify the visibility of struct fields based on specific attribute specifications.
Tokens vs. Attributes
Tokens and attributes serve distinct roles within macros. Tokens refer to the raw input data that a macro processes, while attributes are specific metadata applied to code elements. Attribute macros utilize tokens to interpret and apply these attributes, allowing for dynamic modifications of code based on the metadata provided. This distinction is crucial for understanding how macros can transform code by leveraging the metadata encapsulated within tokens.
Example: ExcludedFields Implementation
The following example demonstrates how tokens are parsed and processed in the context of an attribute macro. The ExcludedFields struct is designed to handle an exclude attribute, which specifies fields to be excluded from certain operations.
Listing 8.37 ExcludedFields implementation for syn major version 2
const EXCLUDE_ATTRIBUTE_NAME: &str = "exclude";
struct ExcludedFields {
fields: Vec<String>
}
impl ExcludedFields {
fn matches_ident(&self, name: &Option<Ident>) -> bool {
name.as_ref().map(|n| n.to_string())
.map(|n| self.fields.iter().any(|f| *f == n))
.unwrap_or_else(|| false)
}
}
impl Parse for ExcludedFields {
fn parse(input: ParseStream) -> Result<Self, syn::Error> {
match input.parse::<MetaList>() { #1
Ok(meta_list) => {
if meta_list.path
.segments
.iter()
.find(|s| s.ident == EXCLUDE_ATTRIBUTE_NAME)
.is_some() #2
{
let parser = Punctuated::<Ident, Token![,]>::parse_terminated;
let identifiers = parser.parse(
meta_list.clone().tokens.into()
).unwrap();
let fields = identifiers.iter()
.map(|v| v.to_string())
.collect(); #3
Ok(ExcludedFields { fields })
} else {
Ok(ExcludedFields { fields: vec![] })
}
}
Err(_) => Ok(
ExcludedFields { fields: vec![] } #4
)
}
}
}
#1 Parses our tokens as a MetaList
#2 Checks that the property is in the path
#3 Retrieves the values from the tokens property and stores them
#4 If parsing fails, we assume there are no items to exclude.
In this implementation, the parse function checks for the presence of the exclude attribute within the token stream. If found, it parses the tokens as a Punctuated list of identifiers, converting them into strings and storing them in the fields vector. This allows the macro to dynamically exclude specified fields based on the parsed tokens.
Tokens in Rust Web Development
In the context of web development, a token is a digital key used in authentication to verify a user's identity. It is a string that represents a user's authentication credentials and is used to authorize access to resources. Tokens are typically included in the HTTP Authorization header and are issued upon successful login. They provide a stateless way to perform authentication, allowing users to make subsequent requests to access protected resources without needing to re-authenticate.
Token Issuance
Tokens are generated and issued after a successful login. The following Rust code snippet demonstrates how to issue a token using the paseto library. The token includes a timestamp for expiration and a claim for the account_id.
Listing 9.20 Adding timestamps to our tokens in src/routes/authentication.rs
use chrono::prelude::*;
fn issue_token(account_id: AccountId) -> String {
let current_date_time = Utc::now();
let dt = current_date_time + chrono::Duration::days(1);
paseto::tokens::PasetoBuilder::new()
.set_encryption_key(
&Vec::from("RANDOM WORDS WINTER MACINTOSH PC".as_bytes())
)
.set_expiration(&dt)
.set_not_before(&Utc::now())
.set_claim("account_id", serde_json::json!(account_id))
.build()
.expect("Failed to construct paseto token w/ builder!")
}
In this code, the PasetoBuilder is used to create a token with an encryption key, expiration time, and claims. The token is set to expire one day after its issuance.
Token Verification and Middleware
To ensure that tokens are valid and to extract necessary information, such as account_id, from them, a verification process is implemented. This process is often encapsulated in middleware, which can be added to route handlers to manage authentication.
Listing 9.24 Adding the auth middleware logic in src/routes/authentication.rs
pub fn verify_token(token: String) -> Result<Session, handle_errors::Error> {
let token = paseto::tokens::validate_local_token(
&token,
None,
&"RANDOM WORDS WINTER MACINTOSH PC".as_bytes(),
&paseto::tokens::TimeBackend::Chrono,
)
.map_err(|_| handle_errors::Error::CannotDecryptToken)?;
serde_json::from_value::<Session>(token).map_err(|_| {
handle_errors::Error::CannotDecryptToken
})
}
fn issue_token(account_id: AccountId) -> String {
let current_date_time = Utc::now();
let dt = current_date_time + chrono::Duration::days(1);
paseto::tokens::PasetoBuilder::new()
.set_encryption_key(
&Vec::from("RANDOM WORDS WINTER MACINTOSH PC".as_bytes())
)
.set_expiration(&dt)
.set_not_before(&Utc::now())
.set_claim("account_id", serde_json::json!(account_id))
.build()
.expect("Failed to construct paseto token w/ builder!")
}
pub fn auth() ->
impl Filter<Extract = (Session,), Error = warp::Rejection> + Clone {
warp::header::<String>("Authorization").and_then(|token: String| {
let token = match verify_token(token) {
Ok(t) => t,
Err(_) => return future::ready(Err(warp::reject::reject())),
};
future::ready(Ok(token))
})
}
The verify_token function checks the validity of a token and attempts to deserialize it into a Session. If the token is invalid, an error is returned. The auth function is a middleware that uses Warp's Filter trait to extract the token from the HTTP request header, verify it, and pass the session to the route handler. If the token is invalid, the request is rejected. This middleware ensures that only authenticated requests are processed further.
| Book Title | Usage of token | Technical Depth | Connections to Other Concepts | Examples Used | Practical Application |
|------------|----------------|-----------------|-------------------------------|---------------|-----------------------|
| [Write Powerful Rust Macros](https://www.manning.com/books/write-powerful-rust-macros) | Tokens are discussed as fundamental building blocks in Rust macros, representing raw input data and metadata. | Detailed explanation of how tokens are parsed and processed in macros, especially in attribute macros. | Connects tokens with attributes, explaining their distinct roles and how they enable dynamic code transformations. | Provides an example of the `ExcludedFields` implementation, showing how tokens are parsed and processed. [more](https://livebook.manning.com/book/write-powerful-rust-macros/chapter-8/167) | Focuses on modifying code visibility and excluding fields dynamically using tokens. |
| [Rust Web Development](https://www.manning.com/books/rust-web-development) | Tokens are described as digital keys used in authentication to verify user identity and authorize access. | Explains token issuance, verification, and middleware implementation for authentication. | Discusses tokens in the context of HTTP headers and authentication processes. | Includes code snippets for issuing and verifying tokens using the `paseto` library. [more](https://livebook.manning.com/book/rust-web-development/chapter-9/133) | Practical application in web development for managing user authentication and access control. |
FAQ (Frequently asked questions)
What is a token in the context of authentication?
How is a token used in verifying a user's identity?
Where are tokens typically included in HTTP requests?
How can you issue a token in Rust?
What library is used for token creation in the provided Rust code?
What is the purpose of a token in authentication?
When is a token issued?
How do you add timestamps to tokens in Rust?
What is the purpose of setting an expiration date on a token?
What are tokens in the context of Rust macros?
How are tokens used in attribute macros?
What example is given for processing tokens in attribute macros?
What do tokens represent in macros?
What are attributes in the context of Rust macros?
How do attribute macros use tokens?