{"id":3465,"date":"2024-10-04T13:52:56","date_gmt":"2024-10-04T11:52:56","guid":{"rendered":"https:\/\/nguenkam.com\/blog\/?p=3465"},"modified":"2024-10-04T13:52:56","modified_gmt":"2024-10-04T11:52:56","slug":"oauth-for-beginners-a-comprehensive-guide","status":"publish","type":"post","link":"https:\/\/nguenkam.com\/blog\/index.php\/2024\/10\/04\/oauth-for-beginners-a-comprehensive-guide\/","title":{"rendered":"OAuth for Beginners: A Comprehensive Guide"},"content":{"rendered":"\n<p>OAuth (Open Authorization) is an open standard protocol that allows users to grant third-party applications access to their resources without sharing their credentials. It is commonly used to enable secure access to user data across different applications.<\/p>\n\n\n\n<h4>Why Should We Use OAuth?<\/h4>\n\n\n\n<ol><li><strong>Security<\/strong>: OAuth allows users to share specific data without revealing their passwords.<\/li><li><strong>User Experience<\/strong>: Users can log in easily using existing accounts (like Google or Facebook).<\/li><li><strong>Granular Access Control<\/strong>: Developers can specify which resources an application can access.<\/li><li><strong>Scalability<\/strong>: OAuth is well-suited for modern web applications that interact with multiple third-party services.<\/li><\/ol>\n\n\n\n<h4>Basics of OAuth<\/h4>\n\n\n\n<p>OAuth typically involves three roles:<\/p>\n\n\n\n<ol><li><strong>Resource Owner<\/strong>: The user who grants access to their resources.<\/li><li><strong>Client<\/strong>: The application requesting access to the resources.<\/li><li><strong>Authorization Server<\/strong>: The server that manages authorization and issues tokens.<\/li><\/ol>\n\n\n\n<h4>OAuth Flow<\/h4>\n\n\n\n<ol><li>The user is redirected to the authorization page of the Authorization Server.<\/li><li>The user logs in and grants permission to the client.<\/li><li>The Authorization Server returns an authorization code.<\/li><li>The client exchanges this code for an access token from the Authorization Server.<\/li><li>The client uses the access token to access protected resources.<\/li><\/ol>\n\n\n\n<h4>Code Example: OAuth 2.0 with Java Spring Boot and Angular<\/h4>\n\n\n\n<p>This example demonstrates how to implement OAuth 2.0 in a Java Spring Boot application with an Angular frontend to access the GitHub API.<\/p>\n\n\n\n<h4><span class=\"has-inline-color has-vivid-cyan-blue-color\">Step 1: Set Up the Spring Boot Application<\/span><\/h4>\n\n\n\n<p>1. Create a Spring Boot Project<\/p>\n\n\n\n<ul><li>Spring Web<\/li><li>Spring Security<\/li><li>OAuth2 Client<\/li><\/ul>\n\n\n\n<p>2. Configure\u00a0<code>application.yml<\/code><\/p>\n\n\n\n<pre class=\"wp-block-code has-small-font-size\"><code>spring:\r\n  security:\r\n    oauth2:\r\n      client:\r\n        registration:\r\n          github:\r\n            client-id: YOUR_CLIENT_ID\r\n            client-secret: YOUR_CLIENT_SECRET\r\n            scope: read:user\r\n            redirect-uri: \"{baseUrl}\/login\/oauth2\/code\/{registrationId}\"\r\n        provider:\r\n          github:\r\n            authorization-uri: https:\/\/github.com\/login\/oauth\/authorize\r\n            token-uri: https:\/\/github.com\/login\/oauth\/access_token\r\n            user-info-uri: https:\/\/api.github.com\/user\r<\/code><\/pre>\n\n\n\n<div style=\"height:100px\" aria-hidden=\"true\" class=\"wp-block-spacer\"><\/div>\n\n\n\n<h4><span class=\"has-inline-color has-vivid-cyan-blue-color\">2. Create a Security Configuration<\/span><\/h4>\n\n\n\n<p>The <code>SecurityConfig<\/code> class is crucial for defining how security is handled in your Spring Boot application. Here\u2019s a breakdown of its components:<\/p>\n\n\n\n<pre class=\"wp-block-code has-small-font-size\"><code>import org.springframework.context.annotation.Configuration;\r\nimport org.springframework.security.config.annotation.web.builders.HttpSecurity;\r\nimport org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;\r\nimport org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;\r\n\r\n@Configuration\r\n@EnableWebSecurity\r\npublic class SecurityConfig extends WebSecurityConfigurerAdapter {\r\n    @Override\r\n    protected void configure(HttpSecurity http) throws Exception {\r\n        http\r\n            .authorizeRequests()\r\n            .antMatchers(\"\/\", \"\/login\").permitAll() \/\/ Allow public access to these endpoints\r\n            .anyRequest().authenticated()\/\/ Require authentication for all other requests\r\n            .and()\r\n            .oauth2Login();\r\n    }\r\n}\r<\/code><\/pre>\n\n\n\n<ul><li><strong><code>@Configuration<\/code><\/strong>: Indicates that this class provides Spring configuration.<\/li><li><strong><code>@EnableWebSecurity<\/code><\/strong>: Enables Spring Security\u2019s web security support.<\/li><li><strong><code>authorizeRequests()<\/code><\/strong>: Configures URL-based authorization.<ul><li><strong><code>.antMatchers(\"\/\", \"\/login\").permitAll()<\/code><\/strong>: Allows unauthenticated access to the root (&#8220;\/&#8221;) and login (&#8220;\/login&#8221;) endpoints.<\/li><li><strong><code>.anyRequest().authenticated()<\/code><\/strong>: Requires authentication for all other requests.<\/li><\/ul><\/li><li><strong><code>oauth2Login()<\/code><\/strong>: Enables OAuth2 login support, which handles the redirection to the authorization server (GitHub in this case).<\/li><\/ul>\n\n\n\n<h4><strong>Authorization Flow Explained<\/strong><\/h4>\n\n\n\n<p>Here\u2019s how the OAuth2 authorization flow works in detail:<\/p>\n\n\n\n<h5> 1: User Initiates Login<\/h5>\n\n\n\n<p>When a user tries to access a protected resource (any URL other than &#8220;\/&#8221; or &#8220;\/login&#8221;), they are redirected to the login page. This page typically includes a button or link to log in via GitHub.<\/p>\n\n\n\n<h5> 2: Redirect to GitHub<\/h5>\n\n\n\n<p>When the user clicks the login button, they are redirected to the GitHub authorization page. This redirection is handled by Spring Security automatically due to the <code>oauth2Login()<\/code> configuration. The request includes parameters like the client ID, redirect URI, and requested scopes.<\/p>\n\n\n\n<h5> 3: User Grants Permission<\/h5>\n\n\n\n<p>On the GitHub authorization page, the user logs in (if not already logged in) and is prompted to authorize the application to access their data (like user profile information).<\/p>\n\n\n\n<h5>4: Authorization Code Received<\/h5>\n\n\n\n<p>Once the user grants permission, GitHub redirects the user back to your application\u2019s specified redirect URI (configured in <code>application.yml<\/code>). This URI includes an authorization code as a query parameter.<\/p>\n\n\n\n<h5>5: Exchange Authorization Code for Access Token<\/h5>\n\n\n\n<p>Spring Security automatically handles the exchange of the authorization code for an access token. It sends a request to GitHub\u2019s token endpoint with the authorization code, client ID, and client secret.<\/p>\n\n\n\n<h5>6: Access Protected Resources<\/h5>\n\n\n\n<p>With the access token received, the application can now make authorized requests to the GitHub API on behalf of the user. For example, it can fetch the user&#8217;s profile information using the <code>\/user<\/code> endpoint.<\/p>\n\n\n\n<div style=\"height:100px\" aria-hidden=\"true\" class=\"wp-block-spacer\"><\/div>\n\n\n\n<h4><span class=\"has-inline-color has-vivid-cyan-blue-color\">Step 3: Create the Angular Application<\/span><\/h4>\n\n\n\n<p>1. Set Up Angular Project<\/p>\n\n\n\n<p>Create a new Angular project using the Angular CLI:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>ng new oauth-demo\r\ncd oauth-demo\r<\/code><\/pre>\n\n\n\n<p>2. Create a Service to Handle Authentication<\/p>\n\n\n\n<pre class=\"wp-block-code has-small-font-size\"><code>import { Injectable } from '@angular\/core';\r\nimport { HttpClient } from '@angular\/common\/http';\r\n\r\n@Injectable({\r\n  providedIn: 'root'\r\n})\r\nexport class AuthService {\r\n  private apiUrl = 'http:\/\/localhost:8080'; \/\/ Your Spring Boot API URL\r\n\r\n  constructor(private http: HttpClient) {}\r\n\r\n  getUserProfile() {\r\n    return this.http.get(`${this.apiUrl}\/user`);\r\n  }\r\n}\r<\/code><\/pre>\n\n\n\n<p>3. Create a Component to Display User Information<\/p>\n\n\n\n<pre class=\"wp-block-code has-small-font-size\"><code>import { Component, OnInit } from '@angular\/core';\r\nimport { AuthService } from '.\/auth.service';\r\n\r\n@Component({\r\n  selector: 'app-profile',\r\n  template: `\r\n    &lt;h1>User Profile&lt;\/h1>\r\n    &lt;pre>{{ user | json }}&lt;\/pre>\r\n  `\r\n})\r\nexport class ProfileComponent implements OnInit {\r\n  user: any;\r\n\r\n  constructor(private authService: AuthService) {}\r\n\r\n  ngOnInit() {\r\n    this.authService.getUserProfile().subscribe(data => {\r\n      this.user = data;\r\n    });\r\n  }\r\n}\r<\/code><\/pre>\n\n\n\n<h4><span class=\"has-inline-color has-vivid-cyan-blue-color\">Step 4: Explanation of the Code<\/span><\/h4>\n\n\n\n<ul><li><strong>Spring Boot<\/strong>: The backend handles OAuth authentication and provides user data from GitHub.<\/li><li><strong>Angular<\/strong>: The frontend interacts with the Spring Boot API to fetch and display user information.<\/li><li><strong>Security Configuration<\/strong>: Defines which endpoints are secured and enables OAuth2 login.<\/li><li><strong>Authorization Flow<\/strong>: When users log in, they are redirected to GitHub for authentication, and upon successful login, they are redirected back to the application.<\/li><\/ul>\n\n\n\n<h4>Advantages of OAuth in Special Cases<\/h4>\n\n\n\n<ol><li><strong>Mobile Applications<\/strong>: Users can log in quickly without entering passwords.<\/li><li><strong>Third-Party Integrations<\/strong>: Simplifies the integration of services like Google Drive or Dropbox into your applications.<\/li><li><strong>Enterprise Applications<\/strong>: Enables centralized user management and access control.<\/li><\/ol>\n\n\n\n<div style=\"height:100px\" aria-hidden=\"true\" class=\"wp-block-spacer\"><\/div>\n\n\n\n<h5>Conclusion<\/h5>\n\n\n\n<p>OAuth is a powerful protocol that enhances security and user experience in modern web applications. By implementing OAuth, developers can create robust and user-friendly applications that meet the demands of today&#8217;s digital landscape. With this guide, you should now have a foundational understanding of OAuth and how to implement it using Java Spring Boot and Angular.<\/p>\n","protected":false},"excerpt":{"rendered":"<p>OAuth (Open Authorization) is an open standard protocol that allows users to grant third-party applications access to their resources without sharing their credentials. It is commonly used to enable secure access to user data across different applications. Why Should We Use OAuth? Security: OAuth allows users to share specific data without revealing their passwords. User [&hellip;]<\/p>\n","protected":false},"author":1,"featured_media":3467,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":[],"categories":[1,37,554,868],"tags":[931,930,301,929,928,927],"_links":{"self":[{"href":"https:\/\/nguenkam.com\/blog\/index.php\/wp-json\/wp\/v2\/posts\/3465"}],"collection":[{"href":"https:\/\/nguenkam.com\/blog\/index.php\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/nguenkam.com\/blog\/index.php\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/nguenkam.com\/blog\/index.php\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/nguenkam.com\/blog\/index.php\/wp-json\/wp\/v2\/comments?post=3465"}],"version-history":[{"count":1,"href":"https:\/\/nguenkam.com\/blog\/index.php\/wp-json\/wp\/v2\/posts\/3465\/revisions"}],"predecessor-version":[{"id":3468,"href":"https:\/\/nguenkam.com\/blog\/index.php\/wp-json\/wp\/v2\/posts\/3465\/revisions\/3468"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/nguenkam.com\/blog\/index.php\/wp-json\/wp\/v2\/media\/3467"}],"wp:attachment":[{"href":"https:\/\/nguenkam.com\/blog\/index.php\/wp-json\/wp\/v2\/media?parent=3465"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/nguenkam.com\/blog\/index.php\/wp-json\/wp\/v2\/categories?post=3465"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/nguenkam.com\/blog\/index.php\/wp-json\/wp\/v2\/tags?post=3465"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}