Struct graph_oauth::oauth::OAuth

source ·
pub struct OAuth { /* private fields */ }
Expand description

OAuth

OAuth client implementing the OAuth 2.0 and OpenID Connect protocols on Microsoft identity platform. This version is specifically meant for the Graph V1.0 and Beta API.

The client supports almost all OAuth 2.0 flows that Microsoft implements as well as the token and code flow specific to the OneDrive api.

The OAuth client is strict on what can be used for a specific OAuth flow. This is to ensure that the credentials used in requests include only information that is required or optional for that specific grant and not any other. Even if you accidently pass a value, such as a nonce, for a grant type that does not use it, any request that is made will not include the nonce regardless.

Disclaimer

Using this API for other resource owners besides Microsoft may work but functionality will more then likely be limited.

Example

use graph_oauth::oauth::OAuth;
let oauth = OAuth::new();

Implementations§

source§

impl OAuth

source

pub fn new() -> OAuth

Create a new OAuth instance.

Example
use graph_oauth::oauth::{OAuth, GrantType};

let mut oauth = OAuth::new();
source

pub fn insert<V: ToString>( &mut self, oac: OAuthCredential, value: V ) -> &mut OAuth

Insert oauth credentials using the OAuthCredential enum. This method is used internally for each of the setter methods. Callers can optionally use this method to set credentials instead of the individual setter methods.

Example
oauth.insert(OAuthCredential::AuthorizeURL, "https://example.com");
assert!(oauth.contains(OAuthCredential::AuthorizeURL));
println!("{:#?}", oauth.get(OAuthCredential::AuthorizeURL));
source

pub fn entry<V: ToString>( &mut self, oac: OAuthCredential, value: V ) -> &mut String

Insert and OAuth credential using the entry trait and returning the credential. This internally calls entry.(OAuthCredential).or_insret_with(value).

Example
let entry = oauth.entry(OAuthCredential::AuthorizeURL, "https://example.com");
assert_eq!(entry, "https://example.com")
source

pub fn get(&self, oac: OAuthCredential) -> Option<String>

Get a previously set credential.

Example
let a = oauth.get(OAuthCredential::AuthorizeURL);
source

pub fn contains(&self, t: OAuthCredential) -> bool

Check if an OAuth credential has already been set.

Example
println!("{:#?}", oauth.contains(OAuthCredential::Nonce));
source

pub fn contains_key(&self, key: &str) -> bool

source

pub fn remove(&mut self, oac: OAuthCredential) -> &mut OAuth

Remove a field from OAuth.

Example
oauth.client_id("client_id");

assert_eq!(oauth.contains(OAuthCredential::ClientId), true);
oauth.remove(OAuthCredential::ClientId);

assert_eq!(oauth.contains(OAuthCredential::ClientId), false);
source

pub fn client_id(&mut self, value: &str) -> &mut OAuth

Set the client id for an OAuth request.

Example
oauth.client_id("client_id");
source

pub fn state(&mut self, value: &str) -> &mut OAuth

Set the state for an OAuth request.

Example
oauth.state("1234");
source

pub fn client_secret(&mut self, value: &str) -> &mut OAuth

Set the client secret for an OAuth request.

Example
oauth.client_secret("client_secret");
source

pub fn authorize_url(&mut self, value: &str) -> &mut OAuth

Set the authorization URL.

Example
oauth.authorize_url("https://example.com/authorize");
source

pub fn access_token_url(&mut self, value: &str) -> &mut OAuth

Set the access token url of a request for OAuth

Example
oauth.access_token_url("https://example.com/token");
source

pub fn refresh_token_url(&mut self, value: &str) -> &mut OAuth

Set the refresh token url of a request for OAuth

Example
oauth.refresh_token_url("https://example.com/token");
source

pub fn tenant_id(&mut self, value: &str) -> &mut OAuth

Set the authorization, access token, and refresh token URL for OAuth based on a tenant id.

Example
oauth.tenant_id("tenant_id");
source

pub fn redirect_uri(&mut self, value: &str) -> &mut OAuth

Set the redirect url of a request

Example
oauth.redirect_uri("https://localhost:8888/redirect");
source

pub fn access_code(&mut self, value: &str) -> &mut OAuth

Set the access code.

Example
oauth.access_code("LDSF[POK43");
source

pub fn response_mode(&mut self, value: &str) -> &mut OAuth

Set the response mode.

Example
oauth.response_mode("query");
source

pub fn response_type(&mut self, value: &str) -> &mut OAuth

Set the response type.

Example
oauth.response_type("token");
source

pub fn nonce(&mut self, value: &str) -> &mut OAuth

Set the nonce.

Example

oauth.nonce("1234");
source

pub fn prompt(&mut self, value: &str) -> &mut OAuth

Set the prompt for open id.

Example

oauth.prompt("login");
source

pub fn id_token(&mut self, value: IdToken) -> &mut OAuth

Set id token for open id.

Example
oauth.id_token(IdToken::new("1345", "code", "state", "session_state"));
source

pub fn session_state(&mut self, value: &str) -> &mut OAuth

Set the session state.

Example
oauth.session_state("session-state");
source

pub fn grant_type(&mut self, value: &str) -> &mut OAuth

Set the grant_type.

Example
oauth.grant_type("token");
source

pub fn resource(&mut self, value: &str) -> &mut OAuth

Set the resource.

Example
oauth.resource("resource");
source

pub fn code_verifier(&mut self, value: &str) -> &mut OAuth

Set the code verifier.

Example
oauth.code_verifier("code_verifier");
source

pub fn domain_hint(&mut self, value: &str) -> &mut OAuth

Set the domain hint.

Example
oauth.domain_hint("domain_hint");
source

pub fn code_challenge(&mut self, value: &str) -> &mut OAuth

Set the code challenge.

Example
oauth.code_challenge("code_challenge");
source

pub fn code_challenge_method(&mut self, value: &str) -> &mut OAuth

Set the code challenge method.

Example
oauth.code_challenge_method("code_challenge_method");
source

pub fn generate_sha256_challenge_and_verifier( &mut self ) -> Result<(), GraphFailure>

Generate a code challenge and code verifier for the authorization code grant flow using proof key for code exchange (PKCE) and SHA256.

This method automatically sets the code_verifier, code_challenge, and code_challenge_method fields.

For authorization, the code_challenge_method parameter in the request body is automatically set to ‘S256’.

Internally this method uses the Rust ring cyrpto library to generate a secure random 32-octet sequence that is base64 URL encoded (no padding). This sequence is hashed using SHA256 and base64 URL encoded (no padding) resulting in a 43-octet URL safe string.

For more info on PKCE and entropy see: https://tools.ietf.org/html/rfc7636#section-7.1

Example

let mut oauth = OAuth::new();
oauth.generate_sha256_challenge_and_verifier();

println!("Code Challenge: {:#?}", oauth.get(OAuthCredential::CodeChallenge));
println!("Code Verifier: {:#?}", oauth.get(OAuthCredential::CodeVerifier));
println!("Code Challenge Method: {:#?}", oauth.get(OAuthCredential::CodeChallengeMethod));
source

pub fn login_hint(&mut self, value: &str) -> &mut OAuth

Set the login hint.

Example
oauth.login_hint("login_hint");
source

pub fn client_assertion(&mut self, value: &str) -> &mut OAuth

Set the client assertion.

Example
oauth.client_assertion("client_assertion");
source

pub fn client_assertion_type(&mut self, value: &str) -> &mut OAuth

Set the client assertion type.

Example
oauth.client_assertion_type("client_assertion_type");
source

pub fn logout_url(&mut self, value: &str) -> &mut OAuth

Set the url to send a post request that will log out the user.

Example
oauth.logout_url("https://example.com/logout?");
source

pub fn post_logout_redirect_uri(&mut self, value: &str) -> &mut OAuth

Set the redirect uri that user will be redirected to after logging out.

Example
oauth.post_logout_redirect_uri("http://localhost:8080");
source

pub fn username(&mut self, value: &str) -> &mut OAuth

Set the redirect uri that user will be redirected to after logging out.

Example
oauth.username("user");
assert!(oauth.contains(OAuthCredential::Username))
source

pub fn password(&mut self, value: &str) -> &mut OAuth

Set the redirect uri that user will be redirected to after logging out.

Example
oauth.password("user");
assert!(oauth.contains(OAuthCredential::Password))
source

pub fn add_scope<T: ToString>(&mut self, scope: T) -> &mut OAuth

Add a scope’ for the OAuth URL.

Example

oauth.add_scope("Sites.Read")
    .add_scope("Sites.ReadWrite")
    .add_scope("Sites.ReadWrite.All");
assert_eq!(oauth.join_scopes(" "), "Sites.Read Sites.ReadWrite Sites.ReadWrite.All");
source

pub fn get_scopes(&self) -> &BTreeSet<String>

Get the scopes.

Example
let mut oauth = OAuth::new();
oauth.add_scope("Files.Read");
oauth.add_scope("Files.ReadWrite");

let scopes = oauth.get_scopes();
assert!(scopes.contains("Files.Read"));
assert!(scopes.contains("Files.ReadWrite"));
source

pub fn join_scopes(&self, sep: &str) -> String

Join scopes.

Example

// the scopes take a separator just like Vec join.
 let s = oauth.join_scopes(" ");
println!("{:#?}", s);
source

pub fn extend_scopes<T: ToString, I: IntoIterator<Item = T>>( &mut self, iter: I ) -> &mut Self

Extend scopes.

Example

let scopes1 = vec!["Files.Read", "Files.ReadWrite"];
oauth.extend_scopes(&scopes1);

assert_eq!(oauth.join_scopes(" "), "Files.Read Files.ReadWrite");
source

pub fn contains_scope<T: ToString>(&self, scope: T) -> bool

Check if OAuth contains a specific scope.

Example

oauth.add_scope("Files.Read");
assert_eq!(oauth.contains_scope("Files.Read"), true);

// Or using static scopes
oauth.add_scope("File.ReadWrite");
assert!(oauth.contains_scope("File.ReadWrite"));
source

pub fn remove_scope<T: AsRef<str>>(&mut self, scope: T)

Remove a previously added scope.

Example

oauth.add_scope("scope");
oauth.remove_scope("scope");
source

pub fn clear_scopes(&mut self)

Remove all scopes.

Example

oauth.add_scope("Files.Read").add_scope("Files.ReadWrite");
assert_eq!("Files.Read Files.ReadWrite", oauth.join_scopes(" "));

oauth.clear_scopes();
assert!(oauth.get_scopes().is_empty());
source

pub fn access_token(&mut self, ac: AccessToken)

Set the access token.

Example
use graph_oauth::oauth::OAuth;
use graph_oauth::oauth::AccessToken;
let mut oauth = OAuth::new();
let access_token = AccessToken::default();
oauth.access_token(access_token);
source

pub fn get_access_token(&self) -> Option<AccessToken>

Get the access token.

Example
let access_token = oauth.get_access_token().unwrap();
println!("{:#?}", access_token);
source

pub fn get_refresh_token(&self) -> Result<String, GraphFailure>

Get the refrsh token. This method returns the current refresh token stored in OAuth and does not make a request for a refresh token.

Example
let mut  access_token = AccessToken::default();
access_token.set_refresh_token("refresh_token");
oauth.access_token(access_token);

let refresh_token = oauth.get_refresh_token().unwrap();
println!("{:#?}", refresh_token);
source

pub fn build(&mut self) -> GrantSelector<AccessTokenGrant>

source

pub fn build_async(&mut self) -> GrantSelector<AsyncAccessTokenGrant>

source

pub fn v1_logout(&mut self) -> Result<Output, GraphFailure>

Sign the user out using the OneDrive v1.0 endpoint.

Example
use graph_oauth::oauth::OAuth;
let mut oauth = OAuth::new();

oauth.v1_logout().unwrap();
source

pub fn v2_logout(&self) -> Result<Output, GraphFailure>

Sign the user out using the OneDrive v2.0 endpoint.

Example
use graph_oauth::oauth::OAuth;
let mut oauth = OAuth::new();

oauth.v2_logout().unwrap();
source§

impl OAuth

source

pub fn params( &mut self, pairs: Vec<OAuthCredential> ) -> Result<HashMap<String, String>, GraphFailure>

source

pub fn encode_uri( &mut self, grant: GrantType, request_type: GrantRequest ) -> Result<String, GraphFailure>

Trait Implementations§

source§

impl AsFile for OAuth

§

type Error = FromAsError

source§

fn as_file<P: AsRef<Path>>(&self, path: P) -> Result<(), Self::Error>

source§

fn as_file_pretty<P: AsRef<Path>>(&self, path: P) -> Result<(), Self::Error>

source§

impl Clone for OAuth

source§

fn clone(&self) -> OAuth

Returns a copy of the value. Read more
1.0.0 · source§

fn clone_from(&mut self, source: &Self)

Performs copy-assignment from source. Read more
source§

impl Debug for OAuth

source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more
source§

impl Default for OAuth

source§

fn default() -> OAuth

Returns the “default value” for a type. Read more
source§

impl<'de> Deserialize<'de> for OAuth

source§

fn deserialize<__D>(__deserializer: __D) -> Result<Self, __D::Error>where __D: Deserializer<'de>,

Deserialize this value from the given Serde deserializer. Read more
source§

impl<V: ToString> Extend<(OAuthCredential, V)> for OAuth

Extend the OAuth credentials.

Example

let mut map: HashMap<OAuthCredential, &str> = HashMap::new();
map.insert(OAuthCredential::ClientId, "client_id");
map.insert(OAuthCredential::ClientSecret, "client_secret");

oauth.extend(map);
source§

fn extend<I: IntoIterator<Item = (OAuthCredential, V)>>(&mut self, iter: I)

Extends a collection with the contents of an iterator. Read more
source§

fn extend_one(&mut self, item: A)

🔬This is a nightly-only experimental API. (extend_one)
Extends a collection with exactly one element.
source§

fn extend_reserve(&mut self, additional: usize)

🔬This is a nightly-only experimental API. (extend_one)
Reserves capacity in a collection for the given number of additional elements. Read more
source§

impl FromFile<OAuth> for OAuth

§

type Error = FromAsError

source§

fn from_file<P: AsRef<Path>>(path: P) -> Result<Self, Self::Error>where for<'de> Self: Deserialize<'de>,

source§

impl PartialEq<OAuth> for OAuth

source§

fn eq(&self, other: &OAuth) -> bool

This method tests for self and other values to be equal, and is used by ==.
1.0.0 · source§

fn ne(&self, other: &Rhs) -> bool

This method tests for !=. The default implementation is almost always sufficient, and should not be overridden without very good reason.
source§

impl Serialize for OAuth

source§

fn serialize<__S>(&self, __serializer: __S) -> Result<__S::Ok, __S::Error>where __S: Serializer,

Serialize this value into the given Serde serializer. Read more
source§

impl Eq for OAuth

source§

impl StructuralEq for OAuth

source§

impl StructuralPartialEq for OAuth

Auto Trait Implementations§

§

impl RefUnwindSafe for OAuth

§

impl Send for OAuth

§

impl Sync for OAuth

§

impl Unpin for OAuth

§

impl UnwindSafe for OAuth

Blanket Implementations§

source§

impl<T> Any for Twhere T: 'static + ?Sized,

source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
source§

impl<T> Borrow<T> for Twhere T: ?Sized,

const: unstable · source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
source§

impl<T> BorrowMut<T> for Twhere T: ?Sized,

const: unstable · source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
source§

impl<Q, K> Equivalent<K> for Qwhere Q: Eq + ?Sized, K: Borrow<Q> + ?Sized,

source§

fn equivalent(&self, key: &K) -> bool

Compare self to key and return true if they are equal.
source§

impl<T> From<T> for T

const: unstable · source§

fn from(t: T) -> T

Returns the argument unchanged.

source§

impl<T> Instrument for T

source§

fn instrument(self, span: Span) -> Instrumented<Self>

Instruments this type with the provided Span, returning an Instrumented wrapper. Read more
source§

fn in_current_span(self) -> Instrumented<Self>

Instruments this type with the current Span, returning an Instrumented wrapper. Read more
source§

impl<T, U> Into<U> for Twhere U: From<T>,

const: unstable · source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

source§

impl<T> ToOwned for Twhere T: Clone,

§

type Owned = T

The resulting type after obtaining ownership.
source§

fn to_owned(&self) -> T

Creates owned data from borrowed data, usually by cloning. Read more
source§

fn clone_into(&self, target: &mut T)

Uses borrowed data to replace owned data, usually by cloning. Read more
source§

impl<T, U> TryFrom<U> for Twhere U: Into<T>,

§

type Error = Infallible

The type returned in the event of a conversion error.
const: unstable · source§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
source§

impl<T, U> TryInto<U> for Twhere U: TryFrom<T>,

§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
const: unstable · source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.
source§

impl<T> WithSubscriber for T

source§

fn with_subscriber<S>(self, subscriber: S) -> WithDispatch<Self>where S: Into<Dispatch>,

Attaches the provided Subscriber to this type, returning a WithDispatch wrapper. Read more
source§

fn with_current_subscriber(self) -> WithDispatch<Self>

Attaches the current default Subscriber to this type, returning a WithDispatch wrapper. Read more
source§

impl<T> DeserializeOwned for Twhere T: for<'de> Deserialize<'de>,