text
stringlengths
9
39.2M
dir
stringlengths
26
295
lang
stringclasses
185 values
created_date
timestamp[us]
updated_date
timestamp[us]
repo_name
stringlengths
1
97
repo_full_name
stringlengths
7
106
star
int64
1k
183k
len_tokens
int64
1
13.8M
```java package com.baeldung.jwt.api; import com.baeldung.jwt.resource.Payment; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RestController; import java.util.ArrayList; import java.util.List; @RestController public class PaymentController { @GetMapping("/payments") public List<Payment> getPayments() { List<Payment> payments = new ArrayList<>(); for(int i = 1; i < 6; i++){ Payment payment = new Payment(); payment.setId(String.valueOf(i)); payment.setAmount(2); payments.add(payment); } return payments; } } ```
/content/code_sandbox/oauth-resource-server/resource-server-jwt/src/main/java/com/baeldung/jwt/api/PaymentController.java
java
2016-03-02T09:04:07
2024-08-06T03:02:12
spring-security-oauth
Baeldung/spring-security-oauth
1,982
127
```java package com.baeldung.jwt.api; import static org.apache.commons.lang3.RandomStringUtils.randomAlphabetic; import static org.apache.commons.lang3.RandomStringUtils.randomNumeric; import java.util.ArrayList; import java.util.List; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.http.HttpStatus; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PathVariable; 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.ResponseStatus; import org.springframework.web.bind.annotation.RestController; import com.baeldung.jwt.resource.Foo; @RestController @RequestMapping(value = "/foos") public class FooController { private static final Logger logger = LoggerFactory.getLogger(FooController.class); @GetMapping(value = "/{id}") public Foo findOne(@PathVariable Long id) { return new Foo(Long.parseLong(randomNumeric(2)), randomAlphabetic(4)); } @GetMapping public List<Foo> findAll() { List<Foo> fooList = new ArrayList<Foo>(); fooList.add(new Foo(Long.parseLong(randomNumeric(2)), randomAlphabetic(4))); fooList.add(new Foo(Long.parseLong(randomNumeric(2)), randomAlphabetic(4))); fooList.add(new Foo(Long.parseLong(randomNumeric(2)), randomAlphabetic(4))); return fooList; } @ResponseStatus(HttpStatus.CREATED) @PostMapping public void create(@RequestBody Foo newFoo) { logger.info("Foo created"); } } ```
/content/code_sandbox/oauth-resource-server/resource-server-jwt/src/main/java/com/baeldung/jwt/api/FooController.java
java
2016-03-02T09:04:07
2024-08-06T03:02:12
spring-security-oauth
Baeldung/spring-security-oauth
1,982
323
```java package com.baeldung.opaque; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.test.context.junit.jupiter.SpringExtension; import com.baeldung.opaque.OpaqueResourceServerApp; @ExtendWith(SpringExtension.class) @SpringBootTest(classes = { OpaqueResourceServerApp.class }) public class ContextIntegrationTest { @Test public void whenLoadApplication_thenSuccess() { } } ```
/content/code_sandbox/oauth-resource-server/resource-server-opaque/src/test/java/com/baeldung/opaque/ContextIntegrationTest.java
java
2016-03-02T09:04:07
2024-08-06T03:02:12
spring-security-oauth
Baeldung/spring-security-oauth
1,982
98
```yaml server: port: 8082 servlet: context-path: /resource-server-opaque ####### resource server configuration properties spring: security: oauth2: resourceserver: opaque: introspection-uri: path_to_url introspection-client-id: barClient introspection-client-secret: barClientSecret ```
/content/code_sandbox/oauth-resource-server/resource-server-opaque/src/main/resources/application.yml
yaml
2016-03-02T09:04:07
2024-08-06T03:02:12
spring-security-oauth
Baeldung/spring-security-oauth
1,982
76
```java package com.baeldung.opaque; import static org.apache.commons.lang3.RandomStringUtils.randomAlphabetic; import static org.apache.commons.lang3.RandomStringUtils.randomNumeric; import static org.assertj.core.api.Assertions.assertThat; import java.util.HashMap; import java.util.List; import java.util.Map; import org.junit.jupiter.api.Test; import org.springframework.http.HttpHeaders; import org.springframework.http.HttpStatus; import com.baeldung.opaque.resource.Bar; import io.restassured.RestAssured; import io.restassured.http.ContentType; import io.restassured.response.Response; /** * This Live Test requires: * - the Authorization Server to be running * - the Resource Server to be running * */ public class OpaqueResourceServerLiveTest { private final String redirectUrl = "path_to_url"; private final String authorizeUrlPattern = "path_to_url" + redirectUrl; private final String tokenUrl = "path_to_url"; private final String resourceUrl = "path_to_url"; @SuppressWarnings("unchecked") @Test public void givenUserWithReadScope_whenGetBarResource_thenSuccess() { String accessToken = obtainAccessToken("read"); // Access resources using access token Response response = RestAssured.given() .header(HttpHeaders.AUTHORIZATION, "Bearer " + accessToken) .get(resourceUrl); System.out.println(response.asString()); assertThat(response.as(List.class)).hasSizeGreaterThan(0); } @Test public void givenUserWithReadScope_whenPostNewBarResource_thenForbidden() { String accessToken = obtainAccessToken("read"); Bar newBar = new Bar(Long.parseLong(randomNumeric(2)), randomAlphabetic(4)); Response response = RestAssured.given() .header(HttpHeaders.AUTHORIZATION, "Bearer " + accessToken) .body(newBar) .post(resourceUrl); assertThat(response.getStatusCode()).isEqualTo(HttpStatus.FORBIDDEN.value()); } @Test public void givenUserWithWriteScope_whenPostNewBarResource_thenCreated() { String accessToken = obtainAccessToken("read write"); Bar newBar = new Bar(Long.parseLong(randomNumeric(2)), randomAlphabetic(4)); Response response = RestAssured.given() .contentType(ContentType.JSON) .header(HttpHeaders.AUTHORIZATION, "Bearer " + accessToken) .body(newBar) .log() .all() .post(resourceUrl); assertThat(response.getStatusCode()).isEqualTo(HttpStatus.CREATED.value()); } private String obtainAccessToken(String scopes) { // obtain authentication url with custom codes Response response = RestAssured.given() .redirects() .follow(false) .get(String.format(authorizeUrlPattern, scopes)); String authSessionId = response.getCookie("AUTH_SESSION_ID"); String kcPostAuthenticationUrl = response.asString() .split("action=\"")[1].split("\"")[0].replace("&amp;", "&"); // obtain authentication code and state response = RestAssured.given() .redirects() .follow(false) .cookie("AUTH_SESSION_ID", authSessionId) .formParams("username", "john@test.com", "password", "123", "credentialId", "") .post(kcPostAuthenticationUrl); assertThat(HttpStatus.FOUND.value()).isEqualTo(response.getStatusCode()); // extract authorization code String location = response.getHeader(HttpHeaders.LOCATION); String code = location.split("code=")[1].split("&")[0]; // get access token Map<String, String> params = new HashMap<String, String>(); params.put("grant_type", "authorization_code"); params.put("code", code); params.put("client_id", "barClient"); params.put("redirect_uri", redirectUrl); params.put("client_secret", "barClientSecret"); response = RestAssured.given() .formParams(params) .post(tokenUrl); return response.jsonPath() .getString("access_token"); } } ```
/content/code_sandbox/oauth-resource-server/resource-server-opaque/src/test/java/com/baeldung/opaque/OpaqueResourceServerLiveTest.java
java
2016-03-02T09:04:07
2024-08-06T03:02:12
spring-security-oauth
Baeldung/spring-security-oauth
1,982
835
```java package com.baeldung.opaque; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; @SpringBootApplication public class OpaqueResourceServerApp { public static void main(String[] args) { SpringApplication.run(OpaqueResourceServerApp.class, args); } } ```
/content/code_sandbox/oauth-resource-server/resource-server-opaque/src/main/java/com/baeldung/opaque/OpaqueResourceServerApp.java
java
2016-03-02T09:04:07
2024-08-06T03:02:12
spring-security-oauth
Baeldung/spring-security-oauth
1,982
57
```java package com.baeldung.opaque.resource; public class Bar { private long id; private String name; public Bar() { super(); } public Bar(final long id, final String name) { super(); this.id = id; this.name = name; } public long getId() { return id; } public void setId(final long id) { this.id = id; } public String getName() { return name; } public void setName(final String name) { this.name = name; } } ```
/content/code_sandbox/oauth-resource-server/resource-server-opaque/src/main/java/com/baeldung/opaque/resource/Bar.java
java
2016-03-02T09:04:07
2024-08-06T03:02:12
spring-security-oauth
Baeldung/spring-security-oauth
1,982
122
```java package com.baeldung.opaque.config; import org.springframework.beans.factory.annotation.Value; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.http.HttpMethod; import org.springframework.security.config.annotation.web.builders.HttpSecurity; import org.springframework.security.web.SecurityFilterChain; @Configuration public class OpaqueSecurityConfig { @Value("${spring.security.oauth2.resourceserver.opaque.introspection-uri}") String introspectionUri; @Value("${spring.security.oauth2.resourceserver.opaque.introspection-client-id}") String clientId; @Value("${spring.security.oauth2.resourceserver.opaque.introspection-client-secret}") String clientSecret; @Bean public SecurityFilterChain filterChain(HttpSecurity http) throws Exception { http.authorizeRequests(authz -> authz.antMatchers(HttpMethod.GET, "/bars/**") .hasAuthority("SCOPE_read") .antMatchers(HttpMethod.POST, "/bars") .hasAuthority("SCOPE_write") .anyRequest() .authenticated()) .oauth2ResourceServer(oauth2 -> oauth2.opaqueToken(token -> token.introspectionUri(this.introspectionUri) .introspectionClientCredentials(this.clientId, this.clientSecret))); return http.build(); } } ```
/content/code_sandbox/oauth-resource-server/resource-server-opaque/src/main/java/com/baeldung/opaque/config/OpaqueSecurityConfig.java
java
2016-03-02T09:04:07
2024-08-06T03:02:12
spring-security-oauth
Baeldung/spring-security-oauth
1,982
262
```java package com.baeldung.opaque.api; import static org.apache.commons.lang3.RandomStringUtils.randomAlphabetic; import static org.apache.commons.lang3.RandomStringUtils.randomNumeric; import java.util.ArrayList; import java.util.List; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.http.HttpStatus; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PathVariable; 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.ResponseStatus; import org.springframework.web.bind.annotation.RestController; import com.baeldung.opaque.resource.Bar; @RestController @RequestMapping(value = "/bars") public class BarController { private static final Logger logger = LoggerFactory.getLogger(BarController.class); @GetMapping(value = "/{id}") public Bar findOne(@PathVariable Long id) { return new Bar(Long.parseLong(randomNumeric(2)), randomAlphabetic(4)); } @GetMapping public List<Bar> findAll() { List<Bar> barList = new ArrayList<Bar>(); barList.add(new Bar(Long.parseLong(randomNumeric(2)), randomAlphabetic(4))); barList.add(new Bar(Long.parseLong(randomNumeric(2)), randomAlphabetic(4))); barList.add(new Bar(Long.parseLong(randomNumeric(2)), randomAlphabetic(4))); return barList; } @ResponseStatus(HttpStatus.CREATED) @PostMapping public void create(@RequestBody Bar newBar) { logger.info("Bar created"); } } ```
/content/code_sandbox/oauth-resource-server/resource-server-opaque/src/main/java/com/baeldung/opaque/api/BarController.java
java
2016-03-02T09:04:07
2024-08-06T03:02:12
spring-security-oauth
Baeldung/spring-security-oauth
1,982
322
```java package com.baeldung.clientjsonlyreact; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.test.context.junit4.SpringRunner; @RunWith(SpringRunner.class) @SpringBootTest public class ApplicationContextIntegrationTest { @Test public void contextLoads() { } } ```
/content/code_sandbox/clients-SPA-legacy/clients-js-only-react-legacy/src/test/java/com/baeldung/clientjsonlyreact/ApplicationContextIntegrationTest.java
java
2016-03-02T09:04:07
2024-08-06T03:02:12
spring-security-oauth
Baeldung/spring-security-oauth
1,982
67
```css *, *:before, *:after { box-sizing: border-box; } body { margin: 0; font-family: 'Raleway', sans-serif; } .landing-page-container { display: flex; flex-direction: column; } .header-container { flex: 4 1 0; background-color: #323232; color: white; text-align: center; padding: 3em; } .header-container .description { font-size: 1.2em; } .examples-container { flex: 1 1 0; display: flex; flex-direction: row; justify-content: space-evenly; } .examples-container a { flex: 1 1 0; text-decoration: none; display: flex; } .example { background-color: #63b175; border: solid #323232; margin: 30px; padding: 1.5em; text-align: center; } .example:hover { box-shadow: 0 0 40px black; } .example .title { color: white; } .example .description { color: #525e74; font-size: 1.3em; } ```
/content/code_sandbox/clients-SPA-legacy/clients-js-only-react-legacy/src/main/resources/static/landing-page.css
css
2016-03-02T09:04:07
2024-08-06T03:02:12
spring-security-oauth
Baeldung/spring-security-oauth
1,982
262
```html <!DOCTYPE html> <html> <head> <title>Landing Page - Baeldung's JS-only SPA Oauth Client</title> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width"> <!-- Styles --> <link rel="stylesheet" href="/landing-page.css"> <link href="path_to_url" rel="stylesheet"> </head> <body> <div id="landing-page-container"> <div class="header-container"> <div class="title"> <h1> Welcome to the JS-only SPA OAuth Clients using Auth Code with PKCE! </h1> </div> <div class="description"> We present here three examples of Single Page Applications: </div> </div> <div class="examples-container"> <a id="simple" href="/pkce-simple/index.html"> <div class="example"> <div class="title"> <h2>The Article's Example SPA</h2> </div> <div class="description"> <p>If we're looking for the application that we built together following the article's steps, this is our option.</p> <p>It has nothing but the most fundamental elements to access secured resources using the OAuth2 Auth Code with PKCE Flow</p> </div> </div> </a> <a id="step-by-step" href="/pkce-stepbystep/index.html"> <div class="example"> <div class="title"> <h2>The Step-By-Step SPA</h2> </div> <div class="description"> <p>We should pick this App if we want to see how the Auth Code with PKCE Flow is carried out in an interactive way.</p> <p> We'll see in the UI and in the browser console what happens behind the scenes when we request an access token. </p> </div> </div> </a> <a id="real-case" href="/pkce-realcase/index.html"> <div class="example"> <div class="title"> <h2>The Real-Case SPA</h2> </div> <div class="description"> <p> In this Application we simulate how a real application would work, making use of our custom Resource Server with protected endpoints. </p> <p> Remember to read The Readme file for more details.</p> </div> </div> </a> </div> </div> </body> </html> ```
/content/code_sandbox/clients-SPA-legacy/clients-js-only-react-legacy/src/main/resources/static/index.html
html
2016-03-02T09:04:07
2024-08-06T03:02:12
spring-security-oauth
Baeldung/spring-security-oauth
1,982
575
```javascript function generate_code_verifier() { return random_string(48); } ```
/content/code_sandbox/clients-SPA-legacy/clients-js-only-react-legacy/src/main/resources/static/common/js/code_verifier_functions.js
javascript
2016-03-02T09:04:07
2024-08-06T03:02:12
spring-security-oauth
Baeldung/spring-security-oauth
1,982
16
```javascript function base64_urlencode(str) { return btoa(str) .replace(/\+/g, '-') .replace(/\//g, '_') .replace(/=/g, ''); } function generate_state() { return random_string(48); } function random_string(len) { var arr = new Uint8Array(len); window.crypto.getRandomValues(arr); var str = base64_urlencode(dec2bin(arr)); return str.substring(0, len); } function dec2hex(dec) { return ('0' + dec.toString(16)).substr(-2) } function dec2bin(arr) { return hex2bin(Array.from(arr, dec2hex).join('')); } function getParameterByName(name, url) { if (!url) url = window.location.href; name = name.replace(/[\[\]]/g, '\\$&'); var regex = new RegExp('[?&]' + name + '(=([^&#]*)|&|#|$)'), results = regex.exec(url); if (!results) return null; if (!results[2]) return ''; return decodeURIComponent(results[2].replace(/\+/g, ' ')); } ```
/content/code_sandbox/clients-SPA-legacy/clients-js-only-react-legacy/src/main/resources/static/common/js/common_functions.js
javascript
2016-03-02T09:04:07
2024-08-06T03:02:12
spring-security-oauth
Baeldung/spring-security-oauth
1,982
247
```javascript const AUTH0_APP_DOMAIN = 'path_to_url const PROVIDER_CONFIGS = { AUTH0: { AUTH_URL: AUTH0_APP_DOMAIN + "/authorize", CLIENT_ID: "R7L3XpkJrwcGEkuxrUdSpGAA9NgX9ouQ", CONFIGURED_REDIRECT_URIS:{ STEP_BY_STEP: "path_to_url", REAL_CASE: "path_to_url", SIMPLE: "path_to_url" }, TOKEN_URI: AUTH0_APP_DOMAIN + "/oauth/token", SCOPES: 'openid profile email', AUDIENCE: "pkceclient.baeldung.com", PROFILE_URL: AUTH0_APP_DOMAIN + "/userinfo", PROFILE_FIELDS: { NAME: "nickname", EMAIL: "email", PICTURE: "picture" }, // Renew Token Period for in seconds: RENEW_TOKEN_PERIOD: 60 } } window.PROVIDER_CONFIGS = PROVIDER_CONFIGS; ```
/content/code_sandbox/clients-SPA-legacy/clients-js-only-react-legacy/src/main/resources/static/common/js/provider_configs.js
javascript
2016-03-02T09:04:07
2024-08-06T03:02:12
spring-security-oauth
Baeldung/spring-security-oauth
1,982
211
```javascript // Spiner indicating something is being processed const Spinner = ({ spinnerText }) => ( <div className="spinner-container"> <p className="spinner-text">{spinnerText || 'Waiting...'}</p> <div className="spinner-icon"></div> </div> ) window.Spinner = Spinner; ```
/content/code_sandbox/clients-SPA-legacy/clients-js-only-react-legacy/src/main/resources/static/common/js/components/spinner.js
javascript
2016-03-02T09:04:07
2024-08-06T03:02:12
spring-security-oauth
Baeldung/spring-security-oauth
1,982
65
```html <!DOCTYPE html> <html> <head> <script src="path_to_url"></script> </head> <body> <script type="text/javascript" src="/common/js/provider_configs.js"></script> <script type="text/javascript"> const urlParams = new URLSearchParams(window.location.search); const authCode = urlParams.get('code'); const state = urlParams.get('state'); const stateMessage = { type: 'state', state } window.opener.postMessage(stateMessage, "*"); const onMainWindowMessageFn = (e) => { if (!e.data.codeVerifier) { return }; const { TOKEN_URI, CLIENT_ID, CONFIGURED_REDIRECT_URIS: { SIMPLE: redirectUri }, AUDIENCE } = PROVIDER_CONFIGS.AUTH0; const tokenRequestBody = { grant_type: 'authorization_code', redirect_uri: redirectUri, code: authCode, code_verifier: e.data.codeVerifier, client_id: CLIENT_ID, audience: AUDIENCE } var headers = { 'Content-type': 'application/x-www-form-urlencoded; charset=UTF-8' } axios.post(TOKEN_URI, new URLSearchParams(tokenRequestBody), { headers }) .then((response) => { const accessToken = response.data.access_token; const tokenMessage = { type: 'accessToken', accessToken } window.opener.postMessage(tokenMessage, "*"); window.close(); } ); } window.addEventListener('message', onMainWindowMessageFn, false); </script> </body> </html> ```
/content/code_sandbox/clients-SPA-legacy/clients-js-only-react-legacy/src/main/resources/static/pkce-simple/callback.html
html
2016-03-02T09:04:07
2024-08-06T03:02:12
spring-security-oauth
Baeldung/spring-security-oauth
1,982
345
```javascript function generate_code_challenge(verifier) { return base64_urlencode(sha256bin(verifier)); } generateCodeChallenge = async (codeVerifier) => { const strBuffer = new TextEncoder('utf-8').encode(codeVerifier); const hashBuffer = await window.crypto.subtle.digest('SHA-256', strBuffer); return Array.from(new Uint8Array(hashBuffer)); } function sha256bin(ascii) { return hex2bin(sha256(ascii)); } function hex2bin(s) { var ret = [] var i = 0 var l s += '' for (l = s.length; i < l; i += 2) { var c = parseInt(s.substr(i, 1), 16) var k = parseInt(s.substr(i + 1, 1), 16) if (isNaN(c) || isNaN(k)) return false ret.push((c << 4) | k) } return String.fromCharCode.apply(String, ret) } var sha256 = function sha256(ascii) { function rightRotate(value, amount) { return (value>>>amount) | (value<<(32 - amount)); }; var mathPow = Math.pow; var maxWord = mathPow(2, 32); var lengthProperty = 'length'; var i, j; // Used as a counter across the whole file var result = ''; var words = []; var asciiBitLength = ascii[lengthProperty]*8; //* caching results is optional - remove/add slash from front of this line to toggle // Initial hash value: first 32 bits of the fractional parts of the square roots of the first 8 primes // (we actually calculate the first 64, but extra values are just ignored) var hash = sha256.h = sha256.h || []; // Round constants: first 32 bits of the fractional parts of the cube roots of the first 64 primes var k = sha256.k = sha256.k || []; var primeCounter = k[lengthProperty]; /*/ var hash = [], k = []; var primeCounter = 0; //*/ var isComposite = {}; for (var candidate = 2; primeCounter < 64; candidate++) { if (!isComposite[candidate]) { for (i = 0; i < 313; i += candidate) { isComposite[i] = candidate; } hash[primeCounter] = (mathPow(candidate, .5)*maxWord)|0; k[primeCounter++] = (mathPow(candidate, 1/3)*maxWord)|0; } } ascii += '\x80'; // Append '1' bit (plus zero padding) while (ascii[lengthProperty]%64 - 56) ascii += '\x00'; // More zero padding for (i = 0; i < ascii[lengthProperty]; i++) { j = ascii.charCodeAt(i); if (j>>8) return; // ASCII check: only accept characters in range 0-255 words[i>>2] |= j << ((3 - i)%4)*8; } words[words[lengthProperty]] = ((asciiBitLength/maxWord)|0); words[words[lengthProperty]] = (asciiBitLength) // process each chunk for (j = 0; j < words[lengthProperty];) { var w = words.slice(j, j += 16); // The message is expanded into 64 words as part of the iteration var oldHash = hash; // This is now the "working hash", often labelled as variables a...g // (we have to truncate as well, otherwise extra entries at the end accumulate hash = hash.slice(0, 8); for (i = 0; i < 64; i++) { var i2 = i + j; // Expand the message into 64 words // Used below if var w15 = w[i - 15], w2 = w[i - 2]; // Iterate var a = hash[0], e = hash[4]; var temp1 = hash[7] + (rightRotate(e, 6) ^ rightRotate(e, 11) ^ rightRotate(e, 25)) // S1 + ((e&hash[5])^((~e)&hash[6])) // ch + k[i] // Expand the message schedule if needed + (w[i] = (i < 16) ? w[i] : ( w[i - 16] + (rightRotate(w15, 7) ^ rightRotate(w15, 18) ^ (w15>>>3)) // s0 + w[i - 7] + (rightRotate(w2, 17) ^ rightRotate(w2, 19) ^ (w2>>>10)) // s1 )|0 ); // This is only used once, so *could* be moved below, but it only saves 4 bytes and makes things unreadble var temp2 = (rightRotate(a, 2) ^ rightRotate(a, 13) ^ rightRotate(a, 22)) // S0 + ((a&hash[1])^(a&hash[2])^(hash[1]&hash[2])); // maj hash = [(temp1 + temp2)|0].concat(hash); // We don't bother trimming off the extra ones, they're harmless as long as we're truncating when we do the slice() hash[4] = (hash[4] + temp1)|0; } for (i = 0; i < 8; i++) { hash[i] = (hash[i] + oldHash[i])|0; } } for (i = 0; i < 8; i++) { for (j = 3; j + 1; j--) { var b = (hash[i]>>(j*8))&255; result += ((b < 16) ? 0 : '') + b.toString(16); } } return result; }; ```
/content/code_sandbox/clients-SPA-legacy/clients-js-only-react-legacy/src/main/resources/static/common/js/code_challenge_functions.js
javascript
2016-03-02T09:04:07
2024-08-06T03:02:12
spring-security-oauth
Baeldung/spring-security-oauth
1,982
1,341
```html <!DOCTYPE html> <html> <head> <script src="path_to_url" crossorigin></script> <script src="path_to_url" crossorigin></script> <script src="path_to_url"></script> <script src="path_to_url"></script> </head> <body> <div id="root"></div> <!-- Other components and Js files goes here --> <script type="text/javascript" src="/common/js/provider_configs.js"></script> <script type="text/babel" src="/pkce-simple/js/components/app.js"></script> <script type="text/babel"> const rootElement = document.getElementById('root'); ReactDOM.render(<App/>, rootElement); </script> </body> </html> ```
/content/code_sandbox/clients-SPA-legacy/clients-js-only-react-legacy/src/main/resources/static/pkce-simple/index.html
html
2016-03-02T09:04:07
2024-08-06T03:02:12
spring-security-oauth
Baeldung/spring-security-oauth
1,982
167
```html <!DOCTYPE html> <html> <head> <!-- Styles --> <link rel="stylesheet" href="/pkce-realcase/css/bael-oauth-pkce-styles.css"> <link href="path_to_url" rel="stylesheet"> <!-- Import the React, React-Dom and Babel libraries --> <!-- Note: Here we are using React's unminified-development version --> <script src="path_to_url" crossorigin></script> <script src="path_to_url" crossorigin></script> <script src="path_to_url"></script> <!-- Axios to make requests easily --> <script src="path_to_url"></script> </head> <body> <div id="root"></div> <script type="text/javascript" src="/common/js/provider_configs.js"></script> <script type="text/javascript" src="/common/js/common_functions.js"></script> <script type="text/babel" src="/pkce-realcase/js/components/popup/popup_window.js"></script> <script type="text/babel"> const parentWindow = window.opener || window.parent; const typeOfWindow = (window.opener && 'popup') || (window.parent && 'iframe'); const urlParams = new URLSearchParams(window.location.search); const popupProps = { authCode: urlParams.get('code'), state: urlParams.get('state'), error: urlParams.get('error'), errorDescription: urlParams.get('error_description'), parentWindow, typeOfWindow } // popup rendering: const rootElement = document.getElementById('root'); ReactDOM.render(<PopupWindow {...popupProps} />, rootElement); </script> </body> </html> ```
/content/code_sandbox/clients-SPA-legacy/clients-js-only-react-legacy/src/main/resources/static/pkce-realcase/popup_code_handler.html
html
2016-03-02T09:04:07
2024-08-06T03:02:12
spring-security-oauth
Baeldung/spring-security-oauth
1,982
369
```javascript class App extends React.Component { state = { codeVerifier: '', codeChallenge: '', state: '', accessToken: '', userName: '' }; createCodes = () => { const state = this.generateRandomString(32); const codeVerifier = this.generateRandomString(32); this.generateCodeChallenge(codeVerifier).then((codeChallenge) => { this.setState({ state, codeVerifier, codeChallenge }) }) } generateRandomString = (length) => { var randomByteArray = new Uint8Array(length); window.crypto.getRandomValues(randomByteArray); var randomString = btoa(String.fromCharCode.apply(null, randomByteArray)); var code = randomString.replace(/\+/g, '-') .replace(/\//g, '_') .replace(/=/g, ''); return code; } generateCodeChallenge = async (codeVerifier) => { const strBuffer = new TextEncoder('utf-8').encode(codeVerifier); const hashBuffer = await window.crypto.subtle.digest('SHA-256', strBuffer); const byteArray = Array.from(new Uint8Array(hashBuffer)); var base64String = btoa(String.fromCharCode.apply(null, byteArray)); var code = base64String.replace(/\+/g, '-') .replace(/\//g, '_') .replace(/=/g, ''); return code; } authorizeApplication = () => { const { AUTH_URL, CLIENT_ID, CONFIGURED_REDIRECT_URIS: { SIMPLE: redirectUri }, SCOPES, AUDIENCE } = PROVIDER_CONFIGS.AUTH0; const authorizationUrl = AUTH_URL + '?client_id=' + CLIENT_ID + "&response_type=code" + '&scope=' + SCOPES + '&redirect_uri=' + redirectUri + '&state=' + this.state.state + '&code_challenge_method=S256' + '&code_challenge=' + this.state.codeChallenge + (AUDIENCE ? ('&audience=' + AUDIENCE) : ''); var popup = window.open(authorizationUrl, 'external_auth_page', 'width=800,height=600'); window.addEventListener('message', this.onPopupResponseFn, false); this.setState({ popup }) } onPopupResponseFn = (e) => { const eventType = e.data && e.data.type; switch (eventType) { case 'state': if (e.data.state !== this.state.state) { window.alert("Retrieved state [" + e.data.state + "] didn't match stored one! Try again"); return; } this.state.popup.postMessage({ codeVerifier: this.state.codeVerifier }, "*"); break; case 'accessToken': const accessToken = e.data.accessToken; this.setState({ accessToken, popup: null, }); break; } } requestResource = () => { const profileInfoUrl = PROVIDER_CONFIGS.AUTH0.PROFILE_URL; const headers = { headers: { Authorization: 'Bearer ' + this.state.accessToken } }; var self = this; axios.get(profileInfoUrl, headers).then(function (response) { self.setState({ userName: response.data.nickname }) }); } render() { return ( <div> <button onClick={this.createCodes}>Create codes</button> {this.state.codeChallenge && <button onClick={this.authorizeApplication}>Authenticate</button>} {this.state.accessToken && <button onClick={this.requestResource}>Request secured resource</button>} {this.state.userName && <div>Welcome {this.state.userName}</div>} </div> ) } } window.App = App; ```
/content/code_sandbox/clients-SPA-legacy/clients-js-only-react-legacy/src/main/resources/static/pkce-simple/js/components/app.js
javascript
2016-03-02T09:04:07
2024-08-06T03:02:12
spring-security-oauth
Baeldung/spring-security-oauth
1,982
789
```html <!DOCTYPE html> <html> <head> <title>Real Case - Baeldung's JS-only SPA Oauth Client</title> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width"> <!-- Styles --> <link rel="stylesheet" href="/pkce-realcase/css/bael-oauth-pkce-styles.css"> <link href="path_to_url" rel="stylesheet"> <!-- Import the React, React-Dom and Babel libraries --> <!-- Note: Here we are using React's unminified-development version --> <script src="path_to_url" crossorigin></script> <script src="path_to_url" crossorigin></script> <script src="path_to_url"></script> <!-- Axios to make requests easily --> <script src="path_to_url"></script> <!-- Icons --> <link rel="stylesheet" href="path_to_url" integrity=your_sha256_hashLbHG9Sr" crossorigin="anonymous"> </head> <body> <div id="root"></div> <script type="text/javascript" src="/pkce-realcase/js/resource_configs.js"></script> <script type="text/javascript" src="/common/js/provider_configs.js"></script> <script type="text/javascript" src="/common/js/common_functions.js"></script> <script type="text/javascript" src="/common/js/code_verifier_functions.js"></script> <script type="text/javascript" src="/common/js/code_challenge_functions.js"></script> <script type="text/babel" src="/common/js/components/spinner.js"></script> <script type="text/babel" src="/pkce-realcase/js/components/navbar/navbar.js"></script> <script type="text/babel" src="/pkce-realcase/js/components/pages/listing.js"></script> <script type="text/babel" src="/pkce-realcase/js/components/pages/listing_item.js"></script> <script type="text/babel" src="/pkce-realcase/js/components/pages/profile.js"></script> <script type="text/babel" src="/pkce-realcase/js/components/app.js"></script> <script type="text/babel"> // main rendering: const rootElement = document.getElementById('root'); ReactDOM.render(<App/>, rootElement); </script> </body> </html> ```
/content/code_sandbox/clients-SPA-legacy/clients-js-only-react-legacy/src/main/resources/static/pkce-realcase/index.html
html
2016-03-02T09:04:07
2024-08-06T03:02:12
spring-security-oauth
Baeldung/spring-security-oauth
1,982
509
```javascript const RESOURCE_CONFIGS = { SAVE_COLOR_URL: 'path_to_url DELETE_COLOR_URL: 'path_to_url{id}', GET_COLORS_URL: 'path_to_url } window.RESOURCE_CONFIGS = RESOURCE_CONFIGS; ```
/content/code_sandbox/clients-SPA-legacy/clients-js-only-react-legacy/src/main/resources/static/pkce-realcase/js/resource_configs.js
javascript
2016-03-02T09:04:07
2024-08-06T03:02:12
spring-security-oauth
Baeldung/spring-security-oauth
1,982
49
```css *, *:before, *:after { box-sizing: border-box; } body { margin: 0; font-family: 'Raleway', sans-serif; } nav { display: flex; flex-direction: row; height: 6em; position: fixed; top: 0; background-color: #323232; color: white; width: 100%; } nav .menu { flex: 4 1 0; display: flex; align-items: center; } nav .menu ul { height: 100%; align-items: center; display: flex; margin: 0; } nav .menu ul il { font-size: 1.7em; margin: 0 20px; text-transform: uppercase; cursor: pointer; height: 100%; align-items: center; display: flex; } nav .login-container { flex: 1 1 0; display: flex; border-width: 2px; border-style: solid; -webkit-border-image: -webkit-linear-gradient(#323232, #a8a8a8, #323232) 0.1 100%; -moz-border-image: -moz-linear-gradient(#323232, #a8a8a8, #323232) 0.1 100%; -o-border-image: -o-linear-gradient(#323232, #a8a8a8, #323232) 0.1 100%; border-image: linear-gradient(to bottom, #323232, #a8a8a8, #323232) 1 100%; } nav .login-container>div { display: flex; position: relative; } nav .login-container div { width: 100% } nav .user-info { display: flex; margin-left: 10px; padding: 10px; cursor: pointer; overflow: hidden; } nav .user-info .picture { flex: 1 1 0; margin-right: 10px; } nav .user-info .picture img { max-height: 100%; max-width: 100%; display: block; border-radius: 10px; } nav .user-info .greeting { flex: 2 1 0; text-align: center; margin: auto; text-align: center; } nav .logout { width: 100%; height: 50%; transform: translateY(5em); position: absolute } nav .logout button { background: rgba(50, 50, 50, 0.8); width: 100%; height: 100%; border: none; color: white; cursor: pointer; } nav .login button { background: none; border: none; font-size: 1.7em; text-transform: uppercase; color: white; width: 100%; } .content-container { margin: 8em auto 0; width: 80%; height: 100%; border-radius: 5px; } .listing-container { background-color: #63b175; box-shadow: 0px 0px 20px black; } .listing-container>div { display: flex; flex-direction: row; } .listing { flex: 3 1 0; margin: 20px 10px; } .listing .listing-item { height: 2em; border: solid #323232; border-width: 1.5px 2px; display: flex; justify-content: space-between; padding: 0 25px; background-color: lightgray; } .listing .listing-item div { margin: auto 0; } .listing .listing-item:first-child { border-radius: 10px 10px 0 0; border-width: 2px 2px 1px 2px; } .listing .listing-item:last-child { border-radius: 0 0 10px 10px; border-width: 1px 2px 2px 2px; } .listing .listing-item .color-demo { width: 1.5em; height: 1.5em; display: inline-block; border-radius: 5px; border: solid #323232; } .listing .listing-item .color-name { text-transform: uppercase; font-size: 1.2em; color: #323232; } .create-color { flex: 1 1 0; margin: 20px 10px; display: flex; flex-direction: column; padding-top: 1.5em; } .create-color input { margin: 0 0 5px 0; height: 2.2em; text-align: center; border-radius: 10px; border-style: none; } .create-color button { margin: 5px 15%; height: 2.5em; border: none; background: #323232; color: white; border-radius: 15px; } .dimmer { position: absolute; width: 100%; height: 200%; z-index: 100; background: rgba(0, 0, 0, 0.5); top: 0; } /* Spinner */ .spinner-container { padding-bottom: 20px; text-align: center; } .spinner-container .spinner-text { font-size: 1.2em; } .spinner-container .spinner-icon { border: 16px solid green; border-top: 16px solid lightgray; border-radius: 50%; width: 120px; height: 120px; animation: spin 2s linear infinite; margin: auto; } button { cursor: pointer; } @keyframes spin { 0% { transform: rotate(0deg); } 100% { transform: rotate(360deg); } } /* Profile */ .profile { text-align: center } .profile .user-info { border: solid #63b175 5px; border-radius: 20px; position: relative; } .profile .user-info .name { font-size: 2em; margin: 0.5em; font-weight: bold; border-bottom: solid #63b175; padding-bottom: 3em; margin: 0; padding-top: 10px; } .profile .user-info .picture { width: 100%; position: absolute; } .profile .user-info .picture img { border: solid #63b175 10px; height: 12em; border-radius: 100px; transform: translateY(-6em); } .profile .user-info .email { font-size: 2em; font-weight: bold; border-top: solid #63b175; padding-top: 3em; margin: 0; padding-bottom: 10px; } .scopes-container { margin: 3em; border: solid 3px #323232; border-radius: 15px; padding: 1em; } .scopes-container div { margin: 0.5em; } .scope-option { margin: 1em; } .refresh-container button { margin: 5px 15%; height: 2.5em; border: none; background: #323232; color: white; border-radius: 15px; padding: 0 2em; } ```
/content/code_sandbox/clients-SPA-legacy/clients-js-only-react-legacy/src/main/resources/static/pkce-realcase/css/bael-oauth-pkce-styles.css
css
2016-03-02T09:04:07
2024-08-06T03:02:12
spring-security-oauth
Baeldung/spring-security-oauth
1,982
1,681
```javascript // Profile const Profile = ({ user, scopes, scopeChangeFn, renewTokenFn }) => { const { name, lastName, email, picture } = user; return ( <div className="profile"> <h2>Profile</h2> <div className="user-info"> <div className="name"> {name ? name + ' ' : ''} {lastName || ''} </div> <div className="picture"> <img src={picture || '/common/images/default-profile.png'} /> </div> <div className="email"> {email || ''} </div> </div> <div className="scopes-container" > <div> Here we can modify the scopes that the application will ask when requesting the Access Token</div> <div className="scope-options-container"> <div className="scope-option"> <input key='create' type='checkbox' checked={scopes.create} onChange={scopeChangeFn.bind(this, 'create')} /> Create Color Scope (colors:create) </div> <div className="scope-option"> <input key='delete' id='deleteCb' type='checkbox' checked={scopes.delete} onChange={scopeChangeFn.bind(this, 'delete')} /> Delete Color Scope (colors:delete) </div> </div> <div className="refresh-container"> <button onClick={renewTokenFn}>Refresh Token and Scopes</button> </div> </div> </div> ) } window.Profile = Profile; ```
/content/code_sandbox/clients-SPA-legacy/clients-js-only-react-legacy/src/main/resources/static/pkce-realcase/js/components/pages/profile.js
javascript
2016-03-02T09:04:07
2024-08-06T03:02:12
spring-security-oauth
Baeldung/spring-security-oauth
1,982
329
```javascript // App component: class App extends React.Component { state = { user: null, auth: null, authRequest: { codeVerifier: '', codeChallenge: '', state: '' }, currentView: 'listing', popup: null, iframe: React.createRef(), iframeComponent: null, scopes: { create: true, delete: true }, }; componentWillUnmount() { window.removeEventListener("message", this.onChildResponseFn); } _generateAuthUrl = (isSilentAuth) => { const { AUTH_URL, CLIENT_ID, CONFIGURED_REDIRECT_URIS: { REAL_CASE: redirectUri }, SCOPES, AUDIENCE } = PROVIDER_CONFIGS.AUTH0; const state = generate_state(); const codeVerifier = generate_code_verifier(); const codeChallenge = generate_code_challenge(codeVerifier); const customScopesString = (this.state.scopes.create ? ' colors:create' : '') + (this.state.scopes.delete ? ' colors:delete' : ''); const authorizationUrl = AUTH_URL + '?client_id=' + CLIENT_ID + "&response_type=code" + '&scope=' + SCOPES + customScopesString + '&redirect_uri=' + redirectUri + '&state=' + state + '&code_challenge_method=S256' + '&code_challenge=' + codeChallenge + (AUDIENCE ? ('&audience=' + AUDIENCE) : '') + (isSilentAuth ? '&prompt=none' : ''); return { state, codeVerifier, codeChallenge, authorizationUrl }; } onLoginFn = () => { const { state, codeVerifier, codeChallenge, authorizationUrl } = this._generateAuthUrl(); window.addEventListener('message', this.onChildResponseFn, false); var popup = window.open(authorizationUrl, 'external_login_page', 'width=800,height=600,left=200,top=100'); this.setState({ popup, authRequest: { codeVerifier, codeChallenge, state } }); } onChildResponseFn = (e) => { const eventType = e.data && e.data.type; switch (eventType) { case 'authCode': if (e.data.state !== this.state.authRequest.state) { window.alert("Retrieved state [" + e.data.state + "] didn't match stored one! Try again"); return; } const authCodeUpdate = { codeVerifier: this.state.authRequest.codeVerifier } var childWindow = this.state[e.data.source].current ? this.state[e.data.source].current.contentWindow : this.state[e.data.source]; childWindow.postMessage(authCodeUpdate, "*"); break; case 'accessToken': const auth = e.data.auth; this._setTimeoutForRenewToken(auth); this.fetchUserInfo(auth); var expiryDate = new Date(); expiryDate.setSeconds(expiryDate.getSeconds() + auth.expires_in); console.log("Setting new token", "Access Token " + auth.access_token, "Expires: " + expiryDate); this.setState({ auth, popup: null, iframeComponent: null }); break; } } _setTimeoutForRenewToken = (auth) => { const defaultRenewTokenPeriod = PROVIDER_CONFIGS.AUTH0.RENEW_TOKEN_PERIOD; const renewTokenIn = auth.expires_in < defaultRenewTokenPeriod ? auth.expires_in : defaultRenewTokenPeriod; this.tokenRenewTimeout = setTimeout(this.renewTokenFn, renewTokenIn * 1000); } renewTokenFn = () => { const { state, codeVerifier, codeChallenge, authorizationUrl } = this._generateAuthUrl(true); const iframeComponent = <iframe style={{ display: 'none' }} src={authorizationUrl} ref={this.state.iframe} />; this.setState({ iframeComponent, authRequest: { codeVerifier, codeChallenge, state } }); } extractProfileField = (data, fieldString) => { if (!fieldString) return; var fields = fieldString.split('.'); var dataValue = { ...data }; for (var field of fields) { dataValue = dataValue[field]; } return dataValue; } fetchUserInfo(auth) { const { PROFILE_URL, PROFILE_FIELDS } = PROVIDER_CONFIGS.AUTH0; const headers = auth ? { headers: { 'Authorization': 'Bearer ' + auth.access_token } } : {}; var self = this; axios.get(PROFILE_URL, headers).then(function (response) { const name = self.extractProfileField(response.data, PROFILE_FIELDS.NAME); const lastName = self.extractProfileField(response.data, PROFILE_FIELDS.LAST_NAME); const email = self.extractProfileField(response.data, PROFILE_FIELDS.EMAIL); const picture = self.extractProfileField(response.data, PROFILE_FIELDS.PICTURE); const user = { name, lastName, email, picture }; self.setState({ user }) }) .catch(function (error) { const errorMessage = "Error retrieving user information" + error; window.alert(errorMessage); }) } onLogoutFn = () => { clearTimeout(this.tokenRenewTimeout); window.removeEventListener("message", this.onChildResponseFn); this.setState({ user: null, auth: null, authRequest: { codeVerifier: '', codeChallenge: '', state: '' }, currentView: 'listing', popup: null, iframeComponent: null }) } changeView = (view) => { this.setState({ currentView: view }) } scopeChangeFn = (field, e) => { const scopes = { ...this.state.scopes }; scopes[field] = !scopes[field]; this.setState({ scopes }); } render() { var CurrentView = null; switch (this.state.currentView) { case 'listing': CurrentView = Listing break; case 'profile': CurrentView = Profile; break; } const { user, auth, popup, iframeComponent } = { ...this.state }; return ( <div> {popup && <div className="dimmer"></div>} <div className="baeldung-container"> <Navbar user={user} auth={auth} onLoginFn={this.onLoginFn} onLogoutFn={this.onLogoutFn} changeView={this.changeView} /> <div className="content-container"> <CurrentView {...this.state} scopeChangeFn={this.scopeChangeFn} renewTokenFn={this.renewTokenFn} /> </div> </div> {iframeComponent || ''} </div> ) } } window.App = App; ```
/content/code_sandbox/clients-SPA-legacy/clients-js-only-react-legacy/src/main/resources/static/pkce-realcase/js/components/app.js
javascript
2016-03-02T09:04:07
2024-08-06T03:02:12
spring-security-oauth
Baeldung/spring-security-oauth
1,982
1,477
```javascript // Listing Item const ListingItem = ({ id, value, onDeleteFn }) => ( <div key={id} className="listing-item"> <div style={{backgroundColor:value}} className="color-demo"></div> <div className="color-name">{value}</div> <div onClick={onDeleteFn.bind(this,id)} className="fas fa-trash-alt"></div> </div> ) window.ListingItem = ListingItem; ```
/content/code_sandbox/clients-SPA-legacy/clients-js-only-react-legacy/src/main/resources/static/pkce-realcase/js/components/pages/listing_item.js
javascript
2016-03-02T09:04:07
2024-08-06T03:02:12
spring-security-oauth
Baeldung/spring-security-oauth
1,982
91
```javascript // PopupWindow component: class PopupWindow extends React.Component { componentDidMount() { if (!this.props.error) { window.addEventListener('message', this.onMainWindowMessageFn, false); const authCodeStatus = { state: this.props.state, type: 'authCode', source: this.props.typeOfWindow } this.props.parentWindow ? this.props.parentWindow.postMessage(authCodeStatus, "*") : window.alert("This is not a popup or iframe window!"); } else { window.alert("Error: " + this.props.error); } } onMainWindowMessageFn = (e) => { const { codeVerifier } = e.data; if (!codeVerifier) { return }; const { TOKEN_URI, CLIENT_ID, CONFIGURED_REDIRECT_URIS: { REAL_CASE: redirectUri }, AUDIENCE } = PROVIDER_CONFIGS.AUTH0; const tokenRequestUrl = TOKEN_URI; const tokenRequestBody = { grant_type: 'authorization_code', redirect_uri: redirectUri, code: this.props.authCode, code_verifier: codeVerifier, client_id: CLIENT_ID } if (AUDIENCE) tokenRequestBody.audience = AUDIENCE; var headers = { 'Content-type': 'application/x-www-form-urlencoded; charset=UTF-8' } var self = this; axios.post(tokenRequestUrl, new URLSearchParams(tokenRequestBody), { headers }) .then(function (response) { const auth = response.data; const tokenStatus = { type: 'accessToken', auth, source: self.props.typeOfWindow } self.props.parentWindow ? self.props.parentWindow.postMessage(tokenStatus, "*") : window.alert("This is not a popup or iframe window!"); window.close(); }) .catch(function (error) { const errorMessage = "Error retrieving token: Provider probably doesn't have CORS enabled for the Token endpoint...try another provider. " + error window.alert(errorMessage); }) } render() { const { error, errorDescription } = this.props; return (error && <div className="popup-container step-container">Error: {error} - {errorDescription}</div>) } } window.PopupWindow = PopupWindow; ```
/content/code_sandbox/clients-SPA-legacy/clients-js-only-react-legacy/src/main/resources/static/pkce-realcase/js/components/popup/popup_window.js
javascript
2016-03-02T09:04:07
2024-08-06T03:02:12
spring-security-oauth
Baeldung/spring-security-oauth
1,982
479
```javascript // Navbar Section class Navbar extends React.Component { state = { logoutVisible: false } toggleLogout = () => { this.setState({ logoutVisible: !this.state.logoutVisible }) } render() { const { user, auth } = this.props; const { name, lastName, picture } = user || {}; return (<nav> <div className="menu"> <ul> <il onClick={this.props.changeView.bind(this, 'listing')}>Listing</il> {user && <il onClick={this.props.changeView.bind(this, 'profile')}>Profile</il>} </ul> </div> <div className="login-container"> {auth ? <div onClick={this.toggleLogout}> <div className="user-info"> <div className="picture"> <img src={picture || '/common/images/default-profile.png'} /> </div> <div className="greeting">Welcome {name ? name + ' ' : ''} {lastName || ''}!</div> </div> {this.state.logoutVisible && <div className="logout"> <button onClick={this.props.onLogoutFn}>Logout</button> </div>} </div> : <div className="login"><button onClick={this.props.onLoginFn}>Login</button></div>} </div> </nav>) }; } window.Navbar = Navbar; ```
/content/code_sandbox/clients-SPA-legacy/clients-js-only-react-legacy/src/main/resources/static/pkce-realcase/js/components/navbar/navbar.js
javascript
2016-03-02T09:04:07
2024-08-06T03:02:12
spring-security-oauth
Baeldung/spring-security-oauth
1,982
306
```javascript // Listing Page class Listing extends React.Component { state = { listing: null, currentColor: '', loading: true } componentDidMount() { this.refreshListing(); } refreshListing = () => { var self = this; axios.get(RESOURCE_CONFIGS.GET_COLORS_URL).then(function (response) { self.setState({ listing: response.data, loading: false }) }).catch(function (error) { console.error(error); const alertMessage = `Error retrieving colors. Please make sure: the resource server is accessible\n ${error}`; window.alert(alertMessage); }) this.setState({ loading: true }) } onDeleteFn = (id) => { const headers = this.props.auth ? { headers: { 'Authorization': 'Bearer ' + this.props.auth.access_token } } : {}; var self = this; axios.delete(RESOURCE_CONFIGS.DELETE_COLOR_URL.replace("{id}", id), headers).then(function () { self.refreshListing() }).catch(function (error) { console.error(error); const alertMessage = `Error deleting color. Please make sure: the resource server is accessible you're logged you have the 'colors:delete' scope checked on the Profile page ${error}`; window.alert(alertMessage); }) } onCreateFn = () => { var self = this; const headers = this.props.auth ? { headers: { 'Authorization': 'Bearer ' + this.props.auth.access_token, 'Content-type': 'text/plain; charset=UTF-8' } } : { headers: { 'Content-type': 'text/plain; charset=UTF-8' } }; axios.post(RESOURCE_CONFIGS.SAVE_COLOR_URL, this.state.currentColor, headers).then(function () { self.refreshListing() }).catch(function (error) { console.error(error); const alertMessage = `Error creating color. Please make sure: the resource server is accessible you're logged you have the 'colors:create' scope checked on the Profile page ${error}`; window.alert(alertMessage); }) } handleChange = (e) => { this.setState({ currentColor: e.target.value }); } render() { return ( <div className="listing-container"> {this.state.listing && <div> <div className="listing"> {!this.state.loading ? this.state.listing.map((element) => ( <ListingItem key={element.id} value={element.value} onDeleteFn={this.onDeleteFn.bind(this, element.id)} /> )) : <Spinner /> } </div> <div className="create-color" disabled={this.state.loading}> <input type="text" value={this.state.currentColor} onChange={this.handleChange.bind(this)} /> <button onClick={this.onCreateFn}>Create!</button> </div> </div> } </div> ); } } window.Listing = Listing; ```
/content/code_sandbox/clients-SPA-legacy/clients-js-only-react-legacy/src/main/resources/static/pkce-realcase/js/components/pages/listing.js
javascript
2016-03-02T09:04:07
2024-08-06T03:02:12
spring-security-oauth
Baeldung/spring-security-oauth
1,982
663
```html <!DOCTYPE html> <html> <head> <!-- Styles --> <link rel="stylesheet" href="/pkce-stepbystep/css/bael-oauth-pkce-styles.css"> <link href="path_to_url" rel="stylesheet"> <!-- Import the React, React-Dom and Babel libraries --> <!-- Note: Here we are using React's unminified-development version --> <script src="path_to_url" crossorigin></script> <script src="path_to_url" crossorigin></script> <script src="path_to_url"></script> <!-- Axios to make requests easily --> <script src="path_to_url"></script> </head> <body> <div id="root"></div> <script type="text/javascript" src="/common/js/provider_configs.js"></script> <script type="text/javascript" src="/common/js/common_functions.js"></script> <script type="text/babel" src="/pkce-stepbystep/js/components/popup/popup_window.js"></script> <script type="text/babel"> const urlParams = new URLSearchParams(window.location.search); console.log("Auth Service redirected with params:"); console.log(window.location.search); console.log("========================="); const popupProps = { authCode: urlParams.get('code'), state: urlParams.get('state'), error: urlParams.get('error'), errorDescription: urlParams.get('error_description') } // popup rendering: const rootElement = document.getElementById('root'); ReactDOM.render(<PopupWindow {...popupProps} />, rootElement); </script> </body> </html> ```
/content/code_sandbox/clients-SPA-legacy/clients-js-only-react-legacy/src/main/resources/static/pkce-stepbystep/popup_code_handler.html
html
2016-03-02T09:04:07
2024-08-06T03:02:12
spring-security-oauth
Baeldung/spring-security-oauth
1,982
353
```html <!DOCTYPE html> <html> <head> <title>Step by Step - Baeldung's JS-only SPA Oauth Client</title> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width"> <!-- Styles --> <link rel="stylesheet" href="/pkce-stepbystep/css/bael-oauth-pkce-styles.css"> <link href="path_to_url" rel="stylesheet"> <!-- Import the React, React-Dom and Babel libraries --> <!-- Note: Here we are using React's unminified-development version --> <script src="path_to_url" crossorigin></script> <script src="path_to_url" crossorigin></script> <script src="path_to_url"></script> <!-- Axios to make requests easily --> <script src="path_to_url"></script> </head> <body> <div id="root"></div> <script type="text/javascript" src="/common/js/provider_configs.js"></script> <script type="text/javascript" src="/common/js/common_functions.js"></script> <script type="text/javascript" src="/common/js/code_verifier_functions.js"></script> <script type="text/javascript" src="/common/js/code_challenge_functions.js"></script> <script type="text/babel" src="/common/js/components/spinner.js"></script> <script type="text/babel" src="/pkce-stepbystep/js/components/steps/step0.js"></script> <script type="text/babel" src="/pkce-stepbystep/js/components/steps/step1.js"></script> <script type="text/babel" src="/pkce-stepbystep/js/components/steps/step2.js"></script> <script type="text/babel" src="/pkce-stepbystep/js/components/steps/step3.js"></script> <script type="text/babel" src="/pkce-stepbystep/js/components/app.js"></script> <script type="text/babel"> // main rendering: const rootElement = document.getElementById('root'); ReactDOM.render(<App/>, rootElement); </script> </body> </html> ```
/content/code_sandbox/clients-SPA-legacy/clients-js-only-react-legacy/src/main/resources/static/pkce-stepbystep/index.html
html
2016-03-02T09:04:07
2024-08-06T03:02:12
spring-security-oauth
Baeldung/spring-security-oauth
1,982
478
```css *, *:before, *:after { box-sizing: border-box; } body { margin: 0; font-family: 'Raleway', sans-serif; } .baeldung-container, .popup-container { text-align: center; } .step-container { padding: 0 10%; margin: 0 5%; min-height: 30vh; display: flex; flex-direction: column; justify-content: space-evenly; } .step-container.step2 { margin: 0 5% 20px 5%; } .step-container:nth-child(odd) { background-color: #63b175; color: white; } .step-container button { border-style: solid; font-size: 1.5em; border-radius: 20px; padding: 5px 20px; margin: 20px 0; } .step-container:nth-child(odd) button { background-color: #63b175; border-color: white; color: white; } .step-container:nth-child(odd) button:hover { background-color: white; color: #63b175; } .step-container:nth-child(even) button { background-color: white; border-color: #63b175; color: #63b175; } .step-container:nth-child(even) button:hover { background-color: #63b175; color: white; } .step-container .action { display: flex; justify-content: space-evenly; } .step-container .action button:disabled { background-color: #E0E0E0; color: gray; border-color: gray; } .step-container .result { padding: 20px; } .step-container .result.large { border-style: solid; border-radius: 5px; border-color: black; } .step-container .result.large span { border-style: none; } .step-container .result span { border-style: solid; padding: 5px 15px; border-radius: 5px; border-color: black; word-wrap: break-word; } .step-container:nth-child(even) .result span { color: #63b175; } .summary { font-size: 1.23em; } .note { font-size: 0.8em; } .result { font-size: 1.7em; } h2 { margin: 0.3em; } /* Spinner */ .spinner-container { padding-bottom: 20px; } .spinner-container .spinner-text { font-size: 1.2em; } .spinner-container .spinner-icon { border: 16px solid green; border-top: 16px solid lightgray; border-radius: 50%; width: 120px; height: 120px; animation: spin 2s linear infinite; margin: auto; } @keyframes spin { 0% { transform: rotate(0deg); } 100% { transform: rotate(360deg); } } /* User Info */ .user-info { border: solid #63b175 5px; border-radius: 20px; position: relative; } .user-info .name { font-size: 2em; margin: 0.5em; font-weight: bold; border-bottom: solid #63b175; padding-bottom: 3em; margin: 0; padding-top: 10px; } .user-info .picture { width: 100%; position: absolute; } .user-info .picture img { border: solid #63b175 10px; height: 12em; border-radius: 100px; transform: translateY(-6em); } .user-info .email { font-size: 2em; font-weight: bold; border-top: solid #63b175; padding-top: 3em; margin: 0; padding-bottom: 10px; } ```
/content/code_sandbox/clients-SPA-legacy/clients-js-only-react-legacy/src/main/resources/static/pkce-stepbystep/css/bael-oauth-pkce-styles.css
css
2016-03-02T09:04:07
2024-08-06T03:02:12
spring-security-oauth
Baeldung/spring-security-oauth
1,982
861
```javascript // App component: class App extends React.Component { state = { step1: { started: false, codeVerifier: '', codeChallenge: '', state: '', provider: 'AUTH0' }, step2: { started: false, popup: null, authCode: '', accessToken: '' }, step3: { started: false, profile: {} } }; componentDidUpdate() { this.lastElement.scrollIntoView({ block: "end", behavior: "smooth" }); } executeStep1CreateCodes = (provider) => { const state = generate_state(); const codeVerifier = generate_code_verifier(); const codeChallenge = generate_code_challenge(codeVerifier); this.setState({ step1: { ...this.state.step1, started: true, codeVerifier, codeChallenge, state, provider } }) } executeStep2RequestCode = () => { const { AUTH_URL, CLIENT_ID, CONFIGURED_REDIRECT_URIS: { STEP_BY_STEP: redirectUri }, SCOPES, AUDIENCE } = PROVIDER_CONFIGS[this.state.step1.provider]; const authorizationUrl = AUTH_URL + '?client_id=' + CLIENT_ID + "&response_type=code" + '&scope=' + SCOPES + '&redirect_uri=' + redirectUri + '&state=' + this.state.step1.state + '&code_challenge_method=S256' + '&code_challenge=' + this.state.step1.codeChallenge + (AUDIENCE ? ('&audience=' + AUDIENCE) : ''); console.log("Opening popup sending user to authorization URL with QueryParams:", AUTH_URL, authorizationUrl.split("&").slice(1)); console.log("========================="); window.addEventListener('message', this.onPopupResponseFn, false); var popup = window.open(authorizationUrl, 'external_login_page', 'width=800,height=600,left=200,top=100'); this.setState({ step2: { ...this.state.step2, started: true, popup } }) } extractProfileField = (data, fieldString) => { if (!fieldString) return; var fields = fieldString.split('.'); var dataValue = { ...data }; for (var field of fields) { dataValue = dataValue[field]; } return dataValue; } executeStep3RequestResource = () => { const { PROFILE_URL, PROFILE_FIELDS } = PROVIDER_CONFIGS[this.state.step1.provider]; const headers = { headers: { Authorization: 'Bearer ' + this.state.step2.accessToken } }; var self = this; axios.get(PROFILE_URL, headers).then(function (response) { const name = self.extractProfileField(response.data, PROFILE_FIELDS.NAME); const lastName = self.extractProfileField(response.data, PROFILE_FIELDS.LAST_NAME); const email = self.extractProfileField(response.data, PROFILE_FIELDS.EMAIL); const picture = self.extractProfileField(response.data, PROFILE_FIELDS.PICTURE); const profile = { name, lastName, email, picture }; self.setState({ step3: { ...self.state.step3, profile } }) }) .catch(function (error) { const errorMessage = "Error retrieving user information" + error; window.alert(errorMessage); }) this.setState({ step3: { ...this.state.step3, started: true, } }) } onPopupResponseFn = (e) => { const eventType = e.data && e.data.type; switch (eventType) { case 'authCode': if (e.data.state !== this.state.step1.state) { window.alert("Retrieved state [" + e.data.state + "] didn't match stored one! Try again"); break; } const popupUpdate = { codeVerifier: this.state.step1.codeVerifier, provider: this.state.step1.provider } this.state.step2.popup.postMessage(popupUpdate, "*"); this.setState({ step2: { ...this.state.step2, authCode: e.data.authCode } }); break; case 'accessToken': this.setState({ step2: { ...this.state.step2, accessToken: e.data.accessToken } }); break; case 'closed': this.setState({ step2: { ...this.state.step2, popup: null } }); break; } } render() { const { step1, step2, step3 } = { ...this.state }; return ( <div className="baeldung-container"> <Step0 providers={Object.keys(PROVIDER_CONFIGS)} nextStepStarted={step1.started} nextStepFn={this.executeStep1CreateCodes} /> {step1.started && <Step1 {...step1} nextStepStarted={step2.started} nextStepFn={this.executeStep2RequestCode} />} {step2.started && <Step2 {...step2} nextStepStarted={step3.started} nextStepFn={this.executeStep3RequestResource} />} {step3.started && <Step3 {...step3} />} <div ref={(ref) => { this.lastElement = ref; }}> </div> </div> ) } } window.App = App; ```
/content/code_sandbox/clients-SPA-legacy/clients-js-only-react-legacy/src/main/resources/static/pkce-stepbystep/js/components/app.js
javascript
2016-03-02T09:04:07
2024-08-06T03:02:12
spring-security-oauth
Baeldung/spring-security-oauth
1,982
1,154
```javascript // PopupWindow component: class PopupWindow extends React.Component { state = { codeVerifier: '', accessToken: '', requestedAccessToken: false, provider: 'AUTH0' }; componentDidMount() { if (!this.props.error) { window.addEventListener('message', this.onMainWindowMessageFn, false); const authCodeStatus = { authCode: this.props.authCode, state: this.props.state, type: 'authCode' } window.opener ? window.opener.postMessage(authCodeStatus, "*") : window.alert("This is not a popup window!"); } else { window.alert("Error: " + this.props.error); } } onMainWindowMessageFn = (e) => { const { codeVerifier, provider } = e.data; if (codeVerifier) this.setState({ codeVerifier, provider }) } requestAccessTokenFn = () => { const { TOKEN_URI, CLIENT_ID, CONFIGURED_REDIRECT_URIS: { STEP_BY_STEP: redirectUri }, AUDIENCE } = PROVIDER_CONFIGS[this.state.provider]; const tokenRequestBody = { grant_type: 'authorization_code', redirect_uri: redirectUri, code: this.props.authCode, code_verifier: this.state.codeVerifier, client_id: CLIENT_ID } if (AUDIENCE) tokenRequestBody.audience = AUDIENCE; var headers = { 'Content-type': 'application/x-www-form-urlencoded; charset=UTF-8' } console.log("Making POST request to URL [" + TOKEN_URI + "] with Headers:"); console.log(headers); console.log("and body:"); console.log(tokenRequestBody); console.log("========================="); var self = this; axios.post(TOKEN_URI, new URLSearchParams(tokenRequestBody), { headers }) .then(function (response) { console.log("Retrieved response with data:") console.log(response.data); console.log("========================="); const accessToken = response.data.access_token; const tokenStatus = { type: 'accessToken', accessToken } window.opener ? window.opener.postMessage(tokenStatus, "*") : window.alert("This is not a popup window!"); self.setState({ accessToken }) }) .catch(function (error) { const errorMessage = "Error retrieving token: Provider probably doesn't have CORS enabled for the Token endpoint...try another provider. " + error window.alert(errorMessage); }) this.setState({ requestedAccessToken: true }) } closeWindow = () => { const closeMessage = { type: 'closed' } window.opener ? window.opener.postMessage(closeMessage, "*") : window.alert("This is not a popup window!"); window.close(); } render() { const { authCode, error, errorDescription } = this.props; const { accessToken, requestedAccessToken } = this.state; return (error ? <div className="popup-container step-container">Error: {error} - {errorDescription}</div> : <div className="popup-container step-container"> <h2>Popup - OAuth 2 Dance</h2> <div className="summary">Auth Server retrieved auth code:</div> <div className="result large"><span>{authCode}</span></div> {(!accessToken) ? <div> <div className="summary">We got just a couple of minutes before the Auth Code expires...</div> <div className="action"> <button onClick={this.requestAccessTokenFn} disabled={requestedAccessToken}>Request Access Token!</button> </div> </div> : <div> <div className="summary">Auth Server retrieved Access Token:</div> <div className="result large"><span>{accessToken}</span></div> <div className="action"> <button onClick={this.closeWindow}>Return</button> </div> </div> } </div> ) } } window.PopupWindow = PopupWindow; ```
/content/code_sandbox/clients-SPA-legacy/clients-js-only-react-legacy/src/main/resources/static/pkce-stepbystep/js/components/popup/popup_window.js
javascript
2016-03-02T09:04:07
2024-08-06T03:02:12
spring-security-oauth
Baeldung/spring-security-oauth
1,982
856
```javascript // Step 2 - Login & obteain access token const Step2 = ({ accessToken, authCode, popup, nextStepFn, nextStepStarted }) => { return (<div className="step2 step-container"> <h2>Step 2 - Login</h2> {authCode && (<div> <div className="summary">Provider retrieved authorization code:</div> <div className="result large"><span>{authCode}</span></div> </div>) } {accessToken && (<div> <div className="summary">Used 'Code Verifier' to obtain the Access Token!</div> <div className="result large"><span>{accessToken}</span></div> </div>) } {!!popup ? <Spinner spinnerText='Waiting for Login process...' /> : (<div className="action"> <button onClick={nextStepFn} disabled={nextStepStarted}>Retrieve Secured User Information!</button> </div>) } </div> ) }; window.Step2 = Step2; ```
/content/code_sandbox/clients-SPA-legacy/clients-js-only-react-legacy/src/main/resources/static/pkce-stepbystep/js/components/steps/step2.js
javascript
2016-03-02T09:04:07
2024-08-06T03:02:12
spring-security-oauth
Baeldung/spring-security-oauth
1,982
228
```javascript // Step 1 - Create Codes const Step1 = ({ codeVerifier, codeChallenge, state, nextStepFn, nextStepStarted }) => ( <div className="step1 step-container"> <h2>Step 1 - Create the codes</h2> <div className="summary">The client must generate the tipical 'state' value to compare later and avoid CSRF:</div> <div className="result"><span>{state}</span></div> <div className="summary">We also generate a "Code Verifier" per request:</div> <div className="result"><span>{codeVerifier}</span></div> <div className="summary">Additionally, it should transform the previous code using a S256 transfromation method. This is called the "Code Challenge":</div> <div className="result"><span>{codeChallenge}</span></div> <div className="action"> <button onClick={nextStepFn} disabled={nextStepStarted}>Request Auth Code!</button> </div> </div> ) window.Step1 = Step1; ```
/content/code_sandbox/clients-SPA-legacy/clients-js-only-react-legacy/src/main/resources/static/pkce-stepbystep/js/components/steps/step1.js
javascript
2016-03-02T09:04:07
2024-08-06T03:02:12
spring-security-oauth
Baeldung/spring-security-oauth
1,982
232
```javascript // Step 3 - Secured User Information const Step3 = ({ profile }) => { const { name, lastName, email, picture } = profile; return ( <div className="step3 step-container"> <h2>Step 3 - Retrieving Secured Resource</h2> <div className="user-info"> <div className="name"> {name ? name + ' ' : ''} {lastName || ''} </div> <div className="picture"> <img src={picture || '/common/images/default-profile.png'} /> </div> <div className="email"> {email || ''} </div> </div> </div> ) }; window.Step3 = Step3; ```
/content/code_sandbox/clients-SPA-legacy/clients-js-only-react-legacy/src/main/resources/static/pkce-stepbystep/js/components/steps/step3.js
javascript
2016-03-02T09:04:07
2024-08-06T03:02:12
spring-security-oauth
Baeldung/spring-security-oauth
1,982
159
```javascript // Step 0 - Initiate Process const Step0 = ({ providers, nextStepFn, nextStepStarted }) => ( <div className="step0 step-container"> <h2>JS OAuth Client using PKCE - Step By Step</h2> <div className="summary">Click to start the authentication process, step by step.</div> <div className="note">Note: Most providers don't support PKCE for SPA yet, resulting in an error retrieving when retrieving the Token (CORS not enabled for that endpoint). <br /> At the moment of creating the tutorial, only Auth0 works properly</div> <div className="action"> {providers.map((provider) => (<button key={provider} onClick={nextStepFn.bind(this, provider)} disabled={nextStepStarted}>Use {provider}</button>)) } </div> </div> ) window.Step0 = Step0; ```
/content/code_sandbox/clients-SPA-legacy/clients-js-only-react-legacy/src/main/resources/static/pkce-stepbystep/js/components/steps/step0.js
javascript
2016-03-02T09:04:07
2024-08-06T03:02:12
spring-security-oauth
Baeldung/spring-security-oauth
1,982
199
```java package com.baeldung.clientjsonlyreact; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; @SpringBootApplication public class ClientJsOnlyReactApplication { public static void main(String[] args) { SpringApplication.run(ClientJsOnlyReactApplication.class, args); } } ```
/content/code_sandbox/clients-SPA-legacy/clients-js-only-react-legacy/src/main/java/com/baeldung/clientjsonlyreact/ClientJsOnlyReactApplication.java
java
2016-03-02T09:04:07
2024-08-06T03:02:12
spring-security-oauth
Baeldung/spring-security-oauth
1,982
59
```java package com.baeldung.resourceserverauth0; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.test.context.junit4.SpringRunner; @RunWith(SpringRunner.class) @SpringBootTest public class OauthResourceServerAuth0ApplicationTests { @Test public void contextLoads() { } } ```
/content/code_sandbox/clients-SPA-legacy/oauth-resource-server-auth0-legacy/src/test/java/com/baeldung/resourceserverauth0/OauthResourceServerAuth0ApplicationTests.java
java
2016-03-02T09:04:07
2024-08-06T03:02:12
spring-security-oauth
Baeldung/spring-security-oauth
1,982
70
```sqlpl insert into color values(1001, 'red'); insert into color values(1002, 'green'); insert into color values(1003, 'blue'); ```
/content/code_sandbox/clients-SPA-legacy/oauth-resource-server-auth0-legacy/src/main/resources/data.sql
sqlpl
2016-03-02T09:04:07
2024-08-06T03:02:12
spring-security-oauth
Baeldung/spring-security-oauth
1,982
37
```yaml spring: security: oauth2: resourceserver: jwt: jwk-set-uri: path_to_url user: password: pass datasource: url: jdbc:h2:mem:bael-colors username: sa password: driver-class-name: org.h2.Driver server: port: 8081 ```
/content/code_sandbox/clients-SPA-legacy/oauth-resource-server-auth0-legacy/src/main/resources/application.yml
yaml
2016-03-02T09:04:07
2024-08-06T03:02:12
spring-security-oauth
Baeldung/spring-security-oauth
1,982
79
```java package com.baeldung.resourceserverauth0; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; @SpringBootApplication public class OauthResourceServerAuth0Application { public static void main(String[] args) { SpringApplication.run(OauthResourceServerAuth0Application.class, args); } } ```
/content/code_sandbox/clients-SPA-legacy/oauth-resource-server-auth0-legacy/src/main/java/com/baeldung/resourceserverauth0/OauthResourceServerAuth0Application.java
java
2016-03-02T09:04:07
2024-08-06T03:02:12
spring-security-oauth
Baeldung/spring-security-oauth
1,982
63
```java package com.baeldung.resourceserverauth0.model; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.Id; @Entity public class Color { @Id @GeneratedValue private Long id; private String value; protected Color() { } public Color(String value) { this.value = value; } public String getValue() { return this.value; } public Long getId() { return id; } } ```
/content/code_sandbox/clients-SPA-legacy/oauth-resource-server-auth0-legacy/src/main/java/com/baeldung/resourceserverauth0/model/Color.java
java
2016-03-02T09:04:07
2024-08-06T03:02:12
spring-security-oauth
Baeldung/spring-security-oauth
1,982
99
```java package com.baeldung.resourceserverauth0.dao; import org.springframework.data.repository.CrudRepository; import com.baeldung.resourceserverauth0.model.Color; public interface ColorRepository extends CrudRepository<Color, Long> { } ```
/content/code_sandbox/clients-SPA-legacy/oauth-resource-server-auth0-legacy/src/main/java/com/baeldung/resourceserverauth0/dao/ColorRepository.java
java
2016-03-02T09:04:07
2024-08-06T03:02:12
spring-security-oauth
Baeldung/spring-security-oauth
1,982
46
```java package com.baeldung.resourceserverauth0.configs; import org.springframework.http.HttpMethod; import org.springframework.security.config.annotation.web.builders.HttpSecurity; import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity; import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter; @EnableWebSecurity public class WebSecurityConfig extends WebSecurityConfigurerAdapter { @Override protected void configure(HttpSecurity http) throws Exception { http.authorizeRequests() .antMatchers(HttpMethod.OPTIONS, "/colors", "/colors/**") .permitAll() .antMatchers(HttpMethod.POST, "/colors") .hasAuthority("SCOPE_colors:create") .antMatchers(HttpMethod.DELETE, "/colors/*") .hasAuthority("SCOPE_colors:delete") .antMatchers(HttpMethod.GET, "/colors") .permitAll() .and() .oauth2ResourceServer() .jwt(); } } ```
/content/code_sandbox/clients-SPA-legacy/oauth-resource-server-auth0-legacy/src/main/java/com/baeldung/resourceserverauth0/configs/WebSecurityConfig.java
java
2016-03-02T09:04:07
2024-08-06T03:02:12
spring-security-oauth
Baeldung/spring-security-oauth
1,982
192
```java package com.baeldung.resourceserverauth0.web.controllers; import java.util.ArrayList; import java.util.List; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.HttpStatus; import org.springframework.web.bind.annotation.CrossOrigin; import org.springframework.web.bind.annotation.DeleteMapping; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PathVariable; 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.RequestMethod; import org.springframework.web.bind.annotation.ResponseStatus; import org.springframework.web.bind.annotation.RestController; import com.baeldung.resourceserverauth0.dao.ColorRepository; import com.baeldung.resourceserverauth0.model.Color; @CrossOrigin(origins = "path_to_url", allowedHeaders = "Authorization") @RestController @RequestMapping("/colors") public class ColorsRestController { @Autowired ColorRepository repository; @GetMapping public List<Color> retrieveNonSecuredResource() { List<Color> colors = new ArrayList<>(); repository.findAll() .forEach(colors::add); return colors; } @PostMapping @ResponseStatus(code = HttpStatus.CREATED) public void retrieveSecuredResource(@RequestBody String color) { repository.save(new Color(color)); } @DeleteMapping("/{id}") public void retrieveNonAccessibledResource(@PathVariable("id") Long id) { repository.deleteById(id); } } ```
/content/code_sandbox/clients-SPA-legacy/oauth-resource-server-auth0-legacy/src/main/java/com/baeldung/resourceserverauth0/web/controllers/ColorsRestController.java
java
2016-03-02T09:04:07
2024-08-06T03:02:12
spring-security-oauth
Baeldung/spring-security-oauth
1,982
291
```java package com.baeldung.auth; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.boot.autoconfigure.liquibase.LiquibaseAutoConfiguration; import org.springframework.boot.autoconfigure.web.ServerProperties; import org.springframework.boot.context.event.ApplicationReadyEvent; import org.springframework.boot.context.properties.EnableConfigurationProperties; import org.springframework.context.ApplicationListener; import org.springframework.context.annotation.Bean; import com.baeldung.auth.config.KeycloakServerProperties; @SpringBootApplication(exclude = LiquibaseAutoConfiguration.class) @EnableConfigurationProperties({ KeycloakServerProperties.class }) public class AuthorizationServerApp { private static final Logger LOG = LoggerFactory.getLogger(AuthorizationServerApp.class); public static void main(String[] args) throws Exception { SpringApplication.run(AuthorizationServerApp.class, args); } @Bean ApplicationListener<ApplicationReadyEvent> onApplicationReadyEventListener(ServerProperties serverProperties, KeycloakServerProperties keycloakServerProperties) { return (evt) -> { Integer port = serverProperties.getPort(); String keycloakContextPath = keycloakServerProperties.getContextPath(); LOG.info("Embedded Keycloak started: path_to_url{}{} to use keycloak", port, keycloakContextPath); }; } } ```
/content/code_sandbox/oauth-sso/sso-authorization-server/src/main/java/com/baeldung/auth/AuthorizationServerApp.java
java
2016-03-02T09:04:07
2024-08-06T03:02:12
spring-security-oauth
Baeldung/spring-security-oauth
1,982
262
```java package com.baeldung.auth.config; import java.io.File; import org.keycloak.Config.Scope; import org.keycloak.common.Profile; import org.keycloak.common.profile.PropertiesFileProfileConfigResolver; import org.keycloak.common.profile.PropertiesProfileConfigResolver; import org.keycloak.platform.PlatformProvider; import org.keycloak.services.ServicesLogger; public class SimplePlatformProvider implements PlatformProvider { public SimplePlatformProvider() { Profile.configure(new PropertiesProfileConfigResolver(System.getProperties()), new PropertiesFileProfileConfigResolver()); } Runnable shutdownHook; @Override public void onStartup(Runnable startupHook) { startupHook.run(); } @Override public void onShutdown(Runnable shutdownHook) { this.shutdownHook = shutdownHook; } @Override public void exit(Throwable cause) { ServicesLogger.LOGGER.fatal(cause); exit(1); } private void exit(int status) { new Thread() { @Override public void run() { System.exit(status); } }.start(); } @Override public File getTmpDirectory() { return new File(System.getProperty("java.io.tmpdir")); } @Override public ClassLoader getScriptEngineClassLoader(Scope scriptProviderConfig) { return null; } @Override public String name() { return "oauth-authorization-server"; } } ```
/content/code_sandbox/oauth-sso/sso-authorization-server/src/main/java/com/baeldung/auth/config/SimplePlatformProvider.java
java
2016-03-02T09:04:07
2024-08-06T03:02:12
spring-security-oauth
Baeldung/spring-security-oauth
1,982
292
```java package com.baeldung.auth.config; import org.jboss.resteasy.core.ResteasyContext; import org.jboss.resteasy.spi.Dispatcher; import org.jboss.resteasy.spi.ResteasyProviderFactory; import org.keycloak.common.util.ResteasyProvider; public class Resteasy3Provider implements ResteasyProvider { @Override public <R> R getContextData(Class<R> type) { return ResteasyProviderFactory.getInstance() .getContextData(type); } @Override public void pushDefaultContextObject(Class type, Object instance) { ResteasyProviderFactory.getInstance() .getContextData(Dispatcher.class) .getDefaultContextObjects() .put(type, instance); } @Override public void pushContext(Class type, Object instance) { ResteasyContext.pushContext(type, instance); } @Override public void clearContextData() { ResteasyContext.clearContextData(); } } ```
/content/code_sandbox/oauth-sso/sso-authorization-server/src/main/java/com/baeldung/auth/config/Resteasy3Provider.java
java
2016-03-02T09:04:07
2024-08-06T03:02:12
spring-security-oauth
Baeldung/spring-security-oauth
1,982
198
```java package com.baeldung.auth.config; import java.util.NoSuchElementException; import org.keycloak.Config; import org.keycloak.exportimport.ExportImportManager; import org.keycloak.models.KeycloakSession; import org.keycloak.representations.idm.RealmRepresentation; import org.keycloak.services.managers.ApplianceBootstrap; import org.keycloak.services.managers.RealmManager; import org.keycloak.services.resources.KeycloakApplication; import org.keycloak.services.util.JsonConfigProviderFactory; import org.keycloak.util.JsonSerialization; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.core.io.ClassPathResource; import org.springframework.core.io.Resource; import com.baeldung.auth.config.KeycloakServerProperties.AdminUser; public class EmbeddedKeycloakApplication extends KeycloakApplication { private static final Logger LOG = LoggerFactory.getLogger(EmbeddedKeycloakApplication.class); static KeycloakServerProperties keycloakServerProperties; protected void loadConfig() { JsonConfigProviderFactory factory = new RegularJsonConfigProviderFactory(); Config.init(factory.create() .orElseThrow(() -> new NoSuchElementException("No value present"))); } @Override protected ExportImportManager bootstrap() { final ExportImportManager exportImportManager = super.bootstrap(); createMasterRealmAdminUser(); createBaeldungRealm(); return exportImportManager; } private void createMasterRealmAdminUser() { KeycloakSession session = getSessionFactory().create(); ApplianceBootstrap applianceBootstrap = new ApplianceBootstrap(session); AdminUser admin = keycloakServerProperties.getAdminUser(); try { session.getTransactionManager() .begin(); applianceBootstrap.createMasterRealmUser(admin.getUsername(), admin.getPassword()); session.getTransactionManager() .commit(); } catch (Exception ex) { LOG.warn("Couldn't create keycloak master admin user: {}", ex.getMessage()); session.getTransactionManager() .rollback(); } session.close(); } private void createBaeldungRealm() { KeycloakSession session = getSessionFactory().create(); try { session.getTransactionManager() .begin(); RealmManager manager = new RealmManager(session); Resource lessonRealmImportFile = new ClassPathResource(keycloakServerProperties.getRealmImportFile()); manager.importRealm(JsonSerialization.readValue(lessonRealmImportFile.getInputStream(), RealmRepresentation.class)); session.getTransactionManager() .commit(); } catch (Exception ex) { LOG.warn("Failed to import Realm json file: {}", ex.getMessage()); session.getTransactionManager() .rollback(); } session.close(); } } ```
/content/code_sandbox/oauth-sso/sso-authorization-server/src/main/java/com/baeldung/auth/config/EmbeddedKeycloakApplication.java
java
2016-03-02T09:04:07
2024-08-06T03:02:12
spring-security-oauth
Baeldung/spring-security-oauth
1,982
527
```java package com.baeldung.auth.config; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import javax.naming.CompositeName; import javax.naming.InitialContext; import javax.naming.Name; import javax.naming.NameParser; import javax.naming.NamingException; import javax.naming.spi.NamingManager; import javax.sql.DataSource; import org.jboss.resteasy.plugins.server.servlet.HttpServlet30Dispatcher; import org.jboss.resteasy.plugins.server.servlet.ResteasyContextParameters; import org.keycloak.platform.Platform; import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean; import org.springframework.boot.web.servlet.FilterRegistrationBean; import org.springframework.boot.web.servlet.ServletRegistrationBean; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; @Configuration public class EmbeddedKeycloakConfig { @Bean ServletRegistrationBean<HttpServlet30Dispatcher> keycloakJaxRsApplication(KeycloakServerProperties keycloakServerProperties, DataSource dataSource) throws Exception { mockJndiEnvironment(dataSource); EmbeddedKeycloakApplication.keycloakServerProperties = keycloakServerProperties; ServletRegistrationBean<HttpServlet30Dispatcher> servlet = new ServletRegistrationBean<>(new HttpServlet30Dispatcher()); servlet.addInitParameter("jakarta.ws.rs.Application", EmbeddedKeycloakApplication.class.getName()); servlet.addInitParameter(ResteasyContextParameters.RESTEASY_SERVLET_MAPPING_PREFIX, keycloakServerProperties.getContextPath()); servlet.addInitParameter(ResteasyContextParameters.RESTEASY_USE_CONTAINER_FORM_PARAMS, "true"); servlet.addUrlMappings(keycloakServerProperties.getContextPath() + "/*"); servlet.setLoadOnStartup(1); servlet.setAsyncSupported(true); return servlet; } @Bean FilterRegistrationBean<EmbeddedKeycloakRequestFilter> keycloakSessionManagement(KeycloakServerProperties keycloakServerProperties) { FilterRegistrationBean<EmbeddedKeycloakRequestFilter> filter = new FilterRegistrationBean<>(); filter.setName("Keycloak Session Management"); filter.setFilter(new EmbeddedKeycloakRequestFilter()); filter.addUrlPatterns(keycloakServerProperties.getContextPath() + "/*"); return filter; } private void mockJndiEnvironment(DataSource dataSource) throws NamingException { NamingManager.setInitialContextFactoryBuilder((env) -> (environment) -> new InitialContext() { @Override public Object lookup(Name name) { return lookup(name.toString()); } @Override public Object lookup(String name) { if ("spring/datasource".equals(name)) { return dataSource; } else if (name.startsWith("java:jboss/ee/concurrency/executor/")) { return fixedThreadPool(); } return null; } @Override public NameParser getNameParser(String name) { return CompositeName::new; } @Override public void close() { // NOOP } }); } @Bean("fixedThreadPool") public ExecutorService fixedThreadPool() { return Executors.newFixedThreadPool(5); } @Bean @ConditionalOnMissingBean(name = "springBootPlatform") protected SimplePlatformProvider springBootPlatform() { return (SimplePlatformProvider) Platform.getPlatform(); } } ```
/content/code_sandbox/oauth-sso/sso-authorization-server/src/main/java/com/baeldung/auth/config/EmbeddedKeycloakConfig.java
java
2016-03-02T09:04:07
2024-08-06T03:02:12
spring-security-oauth
Baeldung/spring-security-oauth
1,982
664
```java package com.baeldung.resource; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertNotNull; import java.util.HashMap; import java.util.Map; import org.junit.jupiter.api.Test; import org.springframework.http.HttpHeaders; import org.springframework.http.HttpStatus; import io.restassured.RestAssured; import io.restassured.response.Response; //Before running this live test make sure both authorization server and resource server in this module are running public class AuthorizationCodeLiveTest { public final static String AUTH_SERVER = "path_to_url"; public final static String RESOURCE_SERVER = "path_to_url"; private final static String REDIRECT_URL = "path_to_url"; private final static String CLIENT_ID = "ssoClient-1"; private final static String CLIENT_SECRET = "ssoClientSecret-1"; @Test public void givenUser_whenUseFooClient_thenOkForFooResourceOnly() { final String accessToken = obtainAccessTokenWithAuthorizationCode("john@test.com", "123"); final Response fooResponse = RestAssured.given() .header("Authorization", "Bearer " + accessToken) .get(RESOURCE_SERVER + "/api/foos/1"); assertEquals(200, fooResponse.getStatusCode()); assertNotNull(fooResponse.jsonPath() .get("name")); } private String obtainAccessTokenWithAuthorizationCode(String username, String password) { String authorizeUrl = AUTH_SERVER + "/auth"; String tokenUrl = AUTH_SERVER + "/token"; Map<String, String> loginParams = new HashMap<String, String>(); loginParams.put("client_id", CLIENT_ID); loginParams.put("response_type", "code"); loginParams.put("redirect_uri", REDIRECT_URL); loginParams.put("scope", "read write"); // user login Response response = RestAssured.given() .formParams(loginParams) .get(authorizeUrl); String cookieValue = response.getCookie("AUTH_SESSION_ID"); String authUrlWithCode = response.htmlPath() .getString("'**'.find{node -> node.name()=='form'}*.@action"); // get code Map<String, String> codeParams = new HashMap<String, String>(); codeParams.put("username", username); codeParams.put("password", password); response = RestAssured.given() .cookie("AUTH_SESSION_ID", cookieValue) .formParams(codeParams) .post(authUrlWithCode); final String location = response.getHeader(HttpHeaders.LOCATION); assertEquals(HttpStatus.FOUND.value(), response.getStatusCode()); final String code = location.split("#|=|&")[3]; // get access token Map<String, String> tokenParams = new HashMap<String, String>(); tokenParams.put("grant_type", "authorization_code"); tokenParams.put("client_id", CLIENT_ID); tokenParams.put("client_secret", CLIENT_SECRET); tokenParams.put("redirect_uri", REDIRECT_URL); tokenParams.put("code", code); response = RestAssured.given() .formParams(tokenParams) .post(tokenUrl); return response.jsonPath() .getString("access_token"); } } ```
/content/code_sandbox/oauth-sso/sso-resource-server/src/test/java/com/baeldung/resource/AuthorizationCodeLiveTest.java
java
2016-03-02T09:04:07
2024-08-06T03:02:12
spring-security-oauth
Baeldung/spring-security-oauth
1,982
666
```java package com.baeldung.resource; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; @SpringBootApplication public class ResourceServerApp { public static void main(String[] args) throws Exception { SpringApplication.run(ResourceServerApp.class, args); } } ```
/content/code_sandbox/oauth-sso/sso-resource-server/src/main/java/com/baeldung/resource/ResourceServerApp.java
java
2016-03-02T09:04:07
2024-08-06T03:02:12
spring-security-oauth
Baeldung/spring-security-oauth
1,982
54
```yaml server: port: 8081 servlet: context-path: /sso-resource-server ####### resource server configuration properties spring: security: oauth2: resourceserver: jwt: issuer-uri: path_to_url jwk-set-uri: path_to_url jpa: defer-datasource-initialization: true ```
/content/code_sandbox/oauth-sso/sso-resource-server/src/main/resources/application.yml
yaml
2016-03-02T09:04:07
2024-08-06T03:02:12
spring-security-oauth
Baeldung/spring-security-oauth
1,982
78
```java package com.baeldung.resource.service; import java.util.Optional; import com.baeldung.resource.persistence.model.Foo; public interface IFooService { Optional<Foo> findById(Long id); Foo save(Foo foo); Iterable<Foo> findAll(); } ```
/content/code_sandbox/oauth-sso/sso-resource-server/src/main/java/com/baeldung/resource/service/IFooService.java
java
2016-03-02T09:04:07
2024-08-06T03:02:12
spring-security-oauth
Baeldung/spring-security-oauth
1,982
55
```java package com.baeldung.resource.web.dto; public class FooDto { private long id; private String name; public FooDto() { super(); } public FooDto(final long id, final String name) { super(); this.id = id; this.name = name; } public long getId() { return id; } public void setId(final long id) { this.id = id; } public String getName() { return name; } public void setName(final String name) { this.name = name; } } ```
/content/code_sandbox/oauth-sso/sso-resource-server/src/main/java/com/baeldung/resource/web/dto/FooDto.java
java
2016-03-02T09:04:07
2024-08-06T03:02:12
spring-security-oauth
Baeldung/spring-security-oauth
1,982
125
```java package com.baeldung.client; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.test.context.junit.jupiter.SpringExtension; @ExtendWith(SpringExtension.class) @SpringBootTest(classes = { SSOClientApplication.class }) public class ContextIntegrationTest { @Test public void whenLoadApplication_thenSuccess() { } } ```
/content/code_sandbox/oauth-sso/sso-client-app-2/src/test/java/com/baeldung/client/ContextIntegrationTest.java
java
2016-03-02T09:04:07
2024-08-06T03:02:12
spring-security-oauth
Baeldung/spring-security-oauth
1,982
83
```yaml spring: security: oauth2: client: registration: custom: client-id: ssoClient-2 client-secret: ssoClientSecret-2 scope: read,write,openid authorization-grant-type: authorization_code redirect-uri: path_to_url provider: custom: authorization-uri: path_to_url token-uri: path_to_url user-info-uri: path_to_url jwk-set-uri: path_to_url user-name-attribute: preferred_username thymeleaf: cache: false cache: type: NONE server: port: 8084 servlet: context-path: /ui-two logging: level: org.springframework: INFO resourceserver: api: url: path_to_url ```
/content/code_sandbox/oauth-sso/sso-client-app-2/src/main/resources/application.yml
yaml
2016-03-02T09:04:07
2024-08-06T03:02:12
spring-security-oauth
Baeldung/spring-security-oauth
1,982
184
```html <!DOCTYPE html> <html lang="en"> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <title>Spring OAuth Client Thymeleaf - 2</title> <link rel="stylesheet" href="path_to_url" /> </head> <body> <nav class="navbar navbar-expand-lg navbar-light bg-light shadow-sm p-3 mb-5"> <a class="navbar-brand" th:href="@{/foos/}">Spring OAuth Client Thymeleaf - 2</a> </nav> <div class="container"> <label>Welcome ! </label> <br /> <a th:href="@{/foos/}" class="btn btn-primary">Login</a> </div> </body> </html> ```
/content/code_sandbox/oauth-sso/sso-client-app-2/src/main/resources/templates/index.html
html
2016-03-02T09:04:07
2024-08-06T03:02:12
spring-security-oauth
Baeldung/spring-security-oauth
1,982
171
```html <!DOCTYPE html> <html lang="en"> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <title>Spring OAuth Client Thymeleaf - 2</title> <link rel="stylesheet" href="path_to_url" /> </head> <body> <nav class="navbar navbar-expand-lg navbar-light bg-light shadow-sm p-3 mb-5"> <a class="navbar-brand" th:href="@{/foos/}">Spring OAuth Client Thymeleaf -2</a> <ul class="navbar-nav ml-auto"> <li class="navbar-text">Hi, <span sec:authentication="name">preferred_username</span>&nbsp;&nbsp;&nbsp; </li> </ul> </nav> <div class="container"> <h1>All Foos:</h1> <table class="table table-bordered table-striped"> <thead> <tr> <td>ID</td> <td>Name</td> <!-- <td>Creation Date</td>--> </tr> </thead> <tbody> <tr th:if="${foos.empty}"> <td colspan="4">No foos</td> </tr> <tr th:each="foo : ${foos}"> <td><span th:text="${foo.id}"> ID </span></td> <td><span th:text="${foo.name}"> Name </span></td> </tr> </tbody> </table> </div> </body> </html> ```
/content/code_sandbox/oauth-sso/sso-client-app-2/src/main/resources/templates/foos.html
html
2016-03-02T09:04:07
2024-08-06T03:02:12
spring-security-oauth
Baeldung/spring-security-oauth
1,982
350
```java package com.baeldung.client; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; @SpringBootApplication public class SSOClientApplication { public static void main(String[] args) { SpringApplication.run(SSOClientApplication.class, args); } } ```
/content/code_sandbox/oauth-sso/sso-client-app-2/src/main/java/com/baeldung/client/SSOClientApplication.java
java
2016-03-02T09:04:07
2024-08-06T03:02:12
spring-security-oauth
Baeldung/spring-security-oauth
1,982
54
```java package com.baeldung.client.spring; import org.springframework.context.annotation.Bean; import org.springframework.security.config.annotation.web.builders.HttpSecurity; import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity; import org.springframework.security.oauth2.client.registration.ClientRegistrationRepository; import org.springframework.security.oauth2.client.web.OAuth2AuthorizedClientRepository; import org.springframework.security.oauth2.client.web.reactive.function.client.ServletOAuth2AuthorizedClientExchangeFilterFunction; import org.springframework.security.web.SecurityFilterChain; import org.springframework.web.reactive.function.client.WebClient; @EnableWebSecurity public class UiSecurityConfig { @Bean public SecurityFilterChain filterChain(HttpSecurity http) throws Exception { http.authorizeRequests() .antMatchers("/") .permitAll() .anyRequest() .authenticated() .and() .oauth2Login(); return http.build(); } @Bean WebClient webClient(ClientRegistrationRepository clientRegistrationRepository, OAuth2AuthorizedClientRepository authorizedClientRepository) { ServletOAuth2AuthorizedClientExchangeFilterFunction oauth2 = new ServletOAuth2AuthorizedClientExchangeFilterFunction(clientRegistrationRepository, authorizedClientRepository); oauth2.setDefaultOAuth2AuthorizedClient(true); return WebClient.builder() .apply(oauth2.oauth2Configuration()) .build(); } } ```
/content/code_sandbox/oauth-sso/sso-client-app-2/src/main/java/com/baeldung/client/spring/UiSecurityConfig.java
java
2016-03-02T09:04:07
2024-08-06T03:02:12
spring-security-oauth
Baeldung/spring-security-oauth
1,982
263
```java package com.baeldung.client.web.model; public class FooModel { private Long id; private String name; public FooModel() { } public FooModel(Long id, String name) { super(); this.id = id; this.name = name; } public Long getId() { return id; } public void setId(Long id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + ((id == null) ? 0 : id.hashCode()); result = prime * result + ((name == null) ? 0 : name.hashCode()); return result; } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; FooModel other = (FooModel) obj; if (id == null) { if (other.id != null) return false; } else if (!id.equals(other.id)) return false; if (name == null) { if (other.name != null) return false; } else if (!name.equals(other.name)) return false; return true; } @Override public String toString() { return "Foo [id=" + id + ", name=" + name + "]"; } } ```
/content/code_sandbox/oauth-sso/sso-client-app-2/src/main/java/com/baeldung/client/web/model/FooModel.java
java
2016-03-02T09:04:07
2024-08-06T03:02:12
spring-security-oauth
Baeldung/spring-security-oauth
1,982
348
```java package com.baeldung.client.web.controller; import java.util.List; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Value; import org.springframework.core.ParameterizedTypeReference; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.reactive.function.client.WebClient; import com.baeldung.client.web.model.FooModel; @Controller public class FooClientController { @Value("${resourceserver.api.url}") private String fooApiUrl; @Autowired private WebClient webClient; @GetMapping("/foos") public String getFoos(Model model) { List<FooModel> foos = this.webClient.get() .uri(fooApiUrl) .retrieve() .bodyToMono(new ParameterizedTypeReference<List<FooModel>>() { }) .block(); model.addAttribute("foos", foos); return "foos"; } } ```
/content/code_sandbox/oauth-sso/sso-client-app-2/src/main/java/com/baeldung/client/web/controller/FooClientController.java
java
2016-03-02T09:04:07
2024-08-06T03:02:12
spring-security-oauth
Baeldung/spring-security-oauth
1,982
200
```yaml spring: security: oauth2: client: registration: custom: client-id: ssoClient-1 client-secret: ssoClientSecret-1 scope: read,write,openid authorization-grant-type: authorization_code redirect-uri: path_to_url provider: custom: authorization-uri: path_to_url token-uri: path_to_url user-info-uri: path_to_url jwk-set-uri: path_to_url user-name-attribute: preferred_username thymeleaf: cache: false cache: type: NONE server: port: 8082 servlet: context-path: /ui-one logging: level: org.springframework: INFO resourceserver: api: url: path_to_url ```
/content/code_sandbox/oauth-sso/sso-client-app-1/src/main/resources/application.yml
yaml
2016-03-02T09:04:07
2024-08-06T03:02:12
spring-security-oauth
Baeldung/spring-security-oauth
1,982
184
```html <!DOCTYPE html> <html lang="en"> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <title>Spring OAuth Client Thymeleaf - 1</title> <link rel="stylesheet" href="path_to_url" /> </head> <body> <nav class="navbar navbar-expand-lg navbar-light bg-light shadow-sm p-3 mb-5"> <a class="navbar-brand" th:href="@{/foos/}">Spring OAuth Client Thymeleaf - 1</a> </nav> <div class="container"> <label>Welcome ! </label> <br /> <a th:href="@{/foos/}" class="btn btn-primary">Login</a> </div> </body> </html> ```
/content/code_sandbox/oauth-sso/sso-client-app-1/src/main/resources/templates/index.html
html
2016-03-02T09:04:07
2024-08-06T03:02:12
spring-security-oauth
Baeldung/spring-security-oauth
1,982
171
```java package com.baeldung.client.spring; import org.springframework.context.annotation.Bean; import org.springframework.security.config.annotation.web.builders.HttpSecurity; import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity; import org.springframework.security.oauth2.client.registration.ClientRegistrationRepository; import org.springframework.security.oauth2.client.web.OAuth2AuthorizedClientRepository; import org.springframework.security.oauth2.client.web.reactive.function.client.ServletOAuth2AuthorizedClientExchangeFilterFunction; import org.springframework.security.web.SecurityFilterChain; import org.springframework.web.reactive.function.client.WebClient; @EnableWebSecurity public class UiSecurityConfig { @Bean public SecurityFilterChain filterChain(HttpSecurity http) throws Exception { http.authorizeRequests() .antMatchers("/", "/login**") .permitAll() .anyRequest() .authenticated() .and() .oauth2Login(); return http.build(); } @Bean WebClient webClient(ClientRegistrationRepository clientRegistrationRepository, OAuth2AuthorizedClientRepository authorizedClientRepository) { ServletOAuth2AuthorizedClientExchangeFilterFunction oauth2 = new ServletOAuth2AuthorizedClientExchangeFilterFunction(clientRegistrationRepository, authorizedClientRepository); oauth2.setDefaultOAuth2AuthorizedClient(true); return WebClient.builder() .apply(oauth2.oauth2Configuration()) .build(); } } ```
/content/code_sandbox/oauth-sso/sso-client-app-1/src/main/java/com/baeldung/client/spring/UiSecurityConfig.java
java
2016-03-02T09:04:07
2024-08-06T03:02:12
spring-security-oauth
Baeldung/spring-security-oauth
1,982
267
```html <!DOCTYPE html> <html lang="en"> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <title>Spring OAuth Client Thymeleaf - 1</title> <link rel="stylesheet" href="path_to_url" /> </head> <body> <nav class="navbar navbar-expand-lg navbar-light bg-light shadow-sm p-3 mb-5"> <a class="navbar-brand" th:href="@{/foos/}">Spring OAuth Client Thymeleaf -1</a> <ul class="navbar-nav ml-auto"> <li class="navbar-text">Hi, <span sec:authentication="name">preferred_username</span>&nbsp;&nbsp;&nbsp; </li> </ul> </nav> <div class="container"> <h1>All Foos:</h1> <table class="table table-bordered table-striped"> <thead> <tr> <td>ID</td> <td>Name</td> </tr> </thead> <tbody> <tr th:if="${foos.empty}"> <td colspan="4">No foos</td> </tr> <tr th:each="foo : ${foos}"> <td><span th:text="${foo.id}"> ID </span></td> <td><span th:text="${foo.name}"> Name </span></td> </tr> </tbody> </table> </div> </body> </html> ```
/content/code_sandbox/oauth-sso/sso-client-app-1/src/main/resources/templates/foos.html
html
2016-03-02T09:04:07
2024-08-06T03:02:12
spring-security-oauth
Baeldung/spring-security-oauth
1,982
338
```java package com.baeldung.client.web.controller; import java.util.List; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Value; import org.springframework.core.ParameterizedTypeReference; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.reactive.function.client.WebClient; import com.baeldung.client.web.model.FooModel; @Controller public class FooClientController { @Value("${resourceserver.api.url}") private String fooApiUrl; @Autowired private WebClient webClient; @GetMapping("/foos") public String getFoos(Model model) { List<FooModel> foos = this.webClient.get() .uri(fooApiUrl) .retrieve() .bodyToMono(new ParameterizedTypeReference<List<FooModel>>() { }) .block(); model.addAttribute("foos", foos); return "foos"; } } ```
/content/code_sandbox/oauth-sso/sso-client-app-1/src/main/java/com/baeldung/client/web/controller/FooClientController.java
java
2016-03-02T09:04:07
2024-08-06T03:02:12
spring-security-oauth
Baeldung/spring-security-oauth
1,982
200
```java package com.baeldung; import org.junit.Test; import org.springframework.boot.test.context.SpringBootTest; @SpringBootTest public class SpringContextIntegrationTest { @Test public void whenContextInitializes_thenNoExceptionsTriggered() throws Exception { } } ```
/content/code_sandbox/oauth-jws-jwk-legacy/oauth-resource-server-jws-jwk-legacy/src/test/java/com/baeldung/SpringContextIntegrationTest.java
java
2016-03-02T09:04:07
2024-08-06T03:02:12
spring-security-oauth
Baeldung/spring-security-oauth
1,982
52
```java package com.baeldung.web; import static org.hamcrest.Matchers.isA; import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; import java.util.HashMap; import java.util.Map; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.http.HttpHeaders; import org.springframework.test.context.junit4.SpringRunner; import org.springframework.test.web.servlet.MockMvc; import io.restassured.RestAssured; import io.restassured.response.Response; /** * This test requires: * * oauth-authorization-server-jws-jwk service running in the environment * */ @SpringBootTest @RunWith(SpringRunner.class) @AutoConfigureMockMvc public class FooControllerLiveTest { @Autowired private MockMvc mockMvc; private static final String TOKEN_URL = "path_to_url"; private static final String RESOURCE_ENDPOINT = "/foos/1"; @Test public void givenAccessToken_whenGetUserResource_thenSuccess() throws Exception { String accessToken = obtainAccessToken(); // Access resources using access token this.mockMvc.perform(get(RESOURCE_ENDPOINT).header(HttpHeaders.AUTHORIZATION, "Bearer " + accessToken)) .andExpect(status().isOk()) .andExpect(jsonPath("$.id").value(1L)) .andExpect(jsonPath("$.name", isA(String.class))); } private String obtainAccessToken() { // get access token Map<String, String> params = new HashMap<String, String>(); params.put("grant_type", "client_credentials"); params.put("scope", "read"); Response response = RestAssured.given() .auth() .basic("bael-client", "bael-secret") .formParams(params) .post(TOKEN_URL); return response.jsonPath() .getString("access_token"); } } ```
/content/code_sandbox/oauth-jws-jwk-legacy/oauth-resource-server-jws-jwk-legacy/src/test/java/com/baeldung/web/FooControllerLiveTest.java
java
2016-03-02T09:04:07
2024-08-06T03:02:12
spring-security-oauth
Baeldung/spring-security-oauth
1,982
421
```java package com.baeldung; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.security.oauth2.config.annotation.web.configuration.EnableResourceServer; @SpringBootApplication @EnableResourceServer public class ResourceServerApplication { public static void main(String[] args) { SpringApplication.run(ResourceServerApplication.class, args); } } ```
/content/code_sandbox/oauth-jws-jwk-legacy/oauth-resource-server-jws-jwk-legacy/src/main/java/com/baeldung/ResourceServerApplication.java
java
2016-03-02T09:04:07
2024-08-06T03:02:12
spring-security-oauth
Baeldung/spring-security-oauth
1,982
69
```java package com.baeldung.web.controller; import org.apache.commons.lang3.RandomStringUtils; import org.springframework.security.access.prepost.PreAuthorize; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; import com.baeldung.web.dto.Foo; @RestController @RequestMapping("/foos") public class FooController { @PreAuthorize("#oauth2.hasScope('read')") @GetMapping("/{id}") public Foo retrieveFoo(@PathVariable("id") Long id) { return new Foo(id, RandomStringUtils.randomAlphabetic(6)); } } ```
/content/code_sandbox/oauth-jws-jwk-legacy/oauth-resource-server-jws-jwk-legacy/src/main/java/com/baeldung/web/controller/FooController.java
java
2016-03-02T09:04:07
2024-08-06T03:02:12
spring-security-oauth
Baeldung/spring-security-oauth
1,982
132
```java package com.baeldung.web.dto; public class Foo { private long id; private String name; public Foo() { super(); } public Foo(final long id, final String name) { super(); this.id = id; this.name = name; } // public long getId() { return id; } public void setId(final long id) { this.id = id; } public String getName() { return name; } public void setName(final String name) { this.name = name; } } ```
/content/code_sandbox/oauth-jws-jwk-legacy/oauth-resource-server-jws-jwk-legacy/src/main/java/com/baeldung/web/dto/Foo.java
java
2016-03-02T09:04:07
2024-08-06T03:02:12
spring-security-oauth
Baeldung/spring-security-oauth
1,982
123
```java package com.baeldung.web; import static org.hamcrest.Matchers.is; import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.test.context.junit4.SpringRunner; import org.springframework.test.web.servlet.MockMvc; @RunWith(SpringRunner.class) @SpringBootTest @AutoConfigureMockMvc public class JwkSetRestControllerIntegrationTest { @Autowired private MockMvc mvc; @Test public void your_sha256_hashWKSetWithConfiguredKey() throws Exception { // @formatter:off this.mvc.perform(get("/.well-known/jwks.json")) .andExpect(status().isOk()) .andExpect(jsonPath("$.keys[0].kid", is("bael-key-id"))); // @formatter:on } } ```
/content/code_sandbox/oauth-jws-jwk-legacy/oauth-authorization-server-jws-jwk-legacy/src/test/java/com/baeldung/web/JwkSetRestControllerIntegrationTest.java
java
2016-03-02T09:04:07
2024-08-06T03:02:12
spring-security-oauth
Baeldung/spring-security-oauth
1,982
222
```java package com.baeldung; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; @SpringBootApplication public class AuthServerApp { public static void main(String[] args) { SpringApplication.run(AuthServerApp.class, args); } } ```
/content/code_sandbox/oauth-jws-jwk-legacy/oauth-authorization-server-jws-jwk-legacy/src/main/java/com/baeldung/AuthServerApp.java
java
2016-03-02T09:04:07
2024-08-06T03:02:12
spring-security-oauth
Baeldung/spring-security-oauth
1,982
51
```java package com.baeldung.config; import java.security.KeyPair; import java.security.interfaces.RSAPrivateKey; import java.util.HashMap; import java.util.Map; import org.springframework.security.jwt.JwtHelper; import org.springframework.security.jwt.crypto.sign.RsaSigner; import org.springframework.security.oauth2.common.OAuth2AccessToken; import org.springframework.security.oauth2.common.util.JsonParser; import org.springframework.security.oauth2.common.util.JsonParserFactory; import org.springframework.security.oauth2.provider.OAuth2Authentication; import org.springframework.security.oauth2.provider.token.store.JwtAccessTokenConverter; public class JwtCustomHeadersAccessTokenConverter extends JwtAccessTokenConverter { private Map<String, String> customHeaders = new HashMap<>(); private JsonParser objectMapper = JsonParserFactory.create(); final RsaSigner signer; public JwtCustomHeadersAccessTokenConverter(Map<String, String> customHeaders, KeyPair keyPair) { super(); super.setKeyPair(keyPair); this.signer = new RsaSigner((RSAPrivateKey) keyPair.getPrivate()); this.customHeaders = customHeaders; } @Override protected String encode(OAuth2AccessToken accessToken, OAuth2Authentication authentication) { String content; try { content = this.objectMapper.formatMap(getAccessTokenConverter().convertAccessToken(accessToken, authentication)); } catch (Exception ex) { throw new IllegalStateException("Cannot convert access token to JSON", ex); } String token = JwtHelper.encode(content, this.signer, this.customHeaders) .getEncoded(); return token; } } ```
/content/code_sandbox/oauth-jws-jwk-legacy/oauth-authorization-server-jws-jwk-legacy/src/main/java/com/baeldung/config/JwtCustomHeadersAccessTokenConverter.java
java
2016-03-02T09:04:07
2024-08-06T03:02:12
spring-security-oauth
Baeldung/spring-security-oauth
1,982
324
```java package com.baeldung.config; import java.security.KeyPair; import java.security.interfaces.RSAPublicKey; import java.util.Collections; import java.util.Map; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.core.io.ClassPathResource; import org.springframework.security.oauth2.config.annotation.web.configuration.EnableAuthorizationServer; import org.springframework.security.oauth2.provider.token.TokenStore; import org.springframework.security.oauth2.provider.token.store.JwtAccessTokenConverter; import org.springframework.security.oauth2.provider.token.store.JwtTokenStore; import org.springframework.security.oauth2.provider.token.store.KeyStoreKeyFactory; import com.nimbusds.jose.JWSAlgorithm; import com.nimbusds.jose.jwk.JWKSet; import com.nimbusds.jose.jwk.KeyUse; import com.nimbusds.jose.jwk.RSAKey; @Configuration @EnableAuthorizationServer public class JwkAuthorizationServerConfiguration { private static final String KEY_STORE_FILE = "bael-jwt.jks"; private static final String KEY_STORE_PASSWORD = "bael-pass"; private static final String KEY_ALIAS = "bael-oauth-jwt"; private static final String JWK_KID = "bael-key-id"; @Bean public TokenStore tokenStore(JwtAccessTokenConverter jwtAccessTokenConverter) { return new JwtTokenStore(jwtAccessTokenConverter); } @Bean public JwtAccessTokenConverter accessTokenConverter() { Map<String, String> customHeaders = Collections.singletonMap("kid", JWK_KID); return new JwtCustomHeadersAccessTokenConverter(customHeaders, keyPair()); } @Bean public KeyPair keyPair() { ClassPathResource ksFile = new ClassPathResource(KEY_STORE_FILE); KeyStoreKeyFactory ksFactory = new KeyStoreKeyFactory(ksFile, KEY_STORE_PASSWORD.toCharArray()); return ksFactory.getKeyPair(KEY_ALIAS); } @Bean public JWKSet jwkSet() { RSAKey.Builder builder = new RSAKey.Builder((RSAPublicKey) keyPair().getPublic()).keyUse(KeyUse.SIGNATURE) .algorithm(JWSAlgorithm.RS256) .keyID(JWK_KID); return new JWKSet(builder.build()); } } ```
/content/code_sandbox/oauth-jws-jwk-legacy/oauth-authorization-server-jws-jwk-legacy/src/main/java/com/baeldung/config/JwkAuthorizationServerConfiguration.java
java
2016-03-02T09:04:07
2024-08-06T03:02:12
spring-security-oauth
Baeldung/spring-security-oauth
1,982
466
```java package com.baeldung.web; import java.util.Map; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RestController; import com.nimbusds.jose.jwk.JWKSet; @RestController public class JwkSetRestController { @Autowired private JWKSet jwkSet; @GetMapping("/.well-known/jwks.json") public Map<String, Object> keys() { return this.jwkSet.toJSONObject(); } } ```
/content/code_sandbox/oauth-jws-jwk-legacy/oauth-authorization-server-jws-jwk-legacy/src/main/java/com/baeldung/web/JwkSetRestController.java
java
2016-03-02T09:04:07
2024-08-06T03:02:12
spring-security-oauth
Baeldung/spring-security-oauth
1,982
106
```java package com.baeldung.test; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.boot.test.context.SpringBootTest.WebEnvironment; import org.springframework.test.context.junit4.SpringRunner; import com.baeldung.config.UiApplication; @RunWith(SpringRunner.class) @SpringBootTest(classes = UiApplication.class, webEnvironment = WebEnvironment.RANDOM_PORT) public class UiIntegrationTest { @Test public void whenLoadApplication_thenSuccess() { } } ```
/content/code_sandbox/oauth-legacy/oauth-ui-password-angularjs-legacy/src/test/java/com/baeldung/test/UiIntegrationTest.java
java
2016-03-02T09:04:07
2024-08-06T03:02:12
spring-security-oauth
Baeldung/spring-security-oauth
1,982
100
```yaml server: port: 8084 zuul: routes: oauth: path: /oauth/** sensitiveHeaders: url: path_to_url Servlet30WrapperFilter: pre: disable:true ```
/content/code_sandbox/oauth-legacy/oauth-ui-password-angularjs-legacy/src/main/resources/application.yml
yaml
2016-03-02T09:04:07
2024-08-06T03:02:12
spring-security-oauth
Baeldung/spring-security-oauth
1,982
48
```html <!DOCTYPE html> <html lang="en"> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <title>Spring Security OAuth</title> <link rel="stylesheet" href="path_to_url"/> </head> <body ng-app="myApp" ng-controller="mainCtrl"> <div th:include="header"></div> <div class="container"> <h1 class="col-sm-12">Login</h1> <div class="col-sm-6"> <div class="col-sm-12"> <label class="col-sm-3">Username</label> <input class="form-control" type="text" ng-model="loginData.username"/> </div> <div class="col-sm-12"> <label class="col-sm-3">Password</label> <input class="form-control" type="password" ng-model="loginData.password"/> </div> <div class="col-sm-12"> <input type="checkbox" ng-model="loginData.remember" id="remember"/> <label for="remember">Remeber me</label> </div> <div class="col-sm-12"> <a class="btn btn-default" href="#" ng-click="login()">Login</a> </div> </div> </div> </body> </html> ```
/content/code_sandbox/oauth-legacy/oauth-ui-password-angularjs-legacy/src/main/resources/templates/login_remember.html
html
2016-03-02T09:04:07
2024-08-06T03:02:12
spring-security-oauth
Baeldung/spring-security-oauth
1,982
266
```html <!DOCTYPE html> <html lang="en"> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <title>Spring Security OAuth</title> <link rel="stylesheet" href="path_to_url"/> </head> <body ng-app="myApp" ng-controller="mainCtrl"> <div th:include="header"></div> <div class="container"> <h1 class="col-sm-12">Login</h1> <div class="col-sm-6"> <div class="col-sm-12"> <label class="col-sm-3">Username</label> <input class="form-control" type="text" ng-model="loginData.username"/> </div> <div class="col-sm-12"> <label class="col-sm-3">Password</label> <input class="form-control" type="password" ng-model="loginData.password"/> </div> <div class="col-sm-12"> <a class="btn btn-default" href="#" ng-click="login()">Login</a> </div> </div> </div> </body> </html> ```
/content/code_sandbox/oauth-legacy/oauth-ui-password-angularjs-legacy/src/main/resources/templates/login.html
html
2016-03-02T09:04:07
2024-08-06T03:02:12
spring-security-oauth
Baeldung/spring-security-oauth
1,982
225
```html <!DOCTYPE html> <html lang="en"> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <title>Spring Security OAuth</title> <link rel="stylesheet" href="path_to_url"/> </head> <body ng-app="myApp" ng-controller="mainCtrl"> <div th:include="header"></div> <div class="container"> <h1 class="col-sm-12">Foo Details</h1> <div class="col-sm-12"> <label class="col-sm-3">ID</label> <span>{{foo.id}}</span> </div> <div class="col-sm-12"> <label class="col-sm-3">Name</label> <span>{{foo.name}}</span> </div> <div class="col-sm-12"> <a class="btn btn-default" href="#" ng-click="getFoo()">New Foo</a> </div> <div class="col-sm-12"> <br/> <br/> <a class="btn btn-info" href="#" ng-click="refreshAccessToken()">Refresh Access Token</a> <br/> <br/> <a class="btn btn-info" href="#" ng-click="logout()" ng-if="isLoggedIn">Logout</a> </div> </div> </body> </html> ```
/content/code_sandbox/oauth-legacy/oauth-ui-password-angularjs-legacy/src/main/resources/templates/index.html
html
2016-03-02T09:04:07
2024-08-06T03:02:12
spring-security-oauth
Baeldung/spring-security-oauth
1,982
259
```html <div> <nav class="navbar navbar-default"> <div class="container-fluid"> <div class="navbar-header"> <a class="navbar-brand" th:href="@{/}">Spring Security OAuth</a> </div> <p class="navbar-text navbar-right">{{organization}} &nbsp; &nbsp; &nbsp;</p> </div><!-- /.container-fluid --> </nav> <script src="path_to_url"></script> <script src="path_to_url"></script> <script src="path_to_url"></script> <script src="path_to_url"></script> <script src="path_to_url"></script> <script type="text/javascript" src="path_to_url"></script> <script th:src="@{/resources/angular-utf8-base64.min.js}"></script> <script> /*<![CDATA[*/ var app = angular.module('myApp', ["ngResource","ngRoute","ngCookies","angular-jwt"]); app.controller('mainCtrl', function($scope,$resource,$http,$httpParamSerializer,$cookies,jwtHelper,$timeout) { $scope.foo = {id:1 , name:"sample foo"}; $scope.foos = $resource("path_to_url",{fooId:'@id'}); $scope.organiztion = ""; $scope.isLoggedIn = false; $scope.getFoo = function(){ $scope.foo = $scope.foos.get({fooId:$scope.foo.id}); } $scope.loginData = {grant_type:"password", username: "", password: "", client_id: "fooClientIdPassword"}; $scope.refreshData = {grant_type:"refresh_token"}; var isLoginPage = window.location.href.indexOf("login") != -1; if(isLoginPage){ console.log("is login page"); if($cookies.get("access_token")){ window.location.href = "index"; } }else{ if($cookies.get("access_token")){ console.log("there is access token"); $http.defaults.headers.common.Authorization= 'Bearer ' + $cookies.get("access_token"); getOrganization(); $scope.isLoggedIn = true; }else{ //obtainAccessToken($scope.refreshData); console.log("there is noooo access token"); $scope.isLoggedIn = false; window.location.href = "login"; } } $scope.login = function() { obtainAccessToken($scope.loginData); } $scope.refreshAccessToken = function(){ obtainAccessToken($scope.refreshData); } $scope.logout = function() { logout($scope.loginData); } if ($cookies.get("remember")=="yes"){ var validity = $cookies.get("validity"); if (validity >10) validity -= 10; $timeout( function(){;$scope.refreshAccessToken();}, validity * 1000); } function obtainAccessToken(params){ if (params.username != null){ if (params.remember != null){ $cookies.put("remember","yes"); } else { $cookies.remove("remember"); } } var req = { method: 'POST', url: "oauth/token", headers: {"Content-type": "application/x-www-form-urlencoded; charset=utf-8"}, data: $httpParamSerializer(params) } $http(req).then( function(data){ $http.defaults.headers.common.Authorization= 'Bearer ' + data.data.access_token; var expireDate = new Date (new Date().getTime() + (1000 * data.data.expires_in)); $cookies.put("access_token", data.data.access_token, {'expires': expireDate}); $cookies.put("validity", data.data.expires_in); window.location.href="index"; },function(){ console.log("error"); window.location.href = "login"; } ); } function getOrganization(){ var token = $cookies.get("access_token"); //JWT /* var payload = jwtHelper.decodeToken(token); console.log(payload); $scope.organization = payload.organization; */ //JDBC $http.get("path_to_url") .then(function(response) { console.log(response); $scope.organization = response.data.organization; }); } function logout(params) { var req = { method: 'DELETE', url: "oauth/token" } $http(req).then( function(data){ $cookies.remove("access_token"); $cookies.remove("validity"); $cookies.remove("remember"); window.location.href="login"; },function(){ console.log("error"); } ); } }); app.factory('rememberMeInterceptor', ['$q','$injector','$httpParamSerializer', function($q, $injector,$httpParamSerializer) { var interceptor = { responseError: function(response) { if (response.status == 401){ var $http = $injector.get('$http'); var $cookies = $injector.get('$cookies'); var deferred = $q.defer(); var refreshData = {grant_type:"refresh_token"}; var req = { method: 'POST', url: "oauth/token", headers: {"Content-type": "application/x-www-form-urlencoded; charset=utf-8"}, data: $httpParamSerializer(refreshData) } $http(req).then( function(data){ $http.defaults.headers.common.Authorization= 'Bearer ' + data.data.access_token; var expireDate = new Date (new Date().getTime() + (1000 * data.data.expires_in)); $cookies.put("access_token", data.data.access_token, {'expires': expireDate}); $cookies.put("validity", data.data.expires_in); window.location.href="index"; },function(){ console.log("error"); $cookies.remove("access_token"); window.location.href = "login"; } ); // make the backend call again and chain the request return deferred.promise.then(function() { return $http(response.config); }); } return $q.reject(response); } }; return interceptor; }]); app.config(['$httpProvider', function($httpProvider) { $httpProvider.interceptors.push('rememberMeInterceptor'); }]); /*]]>*/ </script> </div> ```
/content/code_sandbox/oauth-legacy/oauth-ui-password-angularjs-legacy/src/main/resources/templates/header.html
html
2016-03-02T09:04:07
2024-08-06T03:02:12
spring-security-oauth
Baeldung/spring-security-oauth
1,982
1,342
```javascript "use strict";angular.module("ab-base64",[]).constant("base64",function(){var a={alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",lookup:null,ie:/MSIE /.test(navigator.userAgent),ieo:/MSIE [67]/.test(navigator.userAgent),encode:function(b){var c,d,e,f,g=a.toUtf8(b),h=-1,i=g.length,j=[,,,];if(a.ie){for(c=[];++h<i;)d=g[h],e=g[++h],j[0]=d>>2,j[1]=(3&d)<<4|e>>4,isNaN(e)?j[2]=j[3]=64:(f=g[++h],j[2]=(15&e)<<2|f>>6,j[3]=isNaN(f)?64:63&f),c.push(a.alphabet.charAt(j[0]),a.alphabet.charAt(j[1]),a.alphabet.charAt(j[2]),a.alphabet.charAt(j[3]));return c.join("")}for(c="";++h<i;)d=g[h],e=g[++h],j[0]=d>>2,j[1]=(3&d)<<4|e>>4,isNaN(e)?j[2]=j[3]=64:(f=g[++h],j[2]=(15&e)<<2|f>>6,j[3]=isNaN(f)?64:63&f),c+=a.alphabet[j[0]]+a.alphabet[j[1]]+a.alphabet[j[2]]+a.alphabet[j[3]];return c},decode:function(b){if(b=b.replace(/\s/g,""),b.length%4)throw new Error("InvalidLengthError: decode failed: The string to be decoded is not the correct length for a base64 encoded string.");if(/[^A-Za-z0-9+\/=\s]/g.test(b))throw new Error("InvalidCharacterError: decode failed: The string contains characters invalid in a base64 encoded string.");var c,d=a.fromUtf8(b),e=0,f=d.length;if(a.ieo){for(c=[];f>e;)c.push(d[e]<128?String.fromCharCode(d[e++]):d[e]>191&&d[e]<224?String.fromCharCode((31&d[e++])<<6|63&d[e++]):String.fromCharCode((15&d[e++])<<12|(63&d[e++])<<6|63&d[e++]));return c.join("")}for(c="";f>e;)c+=String.fromCharCode(d[e]<128?d[e++]:d[e]>191&&d[e]<224?(31&d[e++])<<6|63&d[e++]:(15&d[e++])<<12|(63&d[e++])<<6|63&d[e++]);return c},toUtf8:function(a){var b,c=-1,d=a.length,e=[];if(/^[\x00-\x7f]*$/.test(a))for(;++c<d;)e.push(a.charCodeAt(c));else for(;++c<d;)b=a.charCodeAt(c),128>b?e.push(b):2048>b?e.push(b>>6|192,63&b|128):e.push(b>>12|224,b>>6&63|128,63&b|128);return e},fromUtf8:function(b){var c,d=-1,e=[],f=[,,,];if(!a.lookup){for(c=a.alphabet.length,a.lookup={};++d<c;)a.lookup[a.alphabet.charAt(d)]=d;d=-1}for(c=b.length;++d<c&&(f[0]=a.lookup[b.charAt(d)],f[1]=a.lookup[b.charAt(++d)],e.push(f[0]<<2|f[1]>>4),f[2]=a.lookup[b.charAt(++d)],64!==f[2])&&(e.push((15&f[1])<<4|f[2]>>2),f[3]=a.lookup[b.charAt(++d)],64!==f[3]);)e.push((3&f[2])<<6|f[3]);return e}},b={decode:function(b){b=b.replace(/-/g,"+").replace(/_/g,"/");var c=b.length%4;if(c){if(1===c)throw new Error("InvalidLengthError: Input base64url string is the wrong length to determine padding");b+=new Array(5-c).join("=")}return a.decode(b)},encode:function(b){var c=a.encode(b);return c.replace(/\+/g,"-").replace(/\//g,"_").split("=",1)[0]}};return{decode:a.decode,encode:a.encode,urldecode:b.decode,urlencode:b.encode}}()); ```
/content/code_sandbox/oauth-legacy/oauth-ui-password-angularjs-legacy/src/main/webapp/resources/angular-utf8-base64.min.js
javascript
2016-03-02T09:04:07
2024-08-06T03:02:12
spring-security-oauth
Baeldung/spring-security-oauth
1,982
986
```java package com.baeldung.config; import java.io.IOException; import java.io.InputStream; import java.util.Map; import javax.servlet.http.Cookie; import org.apache.commons.io.IOUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.stereotype.Component; import com.fasterxml.jackson.core.type.TypeReference; import com.fasterxml.jackson.databind.ObjectMapper; import com.netflix.zuul.ZuulFilter; import com.netflix.zuul.context.RequestContext; @Component public class CustomPostZuulFilter extends ZuulFilter { private final Logger logger = LoggerFactory.getLogger(this.getClass()); private final ObjectMapper mapper = new ObjectMapper(); @Override public Object run() { final RequestContext ctx = RequestContext.getCurrentContext(); logger.info("in zuul filter " + ctx.getRequest().getRequestURI()); final String requestURI = ctx.getRequest().getRequestURI(); final String requestMethod = ctx.getRequest().getMethod(); try { final InputStream is = ctx.getResponseDataStream(); String responseBody = IOUtils.toString(is, "UTF-8"); if (responseBody.contains("refresh_token")) { final Map<String, Object> responseMap = mapper.readValue(responseBody, new TypeReference<Map<String, Object>>() { }); final String refreshToken = responseMap.get("refresh_token").toString(); responseMap.remove("refresh_token"); responseBody = mapper.writeValueAsString(responseMap); final Cookie cookie = new Cookie("refreshToken", refreshToken); cookie.setHttpOnly(true); // cookie.setSecure(true); cookie.setPath(ctx.getRequest().getContextPath() + "/oauth/token"); cookie.setMaxAge(2592000); // 30 days ctx.getResponse().addCookie(cookie); logger.info("refresh token = " + refreshToken); } if (requestURI.contains("oauth/token") && requestMethod.equals("DELETE")) { final Cookie cookie = new Cookie("refreshToken", ""); cookie.setMaxAge(0); cookie.setPath(ctx.getRequest().getContextPath() + "/oauth/token"); ctx.getResponse().addCookie(cookie); } ctx.setResponseBody(responseBody); } catch (final IOException e) { logger.error("Error occured in zuul post filter", e); } return null; } @Override public boolean shouldFilter() { return true; } @Override public int filterOrder() { return 10; } @Override public String filterType() { return "post"; } } ```
/content/code_sandbox/oauth-legacy/oauth-ui-password-angularjs-legacy/src/main/java/com/baeldung/config/CustomPostZuulFilter.java
java
2016-03-02T09:04:07
2024-08-06T03:02:12
spring-security-oauth
Baeldung/spring-security-oauth
1,982
512
```java package com.baeldung.config; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.context.support.PropertySourcesPlaceholderConfigurer; import org.springframework.web.servlet.config.annotation.DefaultServletHandlerConfigurer; import org.springframework.web.servlet.config.annotation.EnableWebMvc; import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry; import org.springframework.web.servlet.config.annotation.ViewControllerRegistry; import org.springframework.web.servlet.config.annotation.WebMvcConfigurer; @Configuration @EnableWebMvc public class UiWebConfig implements WebMvcConfigurer { @Bean public static PropertySourcesPlaceholderConfigurer propertySourcesPlaceholderConfigurer() { return new PropertySourcesPlaceholderConfigurer(); } @Override public void configureDefaultServletHandling(final DefaultServletHandlerConfigurer configurer) { configurer.enable(); } @Override public void addViewControllers(final ViewControllerRegistry registry) { registry.addViewController("/").setViewName("forward:/index"); registry.addViewController("/index"); registry.addViewController("/login"); registry.addViewController("/login_remember"); } @Override public void addResourceHandlers(final ResourceHandlerRegistry registry) { registry.addResourceHandler("/resources/**").addResourceLocations("/resources/"); } } ```
/content/code_sandbox/oauth-legacy/oauth-ui-password-angularjs-legacy/src/main/java/com/baeldung/config/UiWebConfig.java
java
2016-03-02T09:04:07
2024-08-06T03:02:12
spring-security-oauth
Baeldung/spring-security-oauth
1,982
248
```java package com.baeldung.config; import java.util.HashMap; import java.util.Map; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletRequestWrapper; public class CustomHttpServletRequest extends HttpServletRequestWrapper { private final Map<String, String[]> additionalParams; private final HttpServletRequest request; public CustomHttpServletRequest(final HttpServletRequest request, final Map<String, String[]> additionalParams) { super(request); this.request = request; this.additionalParams = additionalParams; } @Override public Map<String, String[]> getParameterMap() { final Map<String, String[]> map = request.getParameterMap(); final Map<String, String[]> param = new HashMap<String, String[]>(); param.putAll(map); param.putAll(additionalParams); return param; } } ```
/content/code_sandbox/oauth-legacy/oauth-ui-password-angularjs-legacy/src/main/java/com/baeldung/config/CustomHttpServletRequest.java
java
2016-03-02T09:04:07
2024-08-06T03:02:12
spring-security-oauth
Baeldung/spring-security-oauth
1,982
160
```java package com.baeldung.config; import java.io.UnsupportedEncodingException; import java.util.Base64; import java.util.HashMap; import java.util.Map; import javax.servlet.http.Cookie; import javax.servlet.http.HttpServletRequest; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.stereotype.Component; import com.netflix.zuul.ZuulFilter; import com.netflix.zuul.context.RequestContext; @Component public class CustomPreZuulFilter extends ZuulFilter { private final Logger logger = LoggerFactory.getLogger(this.getClass()); @Override public Object run() { final RequestContext ctx = RequestContext.getCurrentContext(); logger.info("in zuul filter " + ctx.getRequest().getRequestURI()); byte[] encoded; try { encoded = Base64.getEncoder().encode("fooClientIdPassword:secret".getBytes("UTF-8")); ctx.addZuulRequestHeader("Authorization", "Basic " + new String(encoded)); logger.info("pre filter"); logger.info(ctx.getRequest().getHeader("Authorization")); final HttpServletRequest req = ctx.getRequest(); final String refreshToken = extractRefreshToken(req); if (refreshToken != null) { final Map<String, String[]> param = new HashMap<String, String[]>(); param.put("refresh_token", new String[] { refreshToken }); param.put("grant_type", new String[] { "refresh_token" }); ctx.setRequest(new CustomHttpServletRequest(req, param)); } } catch (final UnsupportedEncodingException e) { logger.error("Error occured in pre filter", e); } // return null; } private String extractRefreshToken(HttpServletRequest req) { final Cookie[] cookies = req.getCookies(); if (cookies != null) { for (int i = 0; i < cookies.length; i++) { if (cookies[i].getName().equalsIgnoreCase("refreshToken")) { return cookies[i].getValue(); } } } return null; } @Override public boolean shouldFilter() { return true; } @Override public int filterOrder() { return -2; } @Override public String filterType() { return "pre"; } } ```
/content/code_sandbox/oauth-legacy/oauth-ui-password-angularjs-legacy/src/main/java/com/baeldung/config/CustomPreZuulFilter.java
java
2016-03-02T09:04:07
2024-08-06T03:02:12
spring-security-oauth
Baeldung/spring-security-oauth
1,982
459
```java package com.baeldung.config; import org.apache.tomcat.util.http.Rfc6265CookieProcessor; import org.apache.tomcat.util.http.SameSiteCookies; import org.springframework.boot.web.embedded.tomcat.TomcatContextCustomizer; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.web.servlet.config.annotation.WebMvcConfigurer; @Configuration public class SameSiteConfig implements WebMvcConfigurer { @Bean public TomcatContextCustomizer sameSiteCookiesConfig() { return context -> { final Rfc6265CookieProcessor cookieProcessor = new Rfc6265CookieProcessor(); cookieProcessor.setSameSiteCookies(SameSiteCookies.STRICT.getValue()); context.setCookieProcessor(cookieProcessor); }; } } ```
/content/code_sandbox/oauth-legacy/oauth-ui-password-angularjs-legacy/src/main/java/com/baeldung/config/SameSiteConfig.java
java
2016-03-02T09:04:07
2024-08-06T03:02:12
spring-security-oauth
Baeldung/spring-security-oauth
1,982
156
```html <!doctype html> <html> <head> <meta charset="utf-8"> <title>OauthImplicit</title> <base href="/"> <meta name="viewport" content="width=device-width, initial-scale=1"> <link rel="stylesheet" href="path_to_url"/> </head> <body> <app-root>Loading...</app-root> </body> </html> ```
/content/code_sandbox/oauth-legacy/oauth-ui-implicit-angular-legacy/src/main/resources/src/index.html
html
2016-03-02T09:04:07
2024-08-06T03:02:12
spring-security-oauth
Baeldung/spring-security-oauth
1,982
84
```java package com.baeldung.test; import static org.junit.Assert.assertTrue; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.boot.test.context.SpringBootTest.WebEnvironment; import org.springframework.security.oauth2.common.exceptions.InvalidTokenException; import org.springframework.security.oauth2.provider.OAuth2Authentication; import org.springframework.security.oauth2.provider.token.store.JwtTokenStore; import org.springframework.test.context.junit4.SpringRunner; import com.baeldung.config.ResourceServerApplication; @RunWith(SpringRunner.class) @SpringBootTest(classes = ResourceServerApplication.class, webEnvironment = WebEnvironment.RANDOM_PORT) public class JwtClaimsVerifierIntegrationTest { @Autowired private JwtTokenStore tokenStore; @Test public void whenTokenDontContainIssuer_thenSuccess() { final String tokenValue = "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.your_sha256_hashyour_sha256_hashyour_sha256_hashInNjb3BlIjpbImZvbyIsInJlYWQiLCJ3cml0ZSJdfQ.1E5mMPk4zOnaI-P2AYSToobsh9wTNeP0PkCOGd4DZsg"; final OAuth2Authentication auth = tokenStore.readAuthentication(tokenValue); assertTrue(auth.isAuthenticated()); } @Test public void whenTokenContainValidIssuer_thenSuccess() { final String tokenValue = "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.your_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashYWQiLCJ3cml0ZSJdLCJpYXQiOjE1MDQ3MzcxNDR9.G3vVR314v5bKiMJow0wRE0ZOXSakoRLxBSM9_PZeMms"; final OAuth2Authentication auth = tokenStore.readAuthentication(tokenValue); assertTrue(auth.isAuthenticated()); } @Test(expected = InvalidTokenException.class) public void whenTokenContainInvalidIssuer_thenException() { final String tokenValue = "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.your_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashYWQiLCJ3cml0ZSJdLCJpYXQiOjE1MDQ3MzcwNTl9.60HxX5m0vpP6jfxpLPQWr_a5qMLk6owfknbYmBqb68g"; final OAuth2Authentication auth = tokenStore.readAuthentication(tokenValue); assertTrue(auth.isAuthenticated()); } @Test(expected = InvalidTokenException.class) public void whenTokenDontContainUsername_thenException() { final String tokenValue = "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.your_sha256_hashyour_sha256_hashyour_sha256_hashZCIsIndyaXRlIl0sImlhdCI6MTUwNDczNzE4MX0.SEX15_d49_YOMw1UAPvh9pnPBKnATJUY-wN8r9kSVxA"; final OAuth2Authentication auth = tokenStore.readAuthentication(tokenValue); assertTrue(auth.isAuthenticated()); } @Test(expected = InvalidTokenException.class) public void whenTokenContainEmptyUsername_thenException() { final String tokenValue = "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.your_sha256_hashyour_sha256_hashyour_sha256_hashcGUiOlsiZm9vIiwicmVhZCIsIndyaXRlIl0sImlhdCI6MTUwNDczNzMyMX0.MM1RkBy90rTaDkCGGP1j9mKfSNcoRcHEa8WLC7-zR6A"; final OAuth2Authentication auth = tokenStore.readAuthentication(tokenValue); assertTrue(auth.isAuthenticated()); } } ```
/content/code_sandbox/oauth-legacy/oauth-resource-server-legacy-2/src/test/java/com/baeldung/test/JwtClaimsVerifierIntegrationTest.java
java
2016-03-02T09:04:07
2024-08-06T03:02:12
spring-security-oauth
Baeldung/spring-security-oauth
1,982
896
```java package com.baeldung.test; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.boot.test.context.SpringBootTest.WebEnvironment; import org.springframework.test.context.junit4.SpringRunner; import com.baeldung.config.ResourceServerApplication; @RunWith(SpringRunner.class) @SpringBootTest(classes = ResourceServerApplication.class, webEnvironment = WebEnvironment.RANDOM_PORT) public class ResourceServerIntegrationTest { @Test public void whenLoadApplication_thenSuccess() { } } ```
/content/code_sandbox/oauth-legacy/oauth-resource-server-legacy-2/src/test/java/com/baeldung/test/ResourceServerIntegrationTest.java
java
2016-03-02T09:04:07
2024-08-06T03:02:12
spring-security-oauth
Baeldung/spring-security-oauth
1,982
103
```java package com.baeldung.test; import static org.junit.Assert.assertEquals; import io.restassured.RestAssured; import io.restassured.response.Response; import java.util.HashMap; import java.util.Map; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.boot.test.context.SpringBootTest.WebEnvironment; import org.springframework.http.HttpStatus; import org.springframework.test.context.junit4.SpringRunner; import com.baeldung.config.ResourceServerApplication; // Before running this live test make sure authorization server is running @RunWith(SpringRunner.class) @SpringBootTest(classes = ResourceServerApplication.class, webEnvironment = WebEnvironment.DEFINED_PORT) public class OAuth2SwaggerLiveTest { private static final String URL_PREFIX = "path_to_url"; private String tokenValue = null; @Before public void obtainAccessToken() { final Map<String, String> params = new HashMap<String, String>(); params.put("grant_type", "password"); params.put("client_id", "fooClientIdPassword"); params.put("username", "john"); params.put("password", "123"); final Response response = RestAssured.given().auth().preemptive().basic("fooClientIdPassword", "secret").and().with().params(params).when().post("path_to_url"); tokenValue = response.jsonPath().getString("access_token"); } @Test public void whenVerifySwaggerDocIsWorking_thenOK() { Response response = RestAssured.get(URL_PREFIX + "/v2/api-docs"); assertEquals(HttpStatus.UNAUTHORIZED.value(), response.getStatusCode()); response = RestAssured.given().header("Authorization", "Bearer " + tokenValue).get(URL_PREFIX + "/v2/api-docs"); assertEquals(HttpStatus.OK.value(), response.getStatusCode()); } @Test public void whenVerifySwaggerUIIsWorking_thenOK() { Response response = RestAssured.get(URL_PREFIX + "/swagger-ui.html"); assertEquals(HttpStatus.UNAUTHORIZED.value(), response.getStatusCode()); response = RestAssured.given().header("Authorization", "Bearer " + tokenValue).get(URL_PREFIX + "/swagger-ui.html"); assertEquals(HttpStatus.OK.value(), response.getStatusCode()); } } ```
/content/code_sandbox/oauth-legacy/oauth-resource-server-legacy-2/src/test/java/com/baeldung/test/OAuth2SwaggerLiveTest.java
java
2016-03-02T09:04:07
2024-08-06T03:02:12
spring-security-oauth
Baeldung/spring-security-oauth
1,982
460
```java package com.baeldung.config; import org.springframework.context.annotation.Configuration; import org.springframework.security.access.expression.method.MethodSecurityExpressionHandler; import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity; import org.springframework.security.config.annotation.method.configuration.GlobalMethodSecurityConfiguration; import org.springframework.security.oauth2.provider.expression.OAuth2MethodSecurityExpressionHandler; @Configuration @EnableGlobalMethodSecurity(prePostEnabled = true) public class MethodSecurityConfig extends GlobalMethodSecurityConfiguration { @Override protected MethodSecurityExpressionHandler createExpressionHandler() { return new OAuth2MethodSecurityExpressionHandler(); } } ```
/content/code_sandbox/oauth-legacy/oauth-resource-server-legacy-2/src/main/java/com/baeldung/config/MethodSecurityConfig.java
java
2016-03-02T09:04:07
2024-08-06T03:02:12
spring-security-oauth
Baeldung/spring-security-oauth
1,982
120
```java package com.baeldung.config; import java.util.Map; import org.springframework.security.oauth2.common.exceptions.InvalidTokenException; import org.springframework.security.oauth2.provider.token.store.JwtClaimsSetVerifier; public class CustomClaimVerifier implements JwtClaimsSetVerifier { @Override public void verify(Map<String, Object> claims) throws InvalidTokenException { final String username = (String) claims.get("user_name"); if ((username == null) || (username.length() == 0)) { throw new InvalidTokenException("user_name claim is empty"); } } } ```
/content/code_sandbox/oauth-legacy/oauth-resource-server-legacy-2/src/main/java/com/baeldung/config/CustomClaimVerifier.java
java
2016-03-02T09:04:07
2024-08-06T03:02:12
spring-security-oauth
Baeldung/spring-security-oauth
1,982
120
```java package com.baeldung.config; import java.io.IOException; import javax.servlet.Filter; import javax.servlet.FilterChain; import javax.servlet.FilterConfig; import javax.servlet.ServletException; import javax.servlet.ServletRequest; import javax.servlet.ServletResponse; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.springframework.core.Ordered; import org.springframework.core.annotation.Order; import org.springframework.http.HttpMethod; import org.springframework.stereotype.Component; @Component @Order(Ordered.HIGHEST_PRECEDENCE) public class CorsFilter implements Filter { @Override public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException { final HttpServletResponse response = (HttpServletResponse) res; response.setHeader("Access-Control-Allow-Origin", "*"); response.setHeader("Access-Control-Allow-Methods", "POST, PUT, GET, OPTIONS, DELETE"); response.setHeader("Access-Control-Allow-Headers", "Authorization, Content-Type"); response.setHeader("Access-Control-Max-Age", "3600"); if (HttpMethod.OPTIONS.name().equalsIgnoreCase(((HttpServletRequest) req).getMethod())) { response.setStatus(HttpServletResponse.SC_OK); } else { chain.doFilter(req, res); } } @Override public void destroy() { } @Override public void init(FilterConfig config) throws ServletException { } } ```
/content/code_sandbox/oauth-legacy/oauth-resource-server-legacy-2/src/main/java/com/baeldung/config/CorsFilter.java
java
2016-03-02T09:04:07
2024-08-06T03:02:12
spring-security-oauth
Baeldung/spring-security-oauth
1,982
278