You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
I try oauth2 = "*", oauth2 = "1.3.0", both of them didn't work.
And I check the src, it seems missing something:
#![warn(missing_docs)]//!//! A simple implementation of the OAuth2 flow, trying to adhere as much as possible to the [RFC](https://tools.ietf.org/html/rfc6749).//!//! # Getting started//!//! ## Example//!//! ```//! use oauth2::Config;//!//! // Create an OAuth2 config by specifying the client ID, client secret, authorization URL and token URL.//! let mut config = Config::new("client_id", "client_secret", "http://authorize", "http://token");//!//! // Set the desired scopes.//! config = config.add_scope("read");//! config = config.add_scope("write");//!//! // Set the URL the user will be redirected to after the authorization process.//! config = config.set_redirect_url("http://redirect");//!//! // Set a state parameter (optional, but recommended).//! config = config.set_state("1234");//!//! // Generate the full authorization URL.//! // This is the URL you should redirect the user to, in order to trigger the authorization process.//! println!("Browse to: {}", config.authorize_url());//!//! // Once the user has been redirected to the redirect URL, you'll have access to the authorization code.//! // Now you can trade it for an access token.//! let token_result = config.exchange_code("some authorization code");//!//! // Unwrapping token_result will either produce a Token or a TokenError.//! ```//!//! # The client credentials grant type//!//! You can ask for a *client credentials* access token by calling the `Config::exchange_client_credentials` method.//!//! ## Example//!//! ```//! use oauth2::Config;//!//! let mut config = Config::new("client_id", "client_secret", "http://authorize", "http://token");//! config = config.add_scope("read");//! config = config.set_redirect_url("http://redirect");//!//! let token_result = config.exchange_client_credentials();//! ```//!//! # The password grant type//!//! You can ask for a *password* access token by calling the `Config::exchange_password` method, while including//! the username and password.//!//! ## Example//!//! ```//! use oauth2::Config;//!//! let mut config = Config::new("client_id", "client_secret", "http://authorize", "http://token");//! config = config.add_scope("read");//! config = config.set_redirect_url("http://redirect");//!//! let token_result = config.exchange_password("user", "pass");//! ```//!//! # Setting a different response type//!//! The [RFC](https://tools.ietf.org/html/rfc6749#section-3.1.1) specifies various response types.//!//! The crate **defaults to the code response type**, but you can configure it to other values as well, by//! calling the `Config::set_response_type` method.//!//! ## Example//!//! ```//! use oauth2::{Config, ResponseType};//!//! let mut config = Config::new("client_id", "client_secret", "http://authorize", "http://token");//! config = config.set_response_type(ResponseType::Token);//! ```//!//! # Other examples//!//! More specific implementations are available as part of the examples://!//! - [Google](https://github.com/alexcrichton/oauth2-rs/blob/master/examples/google.rs)//! - [Github](https://github.com/alexcrichton/oauth2-rs/blob/master/examples/github.rs)//!externcrate url;externcrate curl;externcrate serde;externcrate serde_json;#[macro_use]externcrate serde_derive;#[macro_use]externcrate log;use std::io::Read;use std::convert::{From,Into,AsRef};use std::fmt::{Display,Formatter};use std::fmt::ErrorasFormatterError;use std::error::Error;use url::Url;use curl::easy::Easy;////// Stores the configuration for an OAuth2 client.///#[derive(Clone)]pubstructConfig{client_id:String,client_secret:String,auth_url:Url,auth_type:AuthType,token_url:Url,scopes:Vec<String>,response_type:ResponseType,redirect_url:Option<String>,state:Option<String>,}////// Indicates whether requests to the authorization server should use basic authentication or/// include the parameters in the request body for requests in which either is valid.////// The default AuthType is *RequestBody*.///#[derive(Clone)]pubenumAuthType{/// The client_id and client_secret will be included as part of the request body.RequestBody,/// The client_id and client_secret will be included using the basic auth authentication scheme.BasicAuth,}implConfig{////// Initializes the OAuth2 client with the client ID, client secret, the base authorization URL and the URL/// ment for requesting the access token.///pubfnnew<I,S,A,T>(client_id:I,client_secret:S,auth_url:A,token_url:T) -> SelfwhereI:Into<String>,S:Into<String>,A:AsRef<str>,T:AsRef<str>{Config{client_id: client_id.into(),client_secret: client_secret.into(),auth_url:Url::parse(auth_url.as_ref()).unwrap(),auth_type:AuthType::RequestBody,token_url:Url::parse(token_url.as_ref()).unwrap(),scopes:Vec::new(),response_type:ResponseType::Code,redirect_url:None,state:None,}}////// Appends a new scope to the authorization URL.///pubfnadd_scope<S>(mutself,scope:S) -> SelfwhereS:Into<String>{self.scopes.push(scope.into());self}////// Allows setting a particular response type. Both `&str` and `ResponseType` work here.////// The default response type is *code*.///pubfnset_response_type<R>(mutself,response_type:R) -> SelfwhereR:Into<ResponseType>{self.response_type = response_type.into();self}////// Allows configuring whether basic auth is used to communicate with the authorization server.////// The default auth type is to place the client_id and client_secret inside the request body.///pubfnset_auth_type(mutself,auth_type:AuthType) -> Self{self.auth_type = auth_type;self}////// Allows setting the redirect URL.///pubfnset_redirect_url<R>(mutself,redirect_url:R) -> SelfwhereR:Into<String>{self.redirect_url = Some(redirect_url.into());self}////// Allows setting a state parameter inside the authorization URL, which we'll be returned/// by the server after the authorization is over.///pubfnset_state<S>(mutself,state:S) -> SelfwhereS:Into<String>{self.state = Some(state.into());self}////// Produces the full authorization URL.///pubfnauthorize_url(&self) -> Url{let scopes = self.scopes.join(" ");let response_type = self.response_type.to_string();letmut pairs = vec![("client_id", &self.client_id),
("scope", &scopes),
("response_type", &response_type),
];ifletSome(ref redirect_url) = self.redirect_url{
pairs.push(("redirect_uri", redirect_url));}ifletSome(ref state) = self.state{
pairs.push(("state", state));}letmut url = self.auth_url.clone();
url.query_pairs_mut().extend_pairs(
pairs.iter().map(|&(k, v)| {(k,&v[..])}));
url
}////// Exchanges a code produced by a successful authorization process with an access token.////// See https://tools.ietf.org/html/rfc6749#section-4.1.3///#[deprecated(since="1.0.0", note="please use `exchange_code` instead")]pubfnexchange<C>(&self,code:C) -> Result<Token,TokenError>whereC:Into<String>{let params = vec![("code", code.into())];self.request_token(params)}////// Exchanges a code produced by a successful authorization process with an access token.////// See https://tools.ietf.org/html/rfc6749#section-4.1.3///pubfnexchange_code<C>(&self,code:C) -> Result<Token,TokenError>whereC:Into<String>{let params = vec![("grant_type", "authorization_code".to_string()),
("code", code.into())];self.request_token(params)}////// Requests an access token for the *client credentials* grant type.////// See https://tools.ietf.org/html/rfc6749#section-4.4.2///pubfnexchange_client_credentials(&self) -> Result<Token,TokenError>{let scopes = self.scopes.join(" ");let params = vec![("grant_type", "client_credentials".to_string()),
("scope", scopes),
];self.request_token(params)}////// Requests an access token for the *password* grant type.////// See https://tools.ietf.org/html/rfc6749#section-4.3.2///pubfnexchange_password<U,P>(&self,username:U,password:P) -> Result<Token,TokenError>whereU:Into<String>,P:Into<String>{let params = vec![("grant_type", "password".to_string()),
("username", username.into()),
("password", password.into())];self.request_token(params)}////// Exchanges a refresh token for an access token////// See https://tools.ietf.org/html/rfc6749#section-6///pubfnexchange_refresh_token<T>(&self,token:T) -> Result<Token,TokenError>whereT:Into<String>{let params = vec![("grant_type", "refresh_token".to_string()),
("refresh_token", token.into()),
];self.request_token(params)}fnrequest_token(&self,mutparams:Vec<(&str,String)>) -> Result<Token,TokenError>{letmut easy = Easy::new();matchself.auth_type{AuthType::RequestBody => {
params.push(("client_id",self.client_id.clone()));
params.push(("client_secret",self.client_secret.clone()));}AuthType::BasicAuth => {
easy.username(&self.client_id).unwrap();
easy.password(&self.client_secret).unwrap();}}ifletSome(ref redirect_url) = self.redirect_url{
params.push(("redirect_uri", redirect_url.to_string()));}let form = url::form_urlencoded::Serializer::new(String::new()).extend_pairs(params).finish();let form = form.into_bytes();letmut form = &form[..];
easy.url(&self.token_url.to_string()[..]).unwrap();
easy.post(true).unwrap();
easy.post_field_size(form.len()asu64).unwrap();letmut data = Vec::new();{letmut transfer = easy.transfer();
transfer.read_function(|buf| {Ok(form.read(buf).unwrap_or(0))}).unwrap();
transfer.write_function(|new_data| {
data.extend_from_slice(new_data);Ok(new_data.len())}).unwrap();
transfer.perform().map_err(|e| TokenError::other(e.to_string()))?;}let code = easy.response_code().unwrap();if code != 200{let reason = String::from_utf8_lossy(data.as_slice());let error = match serde_json::from_str::<TokenError>(&reason){Ok(error) => error,Err(error) => TokenError::other(format!("couldn't parse json response: {}", error))};returnErr(error);}let content_type = easy.content_type().unwrap_or(None).unwrap_or("application/x-www-formurlencoded");if content_type.contains("application/json"){Token::from_json(data)}else{Token::from_form(data)}}}////// The possible values for the `response_type` parameter.////// See https://tools.ietf.org/html/rfc6749#section-3.1.1///#[allow(missing_docs)]#[derive(Clone)]pubenumResponseType{Code,Token,Extension(String),}impl<'a>From<&'a str>forResponseType{fnfrom(response_type:&str) -> ResponseType{match response_type {"code" => ResponseType::Code,"token" => ResponseType::Token,
extension => ResponseType::Extension(extension.to_string()),}}}implDisplayforResponseType{fnfmt(&self,f:&mutFormatter) -> Result<(),FormatterError>{let formatted = matchself{&ResponseType::Code => "code",&ResponseType::Token => "token",&ResponseType::Extension(ref value) => value,};write!(f, "{}", formatted)}}////// The token returned after a successful authorization process.////// See https://tools.ietf.org/html/rfc6749#section-5.1///#[allow(missing_docs)]#[derive(Debug,Clone,PartialEq,Eq,Ord,PartialOrd,Serialize,Deserialize)]pubstructToken{pubtoken_type:String,pubaccess_token:String,#[serde(default)]pubscopes:Vec<String>,#[serde(default)]pubexpires_in:Option<u32>,#[serde(default)]pubrefresh_token:Option<String>,}implToken{fnfrom_form(data:Vec<u8>) -> Result<Self,TokenError>{let form = url::form_urlencoded::parse(&data);debug!("reponse: {:?}", form.collect::<Vec<_>>());letmut token = Token{access_token:String::new(),scopes:Vec::new(),token_type:String::new(),expires_in:None,refresh_token:None,};letmut error:Option<ErrorType> = None;letmut error_description = None;letmut error_uri = None;letmut state = None;for(k, v)in form.into_iter(){match&k[..]{"access_token" => token.access_token = v.into_owned(),"token_type" => token.token_type = v.into_owned(),"scope" => token.scopes = v.split(',').map(|s| s.to_string()).collect(),"error" => error = Some(v.as_ref().into()),"error_description" => error_description = Some(v.into_owned()),"error_uri" => error_uri = Some(v.into_owned()),"state" => state = Some(v.into_owned()),
_ => {}}}if token.access_token.len() != 0{Ok(token)}elseifletSome(error) = error {let token_error = TokenError{ error, error_description, error_uri, state };Err(token_error)}else{Err(TokenError::other("couldn't parse form response"))}}fnfrom_json(data:Vec<u8>) -> Result<Self,TokenError>{let data = String::from_utf8(data).unwrap();debug!("response: {}", data);
serde_json::from_str(&data).map_err(|parse_error| {match serde_json::from_str::<TokenError>(&data){Ok(token_error) => token_error,Err(_) => TokenError::other(format!("couldn't parse json response: {}", parse_error)),}})}}////// An error that occured after a failed authorization process.////// The same structure is returned both for OAuth2 specific errors, but also for parsing/transport errors./// The latter can be differentiated by looking for the `ErrorType::Other` variant.////// See https://tools.ietf.org/html/rfc6749#section-4.2.2.1///#[allow(missing_docs)]#[derive(Debug,PartialEq,Serialize,Deserialize)]pubstructTokenError{puberror:ErrorType,#[serde(default)]puberror_description:Option<String>,#[serde(default)]puberror_uri:Option<String>,#[serde(default)]pubstate:Option<String>,}implTokenError{fnother<E>(error:E) -> TokenErrorwhereE:Into<String>{TokenError{error:ErrorType::Other(error.into()),error_description:None,error_uri:None,state:None,}}}implDisplayforTokenError{fnfmt(&self,f:&mutFormatter) -> Result<(),FormatterError>{letmut formatted = self.error.to_string();ifletSome(ref error_description) = self.error_description{
formatted.push_str(": ");
formatted.push_str(error_description);}ifletSome(ref error_uri) = self.error_uri{
formatted.push_str(" / See ");
formatted.push_str(error_uri);}write!(f, "{}", formatted)}}implErrorforTokenError{fndescription(&self) -> &str{(&self.error).into()}}////// An OAuth2-specific error type or *other*.////// See https://tools.ietf.org/html/rfc6749#section-4.2.2.1///#[allow(missing_docs)]#[derive(Debug,PartialEq,Serialize,Deserialize)]#[serde(rename_all="snake_case")]pubenumErrorType{InvalidRequest,UnauthorizedClient,AccessDenied,UnsupportedResponseType,InvalidScope,ServerError,TemporarilyUnavailable,Other(String),}impl<'a>From<&'a str>forErrorType{fnfrom(error_type:&str) -> ErrorType{match error_type {"invalid_request" => ErrorType::InvalidRequest,"unauthorized_client" => ErrorType::UnauthorizedClient,"access_denied" => ErrorType::AccessDenied,"unsupported_response_type" => ErrorType::UnsupportedResponseType,"invalid_scope" => ErrorType::InvalidScope,"server_error" => ErrorType::ServerError,"temporarily_unavailable" => ErrorType::TemporarilyUnavailable,
other => ErrorType::Other(other.to_string()),}}}impl<'a>Into<&'a str>for&'a ErrorType{fninto(self) -> &'a str{matchself{&ErrorType::InvalidRequest => "invalid_request",&ErrorType::UnauthorizedClient => "unauthorized_client",&ErrorType::AccessDenied => "access_denied",&ErrorType::UnsupportedResponseType => "unsupported_response_type",&ErrorType::InvalidScope => "invalid_scope",&ErrorType::ServerError => "server_error",&ErrorType::TemporarilyUnavailable => "temporarily_unavailable",&ErrorType::Other(ref other) => other,}}}implDisplayforErrorType{fnfmt(&self,f:&mutFormatter) -> Result<(),FormatterError>{let message:&str = self.into();write!(f, "{}", message)}}
The text was updated successfully, but these errors were encountered:
I believe the prelude is specific to the 2.0 (alpha) release branch. The docs for the 1.3 (stable) release branch are here: https://docs.rs/oauth2/1.3.0/oauth2/
I try
oauth2 = "*"
,oauth2 = "1.3.0"
, both of them didn't work.And I check the src, it seems missing something:
The text was updated successfully, but these errors were encountered: