Skip to content

Commit

Permalink
fix: web cookies workflow integration issues and content update
Browse files Browse the repository at this point in the history
  • Loading branch information
gitcommitshow committed Aug 1, 2022
1 parent b38a90b commit 15a4f0c
Show file tree
Hide file tree
Showing 11 changed files with 80 additions and 40 deletions.
17 changes: 16 additions & 1 deletion app.js
Original file line number Diff line number Diff line change
Expand Up @@ -47,7 +47,22 @@ app.use(function(req, res, next){
next();
})

app.use(cors());
// app.use(cors());

//Using explicit header settings for cors instead of cors package to make it easier to understand what exaxtly we are doing
app.use(function (req, res, next) {
// Website you wish to allow to connect
res.setHeader('Access-Control-Allow-Origin', 'http://localhost:4200');
// Request methods you wish to allow
res.setHeader('Access-Control-Allow-Methods', 'GET, POST, OPTIONS, PUT, PATCH, DELETE');
// Request headers you wish to allow
res.setHeader('Access-Control-Allow-Headers', 'X-Requested-With,content-type,authorization');
// Set to true if you need the website to include cookies in the requests sent
// to the API (e.g. in case you use sessions)
res.setHeader('Access-Control-Allow-Credentials', true);
// Pass to next layer of middleware
next();
});

app.use("/", homeRouter);
app.use("/jwt", jwtRouter);
Expand Down
6 changes: 3 additions & 3 deletions frontend/src/app/app.component.html
Original file line number Diff line number Diff line change
Expand Up @@ -113,12 +113,12 @@
</div>

<nav class="nav justify-content-center py-3 mt-5 nav-footer">
<a class="nav-link" href="#">
<a class="nav-link" href="https://github.com/gitcommitshow/auth-jwt/issues/new">
<i class="fa-solid fa-triangle-exclamation me-1"></i>
{{ "app.reportBug" | transloco }}
</a>
<a class="nav-link" href="#">
<a class="nav-link" href="https://twitter.com/intent/tweet?text=%22Learn%20JWT%20by%20reverse%20engineering%22%20%20%40pradeep_io&url=https://github.com/gitcommitshow/auth-jwt">
<i class="fa-brands fa-twitter me-1"></i>
{{ "app.shareTwitter" | transloco }}
</a>
</nav>
</nav>
2 changes: 1 addition & 1 deletion frontend/src/app/finish/finish.component.html
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@ <h1 class="mb-3 heading">{{ "finish.introduction" | transloco }}</h1>

<div class="celebrate_twitter">
<i class="fa-brands fa-twitter" style="color: #ffd852;"></i>
<a target="_blank" href="#">{{ "finish.celebrate" | transloco}}</a>
<a target="_blank" href="https://twitter.com/intent/tweet?text=Just%20finished%20totorial%20on%20JWT.%20@pradeep_io&url=https://github.com/gitcommitshow/auth-jwt">{{ "finish.celebrate" | transloco}}</a>
</div>

<div class="row">
Expand Down
4 changes: 1 addition & 3 deletions frontend/src/app/send-jwt3/send-jwt3.component.html
Original file line number Diff line number Diff line change
Expand Up @@ -5,12 +5,10 @@ <h1 class="mb-3">{{ "send-jwt3.introduction" | transloco }}</h1>
<hr>

<div *ngIf="successText" class="rectangle">
<img src="assets/images/icon-check-square.png"/>
<span>{{ successText }}</span>
<pre>{{ successText }}</pre>
</div>

<div *ngIf="errorText" class="rectangle error">
<img src="assets/images/icon-error.svg"/>
<span>{{ errorText | transloco | uppercase }}</span>
</div>

Expand Down
10 changes: 4 additions & 6 deletions frontend/src/app/send-jwt4/send-jwt4.component.html
Original file line number Diff line number Diff line change
Expand Up @@ -5,13 +5,11 @@ <h1 class="mb-3">{{ "send-jwt4.introduction" | transloco }}</h1>
<hr>

<div *ngIf="successText" class="rectangle">
<img src="assets/images/icon-check-square.png"/>
<span>{{ successText }}</span>
<pre>{{ successText }}</pre>
</div>

<div *ngIf="errorText" class="rectangle error">
<img src="assets/images/icon-error.svg"/>
<span>{{ errorText | transloco | uppercase }}</span>
<span>{{ errorText | transloco | uppercase }}</span>
</div>

<div class="rectangle1">
Expand Down Expand Up @@ -48,8 +46,8 @@ <h1>{{ "send-jwt4.request" | transloco }}</h1>
<img src="assets/images/icon-arrow-right.svg" alt="">
</button>
</p>

<a class="query" target="_blank" href="#">{{ "send-jwt4.queryParameter" | transloco}}</a>
<br/>
<a class="query" target="_blank" href="https://datatracker.ietf.org/doc/html/rfc6265">{{ "send-jwt4.queryParameter" | transloco}}</a>

</div>

Expand Down
7 changes: 6 additions & 1 deletion frontend/src/app/send-jwt4/send-jwt4.component.scss
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
.rectangle {
width: 667px;
height: 53px;
height: fit-content;
padding: 16.5px 223.1px 15.5px 19.9px;
border-radius: 12px;
border: solid 1px rgba(0, 195, 15, 0.75);
Expand All @@ -20,6 +20,11 @@
}
}

.rectangle.error {
border: solid 1px rgba(255, 5, 5, 0.75);
background-color: rgba(209, 66, 31, 0.15);
}

.rectangle1 {
width: 668px;
height: 529px;
Expand Down
35 changes: 27 additions & 8 deletions frontend/src/app/send-jwt4/send-jwt4.component.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ import { Component, OnInit } from '@angular/core';
import { Router } from '@angular/router';
import { DemoService } from '../shared/services/demo.service';
import { StepService } from '../shared/services/step.service';
import { environment } from '../../environments/environment'

@Component({
selector: 'app-send-jwt4',
Expand All @@ -11,6 +12,7 @@ import { StepService } from '../shared/services/step.service';
})
export class SendJwt4Component implements OnInit {

AUTH_SERVER = `${environment.server}`;
successText = "";
errorText = "";

Expand All @@ -26,17 +28,18 @@ export class SendJwt4Component implements OnInit {
}

getAuthorizePage(){
this.router.navigate(['authorize'])
window.open(this.AUTH_SERVER+"/demo/authorize", "_blank");
// this.router.navigate(['authorize'])
}

getProtectedUserData(){
this.demoService.remote().webCookies().subscribe({
this.demoService.remote().sendTokenViaWebCookies().subscribe({
next: (success: any)=>{
console.log("success")
this.errorText = ""
this.successText = JSON.stringify(success, null, 4)
},
complete: () => console.log("Sent token in header"),
complete: () => console.log("Sent token in cookies"),
error: (error: HttpErrorResponse) => {
this.successText = ""
this.errorText = error.statusText || "Unsuccessful"
Expand All @@ -46,15 +49,31 @@ export class SendJwt4Component implements OnInit {
}

getUser(){
this.demoService.remote().getUser().subscribe((user)=>{
console.log(user)
var token: any = localStorage.getItem('token');
var headers = new HttpHeaders()
.set("Content-Type", "application\/json")
if(token) headers.set("Authorization", token);
this.demoService.remote().getUserViaHeaderOrCookies(headers).subscribe({
next: (success: any)=>{
console.log("success")
this.errorText = ""
this.successText = JSON.stringify(success, null, 4)
},
complete: () => console.log("Sent token in header/cookies"),
error: (error: HttpErrorResponse) => {
this.successText = ""
this.errorText = error.statusText || "Unsuccessful"
console.error('error:', error)
}
})
}

logOut(){
this.demoService.remote().logOut().subscribe(success=>{
console.log(success)
})
let popup = window.open(this.AUTH_SERVER+"/demo/logout", "_blank");
setTimeout(() => popup?.close(), 1000);
// this.demoService.remote().logOut().subscribe(success=>{
// console.log(success)
// })
}

backStep() {
Expand Down
8 changes: 5 additions & 3 deletions frontend/src/app/shared/services/demo.service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -38,18 +38,20 @@ export class DemoService {
return httpRequest.get<any>(url, {headers: headers});
},
login(body: any): Observable<any> {
//NOT TO BE USED. Otherwise, cookies won't set correctly
let url = REMOTE_SERVER+ENDPOINTS.login
return httpRequest.post<any>(url, body);
},
sendTokenViaWebCookies(): Observable<any> {
let url = REMOTE_SERVER+ENDPOINTS.webCookies
return httpRequest.get<any>(url);
return httpRequest.get<any>(url, { withCredentials: true });
},
getUser(): Observable<any> {
getUserViaHeaderOrCookies(headers: any): Observable<any> {
let url = REMOTE_SERVER+ENDPOINTS.getUser
return httpRequest.get<any>(url);
return httpRequest.get<any>(url, { headers: headers, withCredentials: true });
},
logOut(): Observable<any> {
//NOT TO BE USED. Otherwise, cookies won't reset correctly
let url = REMOTE_SERVER+ENDPOINTS.logOut
return httpRequest.get<any>(url);
}
Expand Down
10 changes: 5 additions & 5 deletions frontend/src/assets/i18n/en.json
Original file line number Diff line number Diff line change
Expand Up @@ -125,7 +125,7 @@
},

"send-jwt1": {
"introduction": "2. Send JWT to backend with request to access to resources",
"introduction": "2. Send JWT to backend requesting protected resources",
"ways": "There are 4 ways you can send JWT to backend",
"authenticated": "you have been successfully authenticated",
"request": "Send JWT in request parameter",
Expand All @@ -138,7 +138,7 @@
},

"send-jwt2": {
"introduction": "2. Send JWT to backend with request to access to resources",
"introduction": "2. Send JWT to backend requesting protected resources",
"ways": "There are 4 ways you can send JWT to backend",
"authenticated": "you have been successfully authenticated",
"request": "Send token in form body",
Expand All @@ -152,7 +152,7 @@
},

"send-jwt3": {
"introduction": "2. Send JWT to backend with request to access to resources",
"introduction": "2. Send JWT to backend requesting protected resources",
"ways": "There are 4 ways you can send JWT to backend",
"authenticated": "you have been successfully authenticated",
"request": "Send token in request header",
Expand All @@ -169,7 +169,7 @@
"closeBracket": "}"
},
"send-jwt4": {
"introduction": "2. Send JWT to backend with request to access to resources",
"introduction": "2. Send JWT to backend requesting protected resources",
"ways": "There are 4 ways you can send JWT to backend",
"request": "Send token via cookies",
"request1": "Anything stored in cookies is sent with the request by default. So there's nothing special that you need to do in this case as long as the backend server had set the cookie header when it generted the token.",
Expand All @@ -178,7 +178,7 @@
"step2": "Get protected user data",
"step3" : "User data link accessible via token in authorization header with fall back to cookies",
"step4" : "Logout",
"queryParameter": "Read about standards to send token via headers",
"queryParameter": "Read about securely storing cookies",
"body": "Next: Choosing the best method",
"authenticated": "you have been successfully authenticated"
},
Expand Down
18 changes: 9 additions & 9 deletions routes/demo.js
Original file line number Diff line number Diff line change
Expand Up @@ -111,16 +111,16 @@ router.get('/protected/web-cookies', DemoAuthService.isAuthenticated, function(r

router.get('/user', DemoAuthService.isAuthenticated, function(req, res) {
if (req.wantsJson) {
return res.send(
`<pre>
{
success: true,
user: ${JSON.stringify(req.user)}
}</pre>
<a href="/demo/logout">Logout</a>
`)
return res.status(200).send({ success: true, user: req.user, statusText: "Authorized" })
}
return res.send({ success: true, user: req.user })
res.send(
`<pre>
{
success: true,
user: ${JSON.stringify(req.user)}
}</pre>
<a href="/demo/logout">Logout</a>
`)
})

router.get('/logout', [], function(req, res) {
Expand Down
3 changes: 3 additions & 0 deletions views/demo/authorize.ejs
Original file line number Diff line number Diff line change
@@ -1,9 +1,12 @@
<link rel="stylesheet" href="https://cdn.jsdelivr.net/gh/kognise/water.css@latest/dist/dark.min.css">
<h1>Welcome to the authorization server</h1>
<h2>Sign in</h2>
<form id="login-form" action="/demo/oauth/token" method="POST">
<input value="user" name="username" type="text" placeholder="Username e.g. user"> <br/>
<input value="pass" name="password" type="password" placeholder="Password e.g. pass"> <br/>
<input type="submit" value="Login"> <br/><br/>
<p>After successful login, a cookie <code>access_token</code> will be set in your browser.
<br/>So next time, when you make a request to authorization server, <br/>this cookie <code>access_token</code> will be sent to the auth server.</p>
</form>
<script>
// Cross-origin communication about the login info
Expand Down

0 comments on commit 15a4f0c

Please sign in to comment.