<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0" xmlns:atom="http://www.w3.org/2005/Atom" xmlns:dc="http://purl.org/dc/elements/1.1/">
  <channel>
    <title>DEV Community: Alessandro Prencipe</title>
    <description>The latest articles on DEV Community by Alessandro Prencipe (@alessandro_prencipe).</description>
    <link>https://dev.to/alessandro_prencipe</link>
    <image>
      <url>https://media2.dev.to/dynamic/image/width=90,height=90,fit=cover,gravity=auto,format=auto/https:%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Fuser%2Fprofile_image%2F890330%2F18785f5d-0eb6-406b-a332-03dc40c123f4.png</url>
      <title>DEV Community: Alessandro Prencipe</title>
      <link>https://dev.to/alessandro_prencipe</link>
    </image>
    <atom:link rel="self" type="application/rss+xml" href="https://dev.to/feed/alessandro_prencipe"/>
    <language>en</language>
    <item>
      <title>AWS Amplify how to set user session manually</title>
      <dc:creator>Alessandro Prencipe</dc:creator>
      <pubDate>Fri, 28 Oct 2022 09:50:40 +0000</pubDate>
      <link>https://dev.to/alessandro_prencipe/aws-amplify-how-to-set-user-session-manually-6oi</link>
      <guid>https://dev.to/alessandro_prencipe/aws-amplify-how-to-set-user-session-manually-6oi</guid>
      <description>&lt;p&gt;Here's how I solved this problem using amazon-cognito-identity-js&lt;/p&gt;

&lt;p&gt;const userPool = new CognitoUserPool({&lt;br&gt;
      UserPoolId: 'userPoolId',&lt;br&gt;
      ClientId: 'userPoolWebClientId',&lt;br&gt;
    });&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;const cognitoIdToken = new CognitoIdToken({
  IdToken: idToken,
});
const cognitoAccessToken = new CognitoAccessToken({
  AccessToken: accessToken,
});
const cognitoRefreshToken = new CognitoRefreshToken({
  RefreshToken: refreshToken,
});
const username = (cognitoIdToken.payload as any).email;

const user = new CognitoUser({
  Username: username,
  Pool: userPool,
});
user.setSignInUserSession(
  new CognitoUserSession({
    AccessToken: cognitoAccessToken,
    IdToken: cognitoIdToken,
    RefreshToken: cognitoRefreshToken,
  })
);
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

</description>
      <category>aws</category>
      <category>amplify</category>
      <category>angular</category>
      <category>typescript</category>
    </item>
    <item>
      <title>How I implemented the authentication with Amplify in Angular</title>
      <dc:creator>Alessandro Prencipe</dc:creator>
      <pubDate>Thu, 20 Oct 2022 09:25:13 +0000</pubDate>
      <link>https://dev.to/alessandro_prencipe/how-i-implemented-the-authentication-with-amplify-in-angular-5o0</link>
      <guid>https://dev.to/alessandro_prencipe/how-i-implemented-the-authentication-with-amplify-in-angular-5o0</guid>
      <description>&lt;p&gt;Authentication with Amplify is very easy even though I struggled a little bit at the beginning.&lt;br&gt;
Here's how I implemented my authentication. Let me know what you think.&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;I created my auth auth.service.ts with all the possible operations:&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;`&lt;br&gt;
import { Injectable } from '@angular/core';&lt;br&gt;
import { CognitoUser } from 'amazon-cognito-identity-js';&lt;br&gt;
import { Auth } from 'aws-amplify';&lt;br&gt;
import { CognitoHostedUIIdentityProvider } from '@aws-amplify/auth';&lt;/p&gt;

&lt;p&gt;@Injectable({&lt;br&gt;
  providedIn: 'root',&lt;br&gt;
})&lt;br&gt;
export class AuthService {&lt;br&gt;
  user: CognitoUser | undefined;&lt;br&gt;
  constructor() {}&lt;/p&gt;

&lt;p&gt;async signIn({&lt;br&gt;
    email,&lt;br&gt;
    psw,&lt;br&gt;
  }: {&lt;br&gt;
    email: string;&lt;br&gt;
    psw: string;&lt;br&gt;
  }): Promise {&lt;br&gt;
    return Auth.signIn(email, psw);&lt;br&gt;
  }&lt;/p&gt;

&lt;p&gt;async setNewPasswordFirstLogin({&lt;br&gt;
    psw,&lt;br&gt;
  }: {&lt;br&gt;
    psw: string;&lt;br&gt;
  }): Promise {&lt;br&gt;
    return Auth.completeNewPassword(this.user, psw);&lt;br&gt;
  }&lt;/p&gt;

&lt;p&gt;async currentAuthenticatedUser(): Promise {&lt;br&gt;
    return Auth.currentAuthenticatedUser();&lt;br&gt;
  }&lt;/p&gt;

&lt;p&gt;async signOut(): Promise {&lt;br&gt;
    return Auth.signOut();&lt;br&gt;
  }&lt;/p&gt;

&lt;p&gt;async forgotPasswordSendEmail({&lt;br&gt;
    email,&lt;br&gt;
  }: {&lt;br&gt;
    email: string;&lt;br&gt;
  }): Promise {&lt;br&gt;
    return Auth.forgotPassword(email);&lt;br&gt;
  }&lt;/p&gt;

&lt;p&gt;async forgotPasswordSetNewPsw({&lt;br&gt;
    email,&lt;br&gt;
    psw,&lt;br&gt;
    code,&lt;br&gt;
  }: {&lt;br&gt;
    email: string;&lt;br&gt;
    psw: string;&lt;br&gt;
    code: string;&lt;br&gt;
  }): Promise {&lt;br&gt;
    return Auth.forgotPasswordSubmit(email, code, psw);&lt;br&gt;
  }&lt;/p&gt;

&lt;p&gt;setUser(user: CognitoUser) {&lt;br&gt;
    this.user = user;&lt;br&gt;
  }&lt;/p&gt;

&lt;p&gt;async federatedSignIn({ type }: { type: string }) {&lt;br&gt;
    let provider: CognitoHostedUIIdentityProvider | undefined = undefined;&lt;br&gt;
    if (type === 'Google') provider = CognitoHostedUIIdentityProvider.Google;&lt;br&gt;
    if (type === 'Apple') provider = CognitoHostedUIIdentityProvider.Apple;&lt;br&gt;
    if (type === 'Facebook')&lt;br&gt;
      provider = CognitoHostedUIIdentityProvider.Facebook;&lt;br&gt;
    if (provider) {&lt;br&gt;
      return Auth.federatedSignIn({&lt;br&gt;
        provider: provider,&lt;br&gt;
      });&lt;br&gt;
    }&lt;br&gt;
    return;&lt;br&gt;
  }&lt;br&gt;
}&lt;br&gt;
`&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;I created the jwt.interceptor.ts, this was the toughest part that I implemented.
&lt;/li&gt;
&lt;/ul&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;import { Injectable } from '@angular/core';
import {
  HttpRequest,
  HttpHandler,
  HttpEvent,
  HttpInterceptor,
} from '@angular/common/http';
import { Observable, from, switchMap, catchError, throwError } from 'rxjs';
import { environment } from 'src/environments/environment';
import { AuthService } from 'src/app/core/services/auth.service';
import { Auth } from 'aws-amplify';
import { CognitoUserSession } from 'amazon-cognito-identity-js';

@Injectable()
export class JwtInterceptor implements HttpInterceptor {
  constructor(private authService: AuthService) {}

  intercept(
    request: HttpRequest&amp;lt;any&amp;gt;,
    next: HttpHandler
  ): Observable&amp;lt;HttpEvent&amp;lt;any&amp;gt;&amp;gt; {
    return from(Auth.currentSession()).pipe(
      switchMap((auth: any) =&amp;gt; {
        // switchMap() is used instead of map().
        const jwt: string = auth.idToken.jwtToken;
        const authRequest = request.clone({
          setHeaders: {
            Authorization: `Bearer ${jwt}`,
          },
        });
        return next.handle(authRequest);
      }),
      catchError((err) =&amp;gt; {
        if (err.status) {
          return throwError(() =&amp;gt; new Error(err));
        }
      })
    );
  }
}

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;ul&gt;
&lt;li&gt;I implemented the error.interceptor.ts as well for the auto logout
&lt;/li&gt;
&lt;/ul&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;import { Injectable } from '@angular/core';
import {
  HttpRequest,
  HttpHandler,
  HttpEvent,
  HttpInterceptor,
} from '@angular/common/http';
import { Observable, throwError } from 'rxjs';
import { catchError } from 'rxjs/operators';
import { Router } from '@angular/router';
import { AuthService } from '../services/auth.service';
import { LoaderService } from 'src/app/shared/services/loader.service';

/**
 * This is used to logout the user, when the server responds with an unathorized status code.
 * Especially when the session token expires.
 * @export
 * @class ErrorInterceptor
 * @implements {HttpInterceptor}
 */
@Injectable()
export class ErrorInterceptor implements HttpInterceptor {
  constructor(
    private readonly router: Router,
    private readonly authService: AuthService,
  ) {}

  /**
   * Interceptor intercepts the responses, and then process based on the received status code
   * @param {HttpRequest&amp;lt;any&amp;gt;} request
   * @param {HttpHandler} next
   * @returns {Observable&amp;lt;HttpEvent&amp;lt;any&amp;gt;&amp;gt;}
   * @memberof ErrorInterceptor
   */
  intercept(
    request: HttpRequest&amp;lt;any&amp;gt;,
    next: HttpHandler
  ): Observable&amp;lt;HttpEvent&amp;lt;any&amp;gt;&amp;gt; {
    return next.handle(request).pipe(
      catchError((err) =&amp;gt; {
        if (err.status === 401) {
          // auto logout if 401 response returned from api
          this.authService
            .signOut()
            .then(() =&amp;gt; {
              this.router.navigate(['/auth']);
            })
            .catch((err) =&amp;gt; console.log(err));
        }

        // err.error is not null, if the ResponsenEntity contains an Exception
        // err.error.message will give the custom message send from the server
        const error = err.error.errorMessage || err.statusText;
        return throwError(() =&amp;gt; new Error(error));
      })
    );
  }
}

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;I created a login component but it is a simple component that calls the service.&lt;/p&gt;

&lt;p&gt;Let me know what you think about this implementation and if there's a better way to do this particular task.&lt;/p&gt;

</description>
      <category>angular</category>
      <category>amplify</category>
      <category>aws</category>
      <category>authentication</category>
    </item>
  </channel>
</rss>
