Danix
Danix
JCHJava Community | Help. Code. Learn.
Created by Danix on 2/14/2025 in #java-help
Github Authorization via pkce
@Bean
SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
http.cors(cors -> corsFilter())
.csrf(csrf -> csrf.disable()) // Disable CSRF for stateless APIs
.authorizeHttpRequests(auth -> auth
.requestMatchers("/api/admin/**").hasAuthority("ADMIN")
.requestMatchers("/api/user/**").hasAnyAuthority("USER" , "ADMIN")
.requestMatchers("/api/auth/**" , "/api/auth/github").permitAll()
.anyRequest().authenticated() // Protect all other endpoints
)
.sessionManagement(sess -> sess
.sessionCreationPolicy(SessionCreationPolicy.STATELESS) // No sessions
).exceptionHandling(e -> {
e.authenticationEntryPoint((req, res, ex) -> {
res.sendError(HttpServletResponse.SC_UNAUTHORIZED, ex.getMessage());
});
})
.addFilterBefore(jwtFilter, UsernamePasswordAuthenticationFilter.class); // Add JWT filter

return http.build();
}
@Bean
SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
http.cors(cors -> corsFilter())
.csrf(csrf -> csrf.disable()) // Disable CSRF for stateless APIs
.authorizeHttpRequests(auth -> auth
.requestMatchers("/api/admin/**").hasAuthority("ADMIN")
.requestMatchers("/api/user/**").hasAnyAuthority("USER" , "ADMIN")
.requestMatchers("/api/auth/**" , "/api/auth/github").permitAll()
.anyRequest().authenticated() // Protect all other endpoints
)
.sessionManagement(sess -> sess
.sessionCreationPolicy(SessionCreationPolicy.STATELESS) // No sessions
).exceptionHandling(e -> {
e.authenticationEntryPoint((req, res, ex) -> {
res.sendError(HttpServletResponse.SC_UNAUTHORIZED, ex.getMessage());
});
})
.addFilterBefore(jwtFilter, UsernamePasswordAuthenticationFilter.class); // Add JWT filter

return http.build();
}
9 replies
JCHJava Community | Help. Code. Learn.
Created by Danix on 2/14/2025 in #java-help
Github Authorization via pkce
package com.scriptenhancer.controllers;

import java.util.Map;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

@RestController
@RequestMapping("/api/auth")
public class OAuthController {

@Value("${spring.security.oauth2.client.registration.github.client-id}")
private String clientId;

@Value("${spring.security.oauth2.client.registration.github.client-secret}")
private String clientSecret;

@Value("${spring.security.oauth2.client.registration.github.redirect-uri}")
private String redirectUri;

private final RestTemplate restTemplate = new RestTemplate();

@PostMapping("/api/auth/github")
public ResponseEntity<?> handleGitHubCallback(@RequestBody Map<String, String> params) {
String code = params.get("code");
String codeVerifier = params.get("codeVerifier");

// Handle the code and codeVerifier here
System.out.println("The code verifier is : " +codeVerifier);
System.out.println("The code is : " +code);

return ResponseEntity.ok().body("GitHub OAuth Success");
}
}
package com.scriptenhancer.controllers;

import java.util.Map;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

@RestController
@RequestMapping("/api/auth")
public class OAuthController {

@Value("${spring.security.oauth2.client.registration.github.client-id}")
private String clientId;

@Value("${spring.security.oauth2.client.registration.github.client-secret}")
private String clientSecret;

@Value("${spring.security.oauth2.client.registration.github.redirect-uri}")
private String redirectUri;

private final RestTemplate restTemplate = new RestTemplate();

@PostMapping("/api/auth/github")
public ResponseEntity<?> handleGitHubCallback(@RequestBody Map<String, String> params) {
String code = params.get("code");
String codeVerifier = params.get("codeVerifier");

// Handle the code and codeVerifier here
System.out.println("The code verifier is : " +codeVerifier);
System.out.println("The code is : " +code);

return ResponseEntity.ok().body("GitHub OAuth Success");
}
}
9 replies
JCHJava Community | Help. Code. Learn.
Created by Danix on 2/14/2025 in #java-help
Github Authorization via pkce
Spring boot
Spring boot
9 replies
JCHJava Community | Help. Code. Learn.
Created by Danix on 2/14/2025 in #java-help
Github Authorization via pkce
export const generateRandomString = (length) => {
const array = new Uint32Array(length);
window.crypto.getRandomValues(array);
return Array.from(array, (dec) => ('0' + dec.toString(16)).slice(-2)).join('');
};

const sha256 = async (plain) => {
const encoder = new TextEncoder();
const data = encoder.encode(plain);
const hash = await window.crypto.subtle.digest('SHA-256', data);
return btoa(String.fromCharCode(...new Uint8Array(hash)))
.replace(/\+/g, '-')
.replace(/\//g, '_')
.replace(/=+$/, '');
};

export const generateCodeVerifier = () => generateRandomString(64);
export const generateCodeChallenge = async (verifier) => sha256(verifier);
export const generateRandomString = (length) => {
const array = new Uint32Array(length);
window.crypto.getRandomValues(array);
return Array.from(array, (dec) => ('0' + dec.toString(16)).slice(-2)).join('');
};

const sha256 = async (plain) => {
const encoder = new TextEncoder();
const data = encoder.encode(plain);
const hash = await window.crypto.subtle.digest('SHA-256', data);
return btoa(String.fromCharCode(...new Uint8Array(hash)))
.replace(/\+/g, '-')
.replace(/\//g, '_')
.replace(/=+$/, '');
};

export const generateCodeVerifier = () => generateRandomString(64);
export const generateCodeChallenge = async (verifier) => sha256(verifier);
9 replies
JCHJava Community | Help. Code. Learn.
Created by Danix on 2/14/2025 in #java-help
Github Authorization via pkce
import { generateCodeChallenge, generateCodeVerifier , generateRandomString} from "../../utils/pkce";

export const LoginWithGithub = async () => {
const codeVerifier = generateCodeVerifier();
const codeChallenge = await generateCodeChallenge(codeVerifier);

// Store the code verifier in session storage (temporary)
sessionStorage.setItem('code_verifier', codeVerifier);

const params = new URLSearchParams({
client_id: 'Ov23li7XMZBxnH3K31ME', // Replace with your GitHub client ID
redirect_uri: 'http://localhost:5173/oauth2/callback/github', // Must match GitHub OAuth app settings
scope: 'user:email', // Requested scopes
response_type: 'code',
state: generateRandomString(16), // Optional but recommended for security
code_challenge: codeChallenge,
code_challenge_method: 'S256',
});

// Redirect the user to GitHub's authorization endpoint
window.location.href = `https://github.com/login/oauth/authorize?${params.toString()}`;
};
import { generateCodeChallenge, generateCodeVerifier , generateRandomString} from "../../utils/pkce";

export const LoginWithGithub = async () => {
const codeVerifier = generateCodeVerifier();
const codeChallenge = await generateCodeChallenge(codeVerifier);

// Store the code verifier in session storage (temporary)
sessionStorage.setItem('code_verifier', codeVerifier);

const params = new URLSearchParams({
client_id: 'Ov23li7XMZBxnH3K31ME', // Replace with your GitHub client ID
redirect_uri: 'http://localhost:5173/oauth2/callback/github', // Must match GitHub OAuth app settings
scope: 'user:email', // Requested scopes
response_type: 'code',
state: generateRandomString(16), // Optional but recommended for security
code_challenge: codeChallenge,
code_challenge_method: 'S256',
});

// Redirect the user to GitHub's authorization endpoint
window.location.href = `https://github.com/login/oauth/authorize?${params.toString()}`;
};
9 replies
JCHJava Community | Help. Code. Learn.
Created by Danix on 1/27/2025 in #java-help
Api Key Spring boot
hey 0ne last question ! in future i have to commit the or add or push the code from the backend folder or otherr subfolder where the changes occured or from the parent app folder ?
511 replies
JCHJava Community | Help. Code. Learn.
Created by Danix on 1/27/2025 in #java-help
Api Key Spring boot
ok
511 replies
JCHJava Community | Help. Code. Learn.
Created by Danix on 1/27/2025 in #java-help
Api Key Spring boot
main
511 replies
JCHJava Community | Help. Code. Learn.
Created by Danix on 1/27/2025 in #java-help
Api Key Spring boot
not able to delete the test!
511 replies
JCHJava Community | Help. Code. Learn.
Created by Danix on 1/27/2025 in #java-help
Api Key Spring boot
ok
511 replies
JCHJava Community | Help. Code. Learn.
Created by Danix on 1/27/2025 in #java-help
Api Key Spring boot
whats the reason to make another branch and push our code in it
511 replies
JCHJava Community | Help. Code. Learn.
Created by Danix on 1/27/2025 in #java-help
Api Key Spring boot
git branch -d test

error: branch 'test' not found.
PS C:\Users\jeena\OneDrive\Desktop\ScriptEnhancerApp>
git branch -d test

error: branch 'test' not found.
PS C:\Users\jeena\OneDrive\Desktop\ScriptEnhancerApp>
511 replies
JCHJava Community | Help. Code. Learn.
Created by Danix on 1/27/2025 in #java-help
Api Key Spring boot
we are here with alot of errors !
511 replies
JCHJava Community | Help. Code. Learn.
Created by Danix on 1/27/2025 in #java-help
Api Key Spring boot
hm but got confused a lot that why those errors and should i have to continue pushing code with main ?
511 replies
JCHJava Community | Help. Code. Learn.
Created by Danix on 1/27/2025 in #java-help
Api Key Spring boot
ok done
511 replies
JCHJava Community | Help. Code. Learn.
Created by Danix on 1/27/2025 in #java-help
Api Key Spring boot
PS C:\Users\jeena\OneDrive\Desktop\ScriptEnhancerApp> git checkout HEAD .gitignore
Updated 1 path from 53665c3
PS C:\Users\jeena\OneDrive\Desktop\ScriptEnhancerApp> git status
On branch test
Your branch is up to date with 'origin/test'.

nothing to commit, working tree clean
PS C:\Users\jeena\OneDrive\Desktop\ScriptEnhancerApp>
PS C:\Users\jeena\OneDrive\Desktop\ScriptEnhancerApp> git checkout HEAD .gitignore
Updated 1 path from 53665c3
PS C:\Users\jeena\OneDrive\Desktop\ScriptEnhancerApp> git status
On branch test
Your branch is up to date with 'origin/test'.

nothing to commit, working tree clean
PS C:\Users\jeena\OneDrive\Desktop\ScriptEnhancerApp>
511 replies
JCHJava Community | Help. Code. Learn.
Created by Danix on 1/27/2025 in #java-help
Api Key Spring boot
PS C:\Users\jeena\OneDrive\Desktop\ScriptEnhancerApp> git checkout .gitignore
Updated 0 paths from the index
PS C:\Users\jeena\OneDrive\Desktop\ScriptEnhancerApp> git status
On branch test
Your branch is up to date with 'origin/test'.

Changes to be committed:
(use "git restore --staged <file>..." to unstage)
modified: .gitignore

PS C:\Users\jeena\OneDrive\Desktop\ScriptEnhancerApp>
PS C:\Users\jeena\OneDrive\Desktop\ScriptEnhancerApp> git checkout .gitignore
Updated 0 paths from the index
PS C:\Users\jeena\OneDrive\Desktop\ScriptEnhancerApp> git status
On branch test
Your branch is up to date with 'origin/test'.

Changes to be committed:
(use "git restore --staged <file>..." to unstage)
modified: .gitignore

PS C:\Users\jeena\OneDrive\Desktop\ScriptEnhancerApp>
511 replies
JCHJava Community | Help. Code. Learn.
Created by Danix on 1/27/2025 in #java-help
Api Key Spring boot
PS C:\Users\jeena\OneDrive\Desktop\ScriptEnhancerApp> git status
On branch test
Your branch is up to date with 'origin/test'.

Changes to be committed:
(use "git restore --staged <file>..." to unstage)
modified: .gitignore

PS C:\Users\jeena\OneDrive\Desktop\ScriptEnhancerApp>
PS C:\Users\jeena\OneDrive\Desktop\ScriptEnhancerApp> git status
On branch test
Your branch is up to date with 'origin/test'.

Changes to be committed:
(use "git restore --staged <file>..." to unstage)
modified: .gitignore

PS C:\Users\jeena\OneDrive\Desktop\ScriptEnhancerApp>
511 replies
JCHJava Community | Help. Code. Learn.
Created by Danix on 1/27/2025 in #java-help
Api Key Spring boot
from the test branch ?
511 replies
JCHJava Community | Help. Code. Learn.
Created by Danix on 1/27/2025 in #java-help
Api Key Spring boot
yeh
511 replies