# Struct actix_identity::Identity

source ·

    pub struct Identity(/* private fields */);

Expand description

A verified user identity. It can be used as a request extractor.

The lifecycle of a user identity is tied to the lifecycle of the underlying session. If the session is destroyed (e.g. the session expired), the user identity will be forgotten, de-facto forcing a user log out.

## §Examples

    use actix_web::{
        get, post, Responder, HttpRequest, HttpMessage, HttpResponse
    };
    use actix_identity::Identity;

    #[get("/")]
    async fn index(user: Option<Identity>) -> impl Responder {
        if let Some(user) = user {
            format!("Welcome! {}", user.id().unwrap())
        } else {
            "Welcome Anonymous!".to_owned()
        }
    }

    #[post("/login")]
    async fn login(request: HttpRequest) -> impl Responder {
        Identity::login(&request.extensions(), "User1".into());
        HttpResponse::Ok()
    }

    #[post("/logout")]
    async fn logout(user: Identity) -> impl Responder {
        user.logout();
        HttpResponse::Ok()
    }

## §Extractor Behaviour

What happens if you try to extract an `Identity` out of a request that does not have a valid identity attached? The API will return a `401 UNAUTHORIZED` to the caller.

If you want to customise this behaviour, consider extracting `Option<Identity>` or `Result<Identity, actix_web::Error>` instead of a bare `Identity`: you will then be fully in control of the error path.

### §Examples

    use actix_web::{http::header::LOCATION, get, HttpResponse, Responder};
    use actix_identity::Identity;

    #[get("/")]
    async fn index(user: Option<Identity>) -> impl Responder {
        if let Some(user) = user {
            HttpResponse::Ok().finish()
        } else {
            // Redirect to login page if unauthenticated
            HttpResponse::TemporaryRedirect()
                .insert_header((LOCATION, "/login"))
                .finish()
        }
    }

## Implementations§

source §

### impl Identity

source

#### pub fn id(&self) -> Result<String, GetIdentityError>

Return the user id associated to the current session.

##### §Examples

    use actix_web::{get, Responder};
    use actix_identity::Identity;

    #[get("/")]
    async fn index(user: Option<Identity>) -> impl Responder {
        if let Some(user) = user {
            format!("Welcome! {}", user.id().unwrap())
        } else {
            "Welcome Anonymous!".to_owned()
        }
    }

source

#### pub fn login(ext: &Extensions, id: String) -> Result<Self, LoginError>

Attach a valid user identity to the current session.

This method should be called after you have successfully authenticated the user. After `login` has been called, the user will be able to access all routes that require a valid `Identity`.

##### §Examples

    use actix_web::{post, Responder, HttpRequest, HttpMessage, HttpResponse};
    use actix_identity::Identity;

    #[post("/login")]
    async fn login(request: HttpRequest) -> impl Responder {
        Identity::login(&request.extensions(), "User1".into());
        HttpResponse::Ok()
    }

source

#### pub fn logout(self)

Remove the user identity from the current session.

After `logout` has been called, the user will no longer be able to access routes that require a valid `Identity`.

The behaviour on logout is determined by `IdentityMiddlewareBuilder::logout_behaviour`.

##### §Examples

    use actix_web::{post, Responder, HttpResponse};
    use actix_identity::Identity;

    #[post("/logout")]
    async fn logout(user: Identity) -> impl Responder {
        user.logout();
        HttpResponse::Ok()
    }

## Trait Implementations§

source §

### impl FromRequest for Identity

Extractor implementation for `Identity`.

#### §Examples

    use actix_web::{get, Responder};
    use actix_identity::Identity;

    #[get("/")]
    async fn index(user: Option<Identity>) -> impl Responder {
        if let Some(user) = user {
            format!("Welcome! {}", user.id().unwrap())
        } else {
            "Welcome Anonymous!".to_owned()
        }
    }

§

#### type Error = Error

The associated error which can be returned.
§

#### type Future = Ready<Result<Identity, <Identity as FromRequest>::Error>>

Future that resolves to a `Self`. Read more
source §

#### fn from_request(req: &HttpRequest, _: &mut Payload) -> Self::Future

Create a `Self` from request parts asynchronously.
§

#### fn extract(req: &HttpRequest) -> Self::Future

Create a `Self` from request head asynchronously. Read more

## Auto Trait Implementations§

§

### impl !RefUnwindSafe for Identity

§

### impl !Send for Identity

§

### impl !Sync for Identity

§

### impl Unpin for Identity

§

### impl !UnwindSafe for Identity

## Blanket Implementations§

source §

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

source §

#### fn type_id(&self) -> TypeId

Gets the `TypeId` of `self`. Read more
source §

### impl<T> Borrow<T> for T
where T: ?Sized,

source §

#### fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
source §

### impl<T> BorrowMut<T> for T
where T: ?Sized,

source §

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

Mutably borrows from an owned value. Read more
source §

### impl<T> From<T> for T

source §

#### fn from(t: T) -> T

Returns the argument unchanged.

§

### impl<T> Instrument for T

§

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

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

#### 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 T
where U: From<T>,

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> Same for T

§

#### type Output = T

Should always be `Self`
source §

### impl<T, U> TryFrom<U> for T
where U: Into<T>,

§

#### type Error = Infallible

The type returned in the event of a conversion error.
source §

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

Performs the conversion.
source §

### impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

§

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

The type returned in the event of a conversion error.
source §

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

Performs the conversion.
§

### impl<V, T> VZip<V> for T
where V: MultiLane<T>,

§

#### fn vzip(self) -> V

§

### impl<T> WithSubscriber for T

§

#### 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
§

#### fn with_current_subscriber(self) -> WithDispatch<Self>

Attaches the current default `Subscriber` to this type, returning a [`WithDispatch`] wrapper. Read more