jsonwebtoken/README.md

68 lines
2.1 KiB
Markdown
Raw Normal View History

2015-11-02 18:27:28 -05:00
# jsonwebtoken
2015-10-31 11:37:15 -04:00
2015-11-02 16:04:58 -05:00
[![Build Status](https://travis-ci.org/Keats/rust-jwt.svg)](https://travis-ci.org/Keats/rust-jwt)
2015-11-02 18:27:28 -05:00
## Installation
Add the following to Cargo.toml:
```toml
2015-11-10 11:38:41 -05:00
jsonwebtoken = "0.2"
2015-11-02 18:27:28 -05:00
rustc-serialize = "0.3"
```
2015-11-02 16:04:58 -05:00
## How to use
There is a complete example in examples/claims.rs but here's a quick one.
2015-11-02 18:32:32 -05:00
In terms of imports:
```rust
extern crate jsonwebtoken as jwt;
extern crate rustc_serialize;
2015-12-19 19:58:46 -05:00
use jwt::{encode, decode, Header, Algorithm};
2015-11-02 18:32:32 -05:00
```
2015-11-02 16:04:58 -05:00
### Encoding
```rust
let token = encode(Header::default(), &my_claims, "secret".as_ref()).unwrap();
2015-11-02 16:04:58 -05:00
```
In that example, `my_claims` is an instance of the Claims struct.
The struct you are using for your claims should derive `RustcEncodable` and `RustcDecodable`.
The default algorithm is HS256. Look at custom headers section to see how to change that.
2015-11-02 16:04:58 -05:00
### Decoding
```rust
2015-12-19 19:58:46 -05:00
let token = decode::<Claims>(&token, "secret", Algorithm::HS256).unwrap();
// token is a struct with 2 params: header and claims
2015-11-02 16:04:58 -05:00
```
In addition to the normal base64/json decoding errors, `decode` can return two custom errors:
- **InvalidToken**: if the token is not a valid JWT
- **InvalidSignature**: if the signature doesn't match
2015-11-02 16:22:21 -05:00
- **WrongAlgorithmHeader**: if the alg in the header doesn't match the one given to decode
2015-11-02 16:04:58 -05:00
2015-11-03 13:38:41 -05:00
### Validation
Right now, the library only validates the algorithm type used but does not verify claims such as expiration.
Feel free to add a `validate` method to your claims struct to handle that.
2015-12-19 19:58:46 -05:00
### Custom headers
All the parameters from the RFC are supported but the default header only has `typ` and `alg` set: all the other fields are optional.
If you want to set the `kid` parameter for example:
```rust
let mut header = Header::default();
header.kid = Some("blabla".to_owned());
header.alg = Algorithm::HS512;
let token = encode(header, &my_claims, "secret".as_ref()).unwrap();
2015-12-19 19:58:46 -05:00
```
2015-11-02 16:04:58 -05:00
## Algorithms
Right now, only SHA family is supported: SHA256, SHA384 and SHA512.
2015-11-02 16:04:58 -05:00
## Performance
On my thinkpad 440s for a 2 claims struct using SHA256:
2015-11-02 16:04:58 -05:00
2015-10-31 11:37:15 -04:00
```
2015-12-22 12:10:33 -05:00
test bench_decode ... bench: 7,259 ns/iter (+/- 1,506)
test bench_encode ... bench: 4,261 ns/iter (+/- 722)
2015-10-31 11:37:15 -04:00
```