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.springsociallogin; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; @SpringBootApplication public class SpringSocialLoginApplication { public static void main(String[] args) { SpringApplication.run(SpringSocialLoginApplication.class, args); } } ```
/content/code_sandbox/oauth-rest/oauth2-social-login/src/main/java/com/baeldung/springsociallogin/SpringSocialLoginApplication.java
java
2016-03-02T09:04:07
2024-08-06T03:02:12
spring-security-oauth
Baeldung/spring-security-oauth
1,982
58
```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-rest/oauth-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
261
```java package com.baeldung.client.web.controller; import static org.springframework.security.oauth2.client.web.reactive.function.client.ServerOAuth2AuthorizedClientExchangeFilterFunction.oauth2AuthorizedClient; 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.security.oauth2.client.OAuth2AuthorizedClient; import org.springframework.security.oauth2.client.annotation.RegisteredOAuth2AuthorizedClient; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.client.HttpServerErrorException; import org.springframework.web.reactive.function.client.WebClient; import com.baeldung.client.web.model.FooModel; @Controller public class FooClientController { @Value("${resourceserver.api.foo.url:path_to_url}") private String fooApiUrl; @Autowired private WebClient webClient; @GetMapping("/foos") public String getFoos(@RegisteredOAuth2AuthorizedClient("custom") OAuth2AuthorizedClient authorizedClient, Model model) { List<FooModel> foos = this.webClient.get().uri(fooApiUrl).attributes(oauth2AuthorizedClient(authorizedClient)) .retrieve().bodyToMono(new ParameterizedTypeReference<List<FooModel>>() { }).block(); model.addAttribute("foos", foos); return "foos"; } @GetMapping("/addfoo") public String addNewFoo(Model model) { model.addAttribute("foo", new FooModel(0L, "")); return "addfoo"; } @PostMapping("/foos") public String saveFoo(FooModel foo, Model model) { try { this.webClient.post().uri(fooApiUrl).bodyValue(foo).retrieve().bodyToMono(Void.class).block(); return "redirect:/foos"; } catch (final HttpServerErrorException e) { model.addAttribute("msg", e.getResponseBodyAsString()); return "addfoo"; } } } ```
/content/code_sandbox/oauth-rest/oauth-client-spring/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
418
```java package com.baeldung.resource; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; import java.util.HashMap; import java.util.Map; import org.junit.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 are running public class ImplicitFlowLiveTest { private final static String AUTH_SERVER = "path_to_url"; private final static String RESOURCE_SERVER = "path_to_url"; private final static String REDIRECT_URL = "path_to_url"; private final static String CLIENT_ID = "newClient"; private final static String USERNAME = "john@test.com"; private final static String PASSWORD = "123"; @Test public void givenUser_whenUseFooClient_thenOkForFooResourceOnly() { final String accessToken = obtainAccessToken(CLIENT_ID, USERNAME, PASSWORD); 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 obtainAccessToken(String clientId, String username, String password) { String authorizeUrl = AUTH_SERVER + "/auth"; Map<String, String> loginParams = new HashMap<String, String>(); loginParams.put("grant_type", "implicit"); loginParams.put("client_id", clientId); loginParams.put("response_type", "token"); loginParams.put("redirect_uri", REDIRECT_URL); loginParams.put("scope", "read write openid"); // 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 access token Map<String, String> tokenParams = new HashMap<String, String>(); tokenParams.put("username", username); tokenParams.put("password", password); tokenParams.put("client_id", clientId); tokenParams.put("redirect_uri", REDIRECT_URL); response = RestAssured.given().cookie("AUTH_SESSION_ID", cookieValue).formParams(tokenParams) .post(authUrlWithCode); final String location = response.getHeader(HttpHeaders.LOCATION); assertEquals(HttpStatus.FOUND.value(), response.getStatusCode()); final String accessToken = location.split("#|=|&")[4]; return accessToken; } } ```
/content/code_sandbox/oauth-rest/oauth-resource-server/src/test/java/com/baeldung/resource/ImplicitFlowLiveTest.java
java
2016-03-02T09:04:07
2024-08-06T03:02:12
spring-security-oauth
Baeldung/spring-security-oauth
1,982
555
```java package com.baeldung.resource; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; import java.util.HashMap; import java.util.Map; import org.junit.Test; import io.restassured.RestAssured; import io.restassured.response.Response; //Before running this live test make sure both authorization server and resource server are running public class PasswordFlowLiveTest { private final static String AUTH_SERVER = "path_to_url"; private final static String RESOURCE_SERVER = "path_to_url"; private final static String CLIENT_ID = "newClient"; private final static String CLIENT_SECRET = "newClientSecret"; private final static String USERNAME = "john@test.com"; private final static String PASSWORD = "123"; @Test public void givenUser_whenUseFooClient_thenOkForFooResourceOnly() { final String accessToken = obtainAccessToken(CLIENT_ID, USERNAME, PASSWORD); 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 obtainAccessToken(String clientId, String username, String password) { final Map<String, String> params = new HashMap<String, String>(); params.put("grant_type", "password"); params.put("client_id", clientId); params.put("username", username); params.put("password", password); params.put("scope", "read write openid"); final Response response = RestAssured.given().auth().preemptive().basic(clientId, CLIENT_SECRET).and() .with().params(params).when().post(AUTH_SERVER + "/token"); return response.jsonPath().getString("access_token"); } } ```
/content/code_sandbox/oauth-rest/oauth-resource-server/src/test/java/com/baeldung/resource/PasswordFlowLiveTest.java
java
2016-03-02T09:04:07
2024-08-06T03:02:12
spring-security-oauth
Baeldung/spring-security-oauth
1,982
370
```java package com.baeldung.resource; 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.resource.ResourceServerApp; @ExtendWith(SpringExtension.class) @SpringBootTest(classes = { ResourceServerApp.class }) public class ContextIntegrationTest { @Test public void whenLoadApplication_thenSuccess() { } } ```
/content/code_sandbox/oauth-rest/oauth-resource-server/src/test/java/com/baeldung/resource/ContextIntegrationTest.java
java
2016-03-02T09:04:07
2024-08-06T03:02:12
spring-security-oauth
Baeldung/spring-security-oauth
1,982
92
```sqlpl INSERT INTO Foo(id, name) VALUES (default, 'Foo 1'); INSERT INTO Foo(id, name) VALUES (default, 'Foo 2'); INSERT INTO Foo(id, name) VALUES (default, 'Foo 3'); ```
/content/code_sandbox/oauth-rest/oauth-resource-server/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
49
```java package com.baeldung.resource; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; import java.util.HashMap; import java.util.Map; import org.junit.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 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 = "newClient"; private final static String CLIENT_SECRET = "newClientSecret"; @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 openid"); // 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-rest/oauth-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
642
```yaml server: port: 8081 servlet: context-path: /resource-server ####### resource server configuration properties spring: jpa: defer-datasource-initialization: true security: oauth2: resourceserver: jwt: issuer-uri: path_to_url jwk-set-uri: path_to_url ```
/content/code_sandbox/oauth-rest/oauth-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
74
```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-rest/oauth-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
55
```java package com.baeldung.resource.persistence.repository; import org.springframework.data.repository.PagingAndSortingRepository; import com.baeldung.resource.persistence.model.Foo; public interface IFooRepository extends PagingAndSortingRepository<Foo, Long> { } ```
/content/code_sandbox/oauth-rest/oauth-resource-server/src/main/java/com/baeldung/resource/persistence/repository/IFooRepository.java
java
2016-03-02T09:04:07
2024-08-06T03:02:12
spring-security-oauth
Baeldung/spring-security-oauth
1,982
49
```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-rest/oauth-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
56
```java package com.baeldung.resource.persistence.model; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; @Entity public class Foo { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private Long id; private String name; protected Foo() { } public Foo(String name) { 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; 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; Foo other = (Foo) 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-rest/oauth-resource-server/src/main/java/com/baeldung/resource/persistence/model/Foo.java
java
2016-03-02T09:04:07
2024-08-06T03:02:12
spring-security-oauth
Baeldung/spring-security-oauth
1,982
372
```java package com.baeldung.resource.service.impl; import java.util.Optional; import org.springframework.stereotype.Service; import com.baeldung.resource.persistence.model.Foo; import com.baeldung.resource.persistence.repository.IFooRepository; import com.baeldung.resource.service.IFooService; @Service public class FooServiceImpl implements IFooService { private IFooRepository fooRepository; public FooServiceImpl(IFooRepository fooRepository) { this.fooRepository = fooRepository; } @Override public Optional<Foo> findById(Long id) { return fooRepository.findById(id); } @Override public Foo save(Foo foo) { return fooRepository.save(foo); } @Override public Iterable<Foo> findAll() { return fooRepository.findAll(); } } ```
/content/code_sandbox/oauth-rest/oauth-resource-server/src/main/java/com/baeldung/resource/service/impl/FooServiceImpl.java
java
2016-03-02T09:04:07
2024-08-06T03:02:12
spring-security-oauth
Baeldung/spring-security-oauth
1,982
163
```java package com.baeldung.resource.spring; 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 SecurityConfig { @Bean public SecurityFilterChain filterChain(HttpSecurity http) throws Exception { http.cors() .and() .authorizeRequests() .antMatchers(HttpMethod.GET, "/user/info", "/api/foos/**") .hasAuthority("SCOPE_read") .antMatchers(HttpMethod.POST, "/api/foos") .hasAuthority("SCOPE_write") .anyRequest() .authenticated() .and() .oauth2ResourceServer() .jwt(); return http.build(); } } ```
/content/code_sandbox/oauth-rest/oauth-resource-server/src/main/java/com/baeldung/resource/spring/SecurityConfig.java
java
2016-03-02T09:04:07
2024-08-06T03:02:12
spring-security-oauth
Baeldung/spring-security-oauth
1,982
172
```java package com.baeldung.resource.web.controller; import java.util.Collections; import java.util.Map; import org.springframework.security.core.annotation.AuthenticationPrincipal; import org.springframework.security.oauth2.jwt.Jwt; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RestController; @RestController public class UserInfoController { @GetMapping("/user/info") public Map<String, Object> getUserInfo(@AuthenticationPrincipal Jwt principal) { return Collections.singletonMap("user_name", principal.getClaimAsString("preferred_username")); } } ```
/content/code_sandbox/oauth-rest/oauth-resource-server/src/main/java/com/baeldung/resource/web/controller/UserInfoController.java
java
2016-03-02T09:04:07
2024-08-06T03:02:12
spring-security-oauth
Baeldung/spring-security-oauth
1,982
105
```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-rest/oauth-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
127
```java package com.baeldung.resource.web.controller; import java.util.ArrayList; import java.util.Collection; import java.util.List; import org.springframework.http.HttpStatus; import org.springframework.util.StringUtils; import org.springframework.web.bind.annotation.CrossOrigin; 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.PutMapping; 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 org.springframework.web.server.ResponseStatusException; import com.baeldung.resource.persistence.model.Foo; import com.baeldung.resource.service.IFooService; import com.baeldung.resource.web.dto.FooDto; @RestController @RequestMapping(value = "/api/foos") public class FooController { private IFooService fooService; public FooController(IFooService fooService) { this.fooService = fooService; } @CrossOrigin(origins = "path_to_url") @GetMapping(value = "/{id}") public FooDto findOne(@PathVariable Long id) { Foo entity = fooService.findById(id) .orElseThrow(() -> new ResponseStatusException(HttpStatus.NOT_FOUND)); return convertToDto(entity); } @ResponseStatus(HttpStatus.CREATED) @PostMapping public void create(@RequestBody FooDto newFoo) { Foo entity = convertToEntity(newFoo); this.fooService.save(entity); } @GetMapping public Collection<FooDto> findAll() { Iterable<Foo> foos = this.fooService.findAll(); List<FooDto> fooDtos = new ArrayList<>(); foos.forEach(p -> fooDtos.add(convertToDto(p))); return fooDtos; } @PutMapping("/{id}") public FooDto updateFoo(@PathVariable("id") Long id, @RequestBody FooDto updatedFoo) { Foo fooEntity = convertToEntity(updatedFoo); return this.convertToDto(this.fooService.save(fooEntity)); } protected FooDto convertToDto(Foo entity) { FooDto dto = new FooDto(entity.getId(), entity.getName()); return dto; } protected Foo convertToEntity(FooDto dto) { Foo foo = new Foo(dto.getName()); if (!StringUtils.isEmpty(dto.getId())) { foo.setId(dto.getId()); } return foo; } } ```
/content/code_sandbox/oauth-rest/oauth-resource-server/src/main/java/com/baeldung/resource/web/controller/FooController.java
java
2016-03-02T09:04:07
2024-08-06T03:02:12
spring-security-oauth
Baeldung/spring-security-oauth
1,982
500
```sqlpl create table if not exists users( username varchar(64) not null primary key, password varchar(64) not null, email varchar(128), firstName varchar(128) not null, lastName varchar(128) not null, birthDate DATE not null ); delete from users; insert into users(username,password,email, firstName, lastName,birthDate) values('user1','changeme','jean.premier@example.com', 'Jean', 'Premier', PARSEDATETIME('1970-01-01','yyyy-MM-dd')); insert into users(username,password,email, firstName, lastName,birthDate) values('user2','changeme','louis.second@example.com','Louis', 'Second', PARSEDATETIME('1970-01-01','yyyy-MM-dd')); insert into users(username,password,email, firstName, lastName,birthDate) values('user3','changeme','philippe.troisieme@example.com','Philippe', 'Troisime', PARSEDATETIME('1970-01-01','yyyy-MM-dd')); ```
/content/code_sandbox/oauth-rest/keycloak-custom-providers/src/test/resources/custom-database-data.sql
sqlpl
2016-03-02T09:04:07
2024-08-06T03:02:12
spring-security-oauth
Baeldung/spring-security-oauth
1,982
222
```yaml server: port: 8083 spring: datasource: username: sa url: jdbc:h2:mem:testdb keycloak: server: contextPath: /auth adminUser: username: admin password: admin realmImportFile: custom-provider-realm.json ```
/content/code_sandbox/oauth-rest/keycloak-custom-providers/src/test/resources/application-test.yml
yaml
2016-03-02T09:04:07
2024-08-06T03:02:12
spring-security-oauth
Baeldung/spring-security-oauth
1,982
69
```java /** * */ package com.baeldung.auth.provider.user; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.web.client.RestTemplate; /** * @author Philippe * */ @Configuration public class TestClientConfiguration { @Bean public RestTemplate restTemplate() { return new RestTemplate(); } } ```
/content/code_sandbox/oauth-rest/keycloak-custom-providers/src/test/java/com/baeldung/auth/provider/user/TestClientConfiguration.java
java
2016-03-02T09:04:07
2024-08-06T03:02:12
spring-security-oauth
Baeldung/spring-security-oauth
1,982
73
```java package com.baeldung.auth.provider.user; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertNotNull; import javax.sql.DataSource; import org.junit.jupiter.api.BeforeAll; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.jdbc.DataSourceBuilder; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.boot.test.context.SpringBootTest.WebEnvironment; import org.springframework.boot.test.web.server.LocalServerPort; import org.springframework.core.io.ClassPathResource; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.jdbc.datasource.init.ResourceDatabasePopulator; import org.springframework.test.context.ActiveProfiles; import org.springframework.test.context.junit.jupiter.SpringExtension; import org.springframework.web.client.RestTemplate; import com.baeldung.auth.AuthorizationServerApp; @ExtendWith(SpringExtension.class) @SpringBootTest(classes = { AuthorizationServerApp.class }, webEnvironment = WebEnvironment.DEFINED_PORT) @ActiveProfiles("test") public class ContextIntegrationTest { private static final Logger log = LoggerFactory.getLogger(ContextIntegrationTest.class); @LocalServerPort int serverPort; @Autowired private RestTemplate restTemplate; @BeforeAll public static void populateTestDatabase() throws Exception { log.info("Populating database..."); DataSource ds = DataSourceBuilder.create() .driverClassName("org.h2.Driver") .url("jdbc:h2:./target/customuser") .username("SA") .password("") .build(); ResourceDatabasePopulator populator = new ResourceDatabasePopulator(false, false, "UTF-8", new ClassPathResource("custom-database-data.sql")); populator.execute(ds); } @Test public void whenLoadApplication_thenSuccess() throws InterruptedException { log.info("Server port: {}", serverPort); String baseUrl = "path_to_url" + serverPort; ResponseEntity<String> response = restTemplate.getForEntity( baseUrl + "/auth" , String.class); assertNotNull(response); assertEquals(HttpStatus.OK, response.getStatusCode()); log.info("Keycloak test server available at {}/auth", baseUrl); log.info("To test a custom provider user login, go to {}/auth/realms/baeldung/account",baseUrl); Thread.sleep(15*60*1000); } } ```
/content/code_sandbox/oauth-rest/keycloak-custom-providers/src/test/java/com/baeldung/auth/provider/user/ContextIntegrationTest.java
java
2016-03-02T09:04:07
2024-08-06T03:02:12
spring-security-oauth
Baeldung/spring-security-oauth
1,982
510
```java package com.baeldung.auth.provider.mapper; import org.keycloak.models.ClientSessionContext; import org.keycloak.models.KeycloakSession; import org.keycloak.models.ProtocolMapperModel; import org.keycloak.models.UserSessionModel; import org.keycloak.protocol.oidc.mappers.*; import org.keycloak.provider.ProviderConfigProperty; import org.keycloak.representations.IDToken; import java.util.ArrayList; import java.util.List; public class CustomProtocolMapper extends AbstractOIDCProtocolMapper implements OIDCAccessTokenMapper, OIDCIDTokenMapper, UserInfoTokenMapper { public static final String PROVIDER_ID = "custom-protocol-mapper"; private static final List<ProviderConfigProperty> configProperties = new ArrayList<>(); static { OIDCAttributeMapperHelper.addTokenClaimNameConfig(configProperties); OIDCAttributeMapperHelper.addIncludeInTokensConfig(configProperties, CustomProtocolMapper.class); } @Override public String getDisplayCategory() { return "Token Mapper"; } @Override public String getDisplayType() { return "Custom Token Mapper"; } @Override public String getHelpText() { return "Adds a Baeldung text to the claim"; } @Override public List<ProviderConfigProperty> getConfigProperties() { return configProperties; } @Override public String getId() { return PROVIDER_ID; } @Override protected void setClaim(IDToken token, ProtocolMapperModel mappingModel, UserSessionModel userSession, KeycloakSession keycloakSession, ClientSessionContext clientSessionCtx) { OIDCAttributeMapperHelper.mapClaim(token, mappingModel, "Baeldung"); } } ```
/content/code_sandbox/oauth-rest/keycloak-custom-providers/src/main/java/com/baeldung/auth/provider/mapper/CustomProtocolMapper.java
java
2016-03-02T09:04:07
2024-08-06T03:02:12
spring-security-oauth
Baeldung/spring-security-oauth
1,982
356
```java package com.baeldung.auth.provider.user; public final class CustomUserStorageProviderConstants { public static final String CONFIG_KEY_JDBC_DRIVER = "jdbcDriver"; public static final String CONFIG_KEY_JDBC_URL = "jdbcUrl"; public static final String CONFIG_KEY_DB_USERNAME = "username"; public static final String CONFIG_KEY_DB_PASSWORD = "password"; public static final String CONFIG_KEY_VALIDATION_QUERY = "validationQuery"; } ```
/content/code_sandbox/oauth-rest/keycloak-custom-providers/src/main/java/com/baeldung/auth/provider/user/CustomUserStorageProviderConstants.java
java
2016-03-02T09:04:07
2024-08-06T03:02:12
spring-security-oauth
Baeldung/spring-security-oauth
1,982
91
```java package com.baeldung.auth.provider.user; import java.sql.Connection; import java.sql.DriverManager; import java.sql.SQLException; import org.keycloak.component.ComponentModel; import static com.baeldung.auth.provider.user.CustomUserStorageProviderConstants.*; public class DbUtil { public static Connection getConnection(ComponentModel config) throws SQLException{ String driverClass = config.get(CONFIG_KEY_JDBC_DRIVER); try { Class.forName(driverClass); } catch(ClassNotFoundException nfe) { throw new RuntimeException("Invalid JDBC driver: " + driverClass + ". Please check if your driver if properly installed"); } return DriverManager.getConnection(config.get(CONFIG_KEY_JDBC_URL), config.get(CONFIG_KEY_DB_USERNAME), config.get(CONFIG_KEY_DB_PASSWORD)); } } ```
/content/code_sandbox/oauth-rest/keycloak-custom-providers/src/main/java/com/baeldung/auth/provider/user/DbUtil.java
java
2016-03-02T09:04:07
2024-08-06T03:02:12
spring-security-oauth
Baeldung/spring-security-oauth
1,982
154
```java package com.baeldung.auth.provider.user; import java.util.Date; import java.util.List; import java.util.Map; import org.keycloak.common.util.MultivaluedHashMap; import org.keycloak.component.ComponentModel; import org.keycloak.credential.LegacyUserCredentialManager; import org.keycloak.models.KeycloakSession; import org.keycloak.models.RealmModel; import org.keycloak.models.SubjectCredentialManager; import org.keycloak.models.UserModel; import org.keycloak.storage.adapter.AbstractUserAdapter; class CustomUser extends AbstractUserAdapter { private final String username; private final String email; private final String firstName; private final String lastName; private final Date birthDate; private CustomUser(KeycloakSession session, RealmModel realm, ComponentModel storageProviderModel, String username, String email, String firstName, String lastName, Date birthDate ) { super(session, realm, storageProviderModel); this.username = username; this.email = email; this.firstName = firstName; this.lastName = lastName; this.birthDate = birthDate; } @Override public String getUsername() { return username; } @Override public String getFirstName() { return firstName; } @Override public String getLastName() { return lastName; } @Override public String getEmail() { return email; } public Date getBirthDate() { return birthDate; } @Override public Map<String, List<String>> getAttributes() { MultivaluedHashMap<String, String> attributes = new MultivaluedHashMap<>(); attributes.add(UserModel.USERNAME, getUsername()); attributes.add(UserModel.EMAIL,getEmail()); attributes.add(UserModel.FIRST_NAME,getFirstName()); attributes.add(UserModel.LAST_NAME,getLastName()); attributes.add("birthDate",getBirthDate().toString()); return attributes; } static class Builder { private final KeycloakSession session; private final RealmModel realm; private final ComponentModel storageProviderModel; private String username; private String email; private String firstName; private String lastName; private Date birthDate; Builder(KeycloakSession session, RealmModel realm, ComponentModel storageProviderModel,String username) { this.session = session; this.realm = realm; this.storageProviderModel = storageProviderModel; this.username = username; } CustomUser.Builder email(String email) { this.email = email; return this; } CustomUser.Builder firstName(String firstName) { this.firstName = firstName; return this; } CustomUser.Builder lastName(String lastName) { this.lastName = lastName; return this; } CustomUser.Builder birthDate(Date birthDate) { this.birthDate = birthDate; return this; } CustomUser build() { return new CustomUser( session, realm, storageProviderModel, username, email, firstName, lastName, birthDate); } } @Override public SubjectCredentialManager credentialManager() { return new LegacyUserCredentialManager(session, realm, this); } } ```
/content/code_sandbox/oauth-rest/keycloak-custom-providers/src/main/java/com/baeldung/auth/provider/user/CustomUser.java
java
2016-03-02T09:04:07
2024-08-06T03:02:12
spring-security-oauth
Baeldung/spring-security-oauth
1,982
675
```java package com.baeldung.auth.provider.user; import java.sql.Connection; import java.util.List; import org.keycloak.component.ComponentModel; import org.keycloak.component.ComponentValidationException; import org.keycloak.models.KeycloakSession; import org.keycloak.models.RealmModel; import org.keycloak.provider.ProviderConfigProperty; import org.keycloak.provider.ProviderConfigurationBuilder; import org.keycloak.storage.UserStorageProviderFactory; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import static com.baeldung.auth.provider.user.CustomUserStorageProviderConstants.*; public class CustomUserStorageProviderFactory implements UserStorageProviderFactory<CustomUserStorageProvider> { private static final Logger log = LoggerFactory.getLogger(CustomUserStorageProviderFactory.class); protected final List<ProviderConfigProperty> configMetadata; public CustomUserStorageProviderFactory() { log.info("[I24] CustomUserStorageProviderFactory created"); // Create config metadata configMetadata = ProviderConfigurationBuilder.create() .property() .name(CONFIG_KEY_JDBC_DRIVER) .label("JDBC Driver Class") .type(ProviderConfigProperty.STRING_TYPE) .defaultValue("org.h2.Driver") .helpText("Fully qualified class name of the JDBC driver") .add() .property() .name(CONFIG_KEY_JDBC_URL) .label("JDBC URL") .type(ProviderConfigProperty.STRING_TYPE) .defaultValue("jdbc:h2:mem:customdb") .helpText("JDBC URL used to connect to the user database") .add() .property() .name(CONFIG_KEY_DB_USERNAME) .label("Database User") .type(ProviderConfigProperty.STRING_TYPE) .helpText("Username used to connect to the database") .add() .property() .name(CONFIG_KEY_DB_PASSWORD) .label("Database Password") .type(ProviderConfigProperty.STRING_TYPE) .helpText("Password used to connect to the database") .secret(true) .add() .property() .name(CONFIG_KEY_VALIDATION_QUERY) .label("SQL Validation Query") .type(ProviderConfigProperty.STRING_TYPE) .helpText("SQL query used to validate a connection") .defaultValue("select 1") .add() .build(); } @Override public CustomUserStorageProvider create(KeycloakSession ksession, ComponentModel model) { log.info("[I63] creating new CustomUserStorageProvider"); return new CustomUserStorageProvider(ksession,model); } @Override public String getId() { log.info("[I69] getId()"); return "custom-user-provider"; } // Configuration support methods @Override public List<ProviderConfigProperty> getConfigProperties() { return configMetadata; } @Override public void validateConfiguration(KeycloakSession session, RealmModel realm, ComponentModel config) throws ComponentValidationException { try (Connection c = DbUtil.getConnection(config)) { log.info("[I84] Testing connection..." ); c.createStatement().execute(config.get(CONFIG_KEY_VALIDATION_QUERY)); log.info("[I92] Connection OK !" ); } catch(Exception ex) { log.warn("[W94] Unable to validate connection: ex={}", ex.getMessage()); throw new ComponentValidationException("Unable to validate database connection",ex); } } @Override public void onUpdate(KeycloakSession session, RealmModel realm, ComponentModel oldModel, ComponentModel newModel) { log.info("[I94] onUpdate()" ); } @Override public void onCreate(KeycloakSession session, RealmModel realm, ComponentModel model) { log.info("[I99] onCreate()" ); } } ```
/content/code_sandbox/oauth-rest/keycloak-custom-providers/src/main/java/com/baeldung/auth/provider/user/CustomUserStorageProviderFactory.java
java
2016-03-02T09:04:07
2024-08-06T03:02:12
spring-security-oauth
Baeldung/spring-security-oauth
1,982
787
```java package com.baeldung.test; import com.baeldung.config.UiApplication; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.boot.test.context.SpringBootTest.WebEnvironment; import org.springframework.test.context.junit.jupiter.SpringExtension; @ExtendWith(SpringExtension.class) @SpringBootTest(classes = UiApplication.class, webEnvironment = WebEnvironment.RANDOM_PORT) public class UiIntegrationTest { @Test void whenLoadApplication_thenSuccess() { } } ```
/content/code_sandbox/oauth-rest/oauth-ui-authorization-code-angular-zuul/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
107
```yaml server: port: 8089 zuul: routes: auth/code: path: /auth/code/** sensitiveHeaders: url: path_to_url auth/token: path: /auth/token/** sensitiveHeaders: url: path_to_url auth/refresh/revoke: path: /auth/refresh/revoke/** sensitiveHeaders: url: path_to_url auth/refresh: path: /auth/refresh/** sensitiveHeaders: url: path_to_url auth/redirect: path: /auth/redirect/** sensitiveHeaders: url: path_to_url auth/resources: path: /auth/resources/** sensitiveHeaders: url: path_to_url Servlet30WrapperFilter: pre: disable:true ```
/content/code_sandbox/oauth-rest/oauth-ui-authorization-code-angular-zuul/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
170
```java /** * */ package com.baeldung.auth.provider.user; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; import java.text.DateFormat; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.List; import java.util.Map; import java.util.stream.Stream; import org.keycloak.component.ComponentModel; import org.keycloak.credential.CredentialInput; import org.keycloak.credential.CredentialInputValidator; import org.keycloak.models.GroupModel; import org.keycloak.models.KeycloakSession; import org.keycloak.models.RealmModel; import org.keycloak.models.UserModel; import org.keycloak.models.credential.PasswordCredentialModel; import org.keycloak.storage.StorageId; import org.keycloak.storage.UserStorageProvider; import org.keycloak.storage.user.UserLookupProvider; import org.keycloak.storage.user.UserQueryProvider; import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class CustomUserStorageProvider implements UserStorageProvider, UserLookupProvider, CredentialInputValidator, UserQueryProvider { private static final Logger log = LoggerFactory.getLogger(CustomUserStorageProvider.class); private KeycloakSession ksession; private ComponentModel model; public CustomUserStorageProvider(KeycloakSession ksession, ComponentModel model) { this.ksession = ksession; this.model = model; } @Override public void close() { log.info("[I30] close()"); } @Override public UserModel getUserById(RealmModel realm, String id) { log.info("[I35] getUserById({})",id); StorageId sid = new StorageId(id); return getUserByUsername(realm, sid.getExternalId()); } @Override public UserModel getUserByUsername(RealmModel realm, String username) { log.info("[I41] getUserByUsername({})",username); try ( Connection c = DbUtil.getConnection(this.model)) { PreparedStatement st = c.prepareStatement("select username, firstName,lastName, email, birthDate from users where username = ?"); st.setString(1, username); st.execute(); ResultSet rs = st.getResultSet(); if ( rs.next()) { return mapUser(realm,rs); } else { return null; } } catch(SQLException ex) { throw new RuntimeException("Database error:" + ex.getMessage(),ex); } } @Override public UserModel getUserByEmail(RealmModel realm, String email) { log.info("[I48] getUserByEmail({})",email); try ( Connection c = DbUtil.getConnection(this.model)) { PreparedStatement st = c.prepareStatement("select username, firstName,lastName, email, birthDate from users where email = ?"); st.setString(1, email); st.execute(); ResultSet rs = st.getResultSet(); if ( rs.next()) { return mapUser(realm,rs); } else { return null; } } catch(SQLException ex) { throw new RuntimeException("Database error:" + ex.getMessage(),ex); } } @Override public boolean supportsCredentialType(String credentialType) { log.info("[I57] supportsCredentialType({})",credentialType); return PasswordCredentialModel.TYPE.endsWith(credentialType); } @Override public boolean isConfiguredFor(RealmModel realm, UserModel user, String credentialType) { log.info("[I57] isConfiguredFor(realm={},user={},credentialType={})",realm.getName(), user.getUsername(), credentialType); // In our case, password is the only type of credential, so we allways return 'true' if // this is the credentialType return supportsCredentialType(credentialType); } @Override public boolean isValid(RealmModel realm, UserModel user, CredentialInput credentialInput) { log.info("[I57] isValid(realm={},user={},credentialInput.type={})",realm.getName(), user.getUsername(), credentialInput.getType()); if( !this.supportsCredentialType(credentialInput.getType())) { return false; } StorageId sid = new StorageId(user.getId()); String username = sid.getExternalId(); try ( Connection c = DbUtil.getConnection(this.model)) { PreparedStatement st = c.prepareStatement("select password from users where username = ?"); st.setString(1, username); st.execute(); ResultSet rs = st.getResultSet(); if ( rs.next()) { String pwd = rs.getString(1); return pwd.equals(credentialInput.getChallengeResponse()); } else { return false; } } catch(SQLException ex) { throw new RuntimeException("Database error:" + ex.getMessage(),ex); } } // UserQueryProvider implementation @Override public int getUsersCount(RealmModel realm) { log.info("[I93] getUsersCount: realm={}", realm.getName() ); try ( Connection c = DbUtil.getConnection(this.model)) { Statement st = c.createStatement(); st.execute("select count(*) from users"); ResultSet rs = st.getResultSet(); rs.next(); return rs.getInt(1); } catch(SQLException ex) { throw new RuntimeException("Database error:" + ex.getMessage(),ex); } } @Override public Stream<UserModel> getGroupMembersStream(RealmModel realm, GroupModel group, Integer firstResult, Integer maxResults) { log.info("[I113] getUsers: realm={}", realm.getName()); try ( Connection c = DbUtil.getConnection(this.model)) { PreparedStatement st = c.prepareStatement("select username, firstName,lastName, email, birthDate from users order by username limit ? offset ?"); st.setInt(1, maxResults); st.setInt(2, firstResult); st.execute(); ResultSet rs = st.getResultSet(); List<UserModel> users = new ArrayList<>(); while(rs.next()) { users.add(mapUser(realm,rs)); } return users.stream(); } catch(SQLException ex) { throw new RuntimeException("Database error:" + ex.getMessage(),ex); } } @Override public Stream<UserModel> searchForUserStream(RealmModel realm, String search, Integer firstResult, Integer maxResults) { log.info("[I139] searchForUser: realm={}", realm.getName()); try (Connection c = DbUtil.getConnection(this.model)) { PreparedStatement st = c.prepareStatement("select username, firstName,lastName, email, birthDate from users where username like ? order by username limit ? offset ?"); st.setString(1, search); st.setInt(2, maxResults); st.setInt(3, firstResult); st.execute(); ResultSet rs = st.getResultSet(); List<UserModel> users = new ArrayList<>(); while (rs.next()) { users.add(mapUser(realm, rs)); } return users.stream(); } catch (SQLException ex) { throw new RuntimeException("Database error:" + ex.getMessage(), ex); } } @Override public Stream<UserModel> searchForUserStream(RealmModel realm, Map<String, String> params, Integer firstResult, Integer maxResults) { return getGroupMembersStream(realm, null, firstResult, maxResults); } @Override public Stream<UserModel> searchForUserByUserAttributeStream(RealmModel realm, String attrName, String attrValue) { return Stream.empty(); } //------------------- Implementation private UserModel mapUser(RealmModel realm, ResultSet rs) throws SQLException { DateFormat fmt = new SimpleDateFormat("yyyy-MM-dd"); CustomUser user = new CustomUser.Builder(ksession, realm, model, rs.getString("username")) .email(rs.getString("email")) .firstName(rs.getString("firstName")) .lastName(rs.getString("lastName")) .birthDate(rs.getDate("birthDate")) .build(); return user; } } ```
/content/code_sandbox/oauth-rest/keycloak-custom-providers/src/main/java/com/baeldung/auth/provider/user/CustomUserStorageProvider.java
java
2016-03-02T09:04:07
2024-08-06T03:02:12
spring-security-oauth
Baeldung/spring-security-oauth
1,982
1,661
```html <!doctype html> <html> <head> <meta charset="utf-8"> <title>Authorization Code with Zuul</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-rest/oauth-ui-authorization-code-angular-zuul/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
87
```java package com.baeldung.config; import java.io.InputStream; import java.util.List; 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(); try { Map<String, List<String>> params = ctx.getRequestQueryParams(); if (requestURI.contains("auth/redirect")) { final Cookie cookie = new Cookie("code", params.get("code").get(0)); cookie.setHttpOnly(true); cookie.setPath(ctx.getRequest().getContextPath() + "/auth/token"); cookie.setMaxAge(2592000); // 30 days ctx.getResponse().addCookie(cookie); } else if (requestURI.contains("auth/token") || requestURI.contains("auth/refresh")) { if (requestURI.contains("auth/refresh/revoke")) { final Cookie cookie = new Cookie("refreshToken", ""); cookie.setMaxAge(0); ctx.getResponse().addCookie(cookie); } else { 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.setPath(ctx.getRequest().getContextPath() + "/auth/refresh"); cookie.setMaxAge(2592000); // 30 days ctx.getResponse().addCookie(cookie); } ctx.setResponseBody(responseBody); } } } catch (Exception e) { logger.error("Error occured in zuul post filter", e); } return null; } @Override public boolean shouldFilter() { boolean shouldfilter = false; final RequestContext ctx = RequestContext.getCurrentContext(); String URI = ctx.getRequest().getRequestURI(); if (URI.contains("auth/redirect") || URI.contains("auth/token") || URI.contains("auth/refresh")) { shouldfilter = true; } return shouldfilter; } @Override public int filterOrder() { return 10; } @Override public String filterType() { return "post"; } } ```
/content/code_sandbox/oauth-rest/oauth-ui-authorization-code-angular-zuul/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
651
```java package com.baeldung.config; import java.io.IOException; import java.util.List; 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.cloud.netflix.zuul.filters.support.FilterConstants; import org.springframework.stereotype.Component; import com.google.common.collect.Lists; import com.google.common.collect.Maps; 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()); private final static String REDIRECT_URL = "path_to_url"; private final static String CLIENT_ID = "newClient"; private final static String CLIENT_SECRET = "newClientSecret"; @Override public Object run() { final RequestContext ctx = RequestContext.getCurrentContext(); logger.info("in zuul filter URI:" + ctx.getRequest().getRequestURI()); final HttpServletRequest req = ctx.getRequest(); String requestURI = req.getRequestURI(); if (requestURI.contains("auth/code")) { Map<String, List<String>> params = ctx.getRequestQueryParams(); if (params == null) { params = Maps.newHashMap(); } params.put("response_type", Lists.newArrayList(new String[] { "code" })); params.put("scope", Lists.newArrayList(new String[] { "read" })); params.put("client_id", Lists.newArrayList(new String[] { CLIENT_ID })); params.put("redirect_uri", Lists.newArrayList(new String[] { REDIRECT_URL })); ctx.setRequestQueryParams(params); } else if (requestURI.contains("auth/token") || requestURI.contains("auth/refresh")) { try { byte[] bytes; if (requestURI.contains("auth/refresh/revoke")) { String cookieValue = extractCookie(req, "refreshToken"); String formParams = createFormData(requestURI, cookieValue); bytes = formParams.getBytes("UTF-8"); } else { String cookieValue = requestURI.contains("token") ? extractCookie(req, "code") : extractCookie(req, "refreshToken"); String formParams = createFormData(requestURI, cookieValue); bytes = formParams.getBytes("UTF-8"); } ctx.setRequest(new CustomHttpServletRequest(req, bytes)); } catch (IOException e) { e.printStackTrace(); } } return null; } private String extractCookie(HttpServletRequest req, String name) { final Cookie[] cookies = req.getCookies(); if (cookies != null) { for (int i = 0; i < cookies.length; i++) { if (cookies[i].getName().equalsIgnoreCase(name)) { return cookies[i].getValue(); } } } return null; } private String createFormData(String requestURI, String cookieValue) { String formData = ""; if (requestURI.contains("token")) { formData = String.format("grant_type=%s&client_id=%s&client_secret=%s&redirect_uri=%s&code=%s", "authorization_code", CLIENT_ID, CLIENT_SECRET, REDIRECT_URL, cookieValue); } else if (requestURI.contains("refresh")) { if (requestURI.contains("revoke")) { formData = String.format("client_id=%s&client_secret=%s&refresh_token=%s", CLIENT_ID, CLIENT_SECRET, cookieValue); } else { formData = String.format("grant_type=%s&client_id=%s&client_secret=%s&refresh_token=%s", "refresh_token", CLIENT_ID, CLIENT_SECRET, cookieValue); } } return formData; } @Override public boolean shouldFilter() { boolean shouldfilter = false; final RequestContext ctx = RequestContext.getCurrentContext(); String URI = ctx.getRequest().getRequestURI(); if (URI.contains("auth/code") || URI.contains("auth/token") || URI.contains("auth/refresh")) { shouldfilter = true; } return shouldfilter; } @Override public int filterOrder() { return FilterConstants.PRE_DECORATION_FILTER_ORDER + 1; } @Override public String filterType() { return "pre"; } } ```
/content/code_sandbox/oauth-rest/oauth-ui-authorization-code-angular-zuul/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
906
```java package com.baeldung.config; import java.io.IOException; import javax.servlet.ServletInputStream; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletRequestWrapper; import com.netflix.zuul.http.ServletInputStreamWrapper; public class CustomHttpServletRequest extends HttpServletRequestWrapper { private final byte[] bytes; public CustomHttpServletRequest(final HttpServletRequest request, byte[] bytes) { super(request); this.bytes = bytes; } @Override public ServletInputStream getInputStream() throws IOException { return new ServletInputStreamWrapper(bytes); } @Override public int getContentLength() { return bytes.length; } @Override public long getContentLengthLong() { return bytes.length; } @Override public String getMethod() { return "POST"; } } ```
/content/code_sandbox/oauth-rest/oauth-ui-authorization-code-angular-zuul/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
158
```java package com.baeldung.config; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.boot.web.servlet.support.SpringBootServletInitializer; import org.springframework.cloud.netflix.zuul.EnableZuulProxy; @EnableZuulProxy @SpringBootApplication public class UiApplication extends SpringBootServletInitializer { public static void main(String[] args) { SpringApplication.run(UiApplication.class, args); } } ```
/content/code_sandbox/oauth-rest/oauth-ui-authorization-code-angular-zuul/src/main/java/com/baeldung/config/UiApplication.java
java
2016-03-02T09:04:07
2024-08-06T03:02:12
spring-security-oauth
Baeldung/spring-security-oauth
1,982
88
```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-rest/oauth-ui-authorization-code-angular-zuul/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
```yaml server: port: 8090 logging: level: root: INFO org.springframework.web: INFO org.springframework.security: INFO org.springframework.security.oauth2: INFO spring: security: oauth2: resourceserver: jwt: issuer-uri: path_to_url ```
/content/code_sandbox/oauth-authorization-server/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
66
```java package com.baeldung; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; @SpringBootApplication public class OAuth2ResourceServerApplication { public static void main(String[] args) { SpringApplication.run(OAuth2ResourceServerApplication.class, args); } } ```
/content/code_sandbox/oauth-authorization-server/resource-server/src/main/java/com/baeldung/OAuth2ResourceServerApplication.java
java
2016-03-02T09:04:07
2024-08-06T03:02:12
spring-security-oauth
Baeldung/spring-security-oauth
1,982
56
```java package com.baeldung.web; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RestController; @RestController public class ArticlesController { @GetMapping("/articles") public String[] getArticles() { return new String[]{"Article 1", "Article 2", "Article 3"}; } } ```
/content/code_sandbox/oauth-authorization-server/resource-server/src/main/java/com/baeldung/web/ArticlesController.java
java
2016-03-02T09:04:07
2024-08-06T03:02:12
spring-security-oauth
Baeldung/spring-security-oauth
1,982
67
```java package com.baeldung.config; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.security.config.Customizer; import org.springframework.security.config.annotation.web.builders.HttpSecurity; import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity; import org.springframework.security.web.SecurityFilterChain; @Configuration @EnableWebSecurity public class ResourceServerConfig { @Bean SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception { http.securityMatcher("/articles/**") .authorizeHttpRequests(authorize -> authorize.anyRequest() .hasAuthority("SCOPE_articles.read")) .oauth2ResourceServer(oauth2 -> oauth2.jwt(Customizer.withDefaults())); return http.build(); } } ```
/content/code_sandbox/oauth-authorization-server/resource-server/src/main/java/com/baeldung/config/ResourceServerConfig.java
java
2016-03-02T09:04:07
2024-08-06T03:02:12
spring-security-oauth
Baeldung/spring-security-oauth
1,982
149
```yaml server: port: 9000 logging: level: root: INFO org.springframework.web: INFO org.springframework.security: INFO org.springframework.security.oauth2: INFO spring: security: oauth2: authorizationserver: issuer: path_to_url client: articles-client: registration: client-id: articles-client client-secret: "{noop}secret" client-name: Articles Client client-authentication-methods: - client_secret_basic authorization-grant-types: - authorization_code - refresh_token redirect-uris: - path_to_url - path_to_url scopes: - openid - articles.read ```
/content/code_sandbox/oauth-authorization-server/spring-authorization-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
155
```java package com.baeldung; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; @SpringBootApplication public class OAuth2AuthorizationServerApplication { public static void main(String[] args) { SpringApplication.run(OAuth2AuthorizationServerApplication.class, args); } } ```
/content/code_sandbox/oauth-authorization-server/spring-authorization-server/src/main/java/com/baeldung/OAuth2AuthorizationServerApplication.java
java
2016-03-02T09:04:07
2024-08-06T03:02:12
spring-security-oauth
Baeldung/spring-security-oauth
1,982
56
```java package com.baeldung.config; import static org.springframework.security.config.Customizer.withDefaults; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.core.annotation.Order; import org.springframework.security.config.annotation.web.builders.HttpSecurity; import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity; import org.springframework.security.core.userdetails.User; import org.springframework.security.core.userdetails.UserDetails; import org.springframework.security.core.userdetails.UserDetailsService; import org.springframework.security.crypto.factory.PasswordEncoderFactories; import org.springframework.security.crypto.password.PasswordEncoder; import org.springframework.security.oauth2.server.authorization.config.annotation.web.configuration.OAuth2AuthorizationServerConfiguration; import org.springframework.security.oauth2.server.authorization.config.annotation.web.configurers.OAuth2AuthorizationServerConfigurer; import org.springframework.security.provisioning.InMemoryUserDetailsManager; import org.springframework.security.web.SecurityFilterChain; @Configuration @EnableWebSecurity public class DefaultSecurityConfig { @Bean @Order(1) SecurityFilterChain authorizationServerSecurityFilterChain(HttpSecurity http) throws Exception { OAuth2AuthorizationServerConfiguration.applyDefaultSecurity(http); http.getConfigurer(OAuth2AuthorizationServerConfigurer.class) .oidc(withDefaults()); // Enable OpenID Connect 1.0 return http.formLogin(withDefaults()).build(); } @Bean @Order(2) SecurityFilterChain defaultSecurityFilterChain(HttpSecurity http) throws Exception { http.authorizeHttpRequests(authorizeRequests -> authorizeRequests.anyRequest() .authenticated()) .formLogin(withDefaults()); return http.build(); } @Bean UserDetailsService users() { PasswordEncoder encoder = PasswordEncoderFactories.createDelegatingPasswordEncoder(); UserDetails user = User.builder() .username("admin") .password("password") .passwordEncoder(encoder::encode) .roles("USER") .build(); return new InMemoryUserDetailsManager(user); } } ```
/content/code_sandbox/oauth-authorization-server/spring-authorization-server/src/main/java/com/baeldung/config/DefaultSecurityConfig.java
java
2016-03-02T09:04:07
2024-08-06T03:02:12
spring-security-oauth
Baeldung/spring-security-oauth
1,982
394
```java package com.baeldung; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; @SpringBootApplication public class OAuth2ClientApplication { public static void main(String[] args) { SpringApplication.run(OAuth2ClientApplication.class, args); } } ```
/content/code_sandbox/oauth-authorization-server/client-server/src/main/java/com/baeldung/OAuth2ClientApplication.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: 8080 logging: level: root: INFO org.springframework.web: INFO org.springframework.security: INFO org.springframework.security.oauth2: INFO spring: security: oauth2: client: registration: articles-client-oidc: provider: spring client-id: articles-client client-secret: secret authorization-grant-type: authorization_code redirect-uri: "path_to_url{registrationId}" scope: openid client-name: articles-client-oidc articles-client-authorization-code: provider: spring client-id: articles-client client-secret: secret authorization-grant-type: authorization_code redirect-uri: "path_to_url" scope: articles.read client-name: articles-client-authorization-code provider: spring: issuer-uri: path_to_url ```
/content/code_sandbox/oauth-authorization-server/client-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
191
```java package com.baeldung.config; 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.web.SecurityFilterChain; import static org.springframework.security.config.Customizer.withDefaults; @EnableWebSecurity public class SecurityConfig { @Bean SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception { http .authorizeHttpRequests(authorizeRequests -> authorizeRequests.anyRequest().authenticated() ) .oauth2Login(oauth2Login -> oauth2Login.loginPage("/oauth2/authorization/articles-client-oidc")) .oauth2Client(withDefaults()); return http.build(); } } ```
/content/code_sandbox/oauth-authorization-server/client-server/src/main/java/com/baeldung/config/SecurityConfig.java
java
2016-03-02T09:04:07
2024-08-06T03:02:12
spring-security-oauth
Baeldung/spring-security-oauth
1,982
150
```java package com.baeldung.config; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.security.oauth2.client.OAuth2AuthorizedClientManager; import org.springframework.security.oauth2.client.OAuth2AuthorizedClientProvider; import org.springframework.security.oauth2.client.OAuth2AuthorizedClientProviderBuilder; import org.springframework.security.oauth2.client.registration.ClientRegistrationRepository; import org.springframework.security.oauth2.client.web.DefaultOAuth2AuthorizedClientManager; import org.springframework.security.oauth2.client.web.OAuth2AuthorizedClientRepository; import org.springframework.security.oauth2.client.web.reactive.function.client.ServletOAuth2AuthorizedClientExchangeFilterFunction; import org.springframework.web.reactive.function.client.WebClient; @Configuration public class WebClientConfig { @Bean WebClient webClient(OAuth2AuthorizedClientManager authorizedClientManager) { ServletOAuth2AuthorizedClientExchangeFilterFunction oauth2Client = new ServletOAuth2AuthorizedClientExchangeFilterFunction(authorizedClientManager); return WebClient.builder() .apply(oauth2Client.oauth2Configuration()) .build(); } @Bean OAuth2AuthorizedClientManager authorizedClientManager( ClientRegistrationRepository clientRegistrationRepository, OAuth2AuthorizedClientRepository authorizedClientRepository) { OAuth2AuthorizedClientProvider authorizedClientProvider = OAuth2AuthorizedClientProviderBuilder.builder() .authorizationCode() .refreshToken() .build(); DefaultOAuth2AuthorizedClientManager authorizedClientManager = new DefaultOAuth2AuthorizedClientManager( clientRegistrationRepository, authorizedClientRepository); authorizedClientManager.setAuthorizedClientProvider(authorizedClientProvider); return authorizedClientManager; } } ```
/content/code_sandbox/oauth-authorization-server/client-server/src/main/java/com/baeldung/config/WebClientConfig.java
java
2016-03-02T09:04:07
2024-08-06T03:02:12
spring-security-oauth
Baeldung/spring-security-oauth
1,982
331
```java package com.baeldung.web; import org.springframework.security.oauth2.client.OAuth2AuthorizedClient; import org.springframework.security.oauth2.client.annotation.RegisteredOAuth2AuthorizedClient; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RestController; import org.springframework.web.reactive.function.client.WebClient; import static org.springframework.security.oauth2.client.web.reactive.function.client.ServerOAuth2AuthorizedClientExchangeFilterFunction.oauth2AuthorizedClient; @RestController public class ArticlesController { public ArticlesController(WebClient webClient) { this.webClient = webClient; } private WebClient webClient; @GetMapping(value = "/articles") public String[] getArticles( @RegisteredOAuth2AuthorizedClient("articles-client-authorization-code") OAuth2AuthorizedClient authorizedClient ) { return this.webClient .get() .uri("path_to_url") .attributes(oauth2AuthorizedClient(authorizedClient)) .retrieve() .bodyToMono(String[].class) .block(); } } ```
/content/code_sandbox/oauth-authorization-server/client-server/src/main/java/com/baeldung/web/ArticlesController.java
java
2016-03-02T09:04:07
2024-08-06T03:02:12
spring-security-oauth
Baeldung/spring-security-oauth
1,982
211
```java package com.baeldung.jwt; 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.jwt.JWTAuthorizationServerApp; @ExtendWith(SpringExtension.class) @SpringBootTest(classes = { JWTAuthorizationServerApp.class }) public class ContextIntegrationTest { @Test public void whenLoadApplication_thenSuccess() { } } ```
/content/code_sandbox/oauth-jwt/jwt-auth-server/src/test/java/com/baeldung/jwt/ContextIntegrationTest.java
java
2016-03-02T09:04:07
2024-08-06T03:02:12
spring-security-oauth
Baeldung/spring-security-oauth
1,982
94
```java package com.baeldung.jwt; import io.restassured.RestAssured; import io.restassured.response.Response; import java.util.Base64; 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 static org.assertj.core.api.Assertions.assertThat; public class AuthorizationServerLiveTest { public static final String AUTHORIZE_CODE_URL = "path_to_url"; public static final String TOKEN_URL = "path_to_url"; public static final String INTROSPECT_URL = "path_to_url"; public static final String USER_INFO_URL = "path_to_url"; public static final String JWT_CLIENT_SECRET = "jwtClientSecret"; public static final String JWT_CLIENT = "jwtClient"; public static final String REDIRECT_URL = "path_to_url"; public static final String USERNAME = "john@test.com"; public static final String PASSWORD = "123"; public static final String OIDC_DISCOVERY_URL = "path_to_url"; @Test public void givenAuthorizationCodeGrant_whenObtainAccessToken_thenSuccess() { String accessToken = obtainTokens().accessToken; assertThat(accessToken).isNotBlank(); } @Test public void your_sha256_hashSuccess() { final String tokenUrl = "path_to_url"; String refreshToken = obtainTokens().refreshToken; assertThat(refreshToken).isNotBlank(); Map<String, String> params = new HashMap<>(); params.put("client_id", "jwtClient"); params.put("client_secret", "jwtClientSecret"); params.put("grant_type", "refresh_token"); params.put("refresh_token", refreshToken); Response response = RestAssured .given() .formParams(params) .post(tokenUrl); assertThat(response .jsonPath() .getString("access_token")).isNotBlank(); } @Test public void givenPasswordGrant_whenObtainAccessToken_thenSuccess() { Map<String, String> params = new HashMap<>(); params.put("client_id", JWT_CLIENT); params.put("client_secret", JWT_CLIENT_SECRET); params.put("grant_type", "password"); params.put("username", USERNAME); params.put("password", PASSWORD); Response response = RestAssured .given() .formParams(params) .post(TOKEN_URL); assertThat(response .jsonPath() .getString("access_token")).isNotBlank(); } @Test public void your_sha256_hashIsMatched(){ String accessToken = obtainTokens().accessToken; Response response = RestAssured .given() .header("Authorization", String.format("Bearer %s", accessToken)) .get(USER_INFO_URL); assertThat(response .jsonPath() .getString("preferred_username")).isEqualTo(USERNAME); } @Test public void givenAccessToken_whenIntrospect_thenTokenIsActive(){ String accessToken = obtainTokens().accessToken; Response response = RestAssured .given() .header("Authorization", String.format("Basic %s", new String(Base64.getEncoder().encode((JWT_CLIENT + ":" + JWT_CLIENT_SECRET).getBytes())))) .formParam("token", accessToken) .post(INTROSPECT_URL); assertThat(response .jsonPath() .getBoolean("active")).isTrue(); } @Test public void your_sha256_hashdpointIsAvailable() { Response response = RestAssured .given() .redirects() .follow(false) .get(OIDC_DISCOVERY_URL); assertThat(HttpStatus.OK.value()).isEqualTo(response.getStatusCode()); System.out.println(response.asString()); assertThat(response .jsonPath() .getMap("$.")).containsKeys("issuer", "authorization_endpoint", "token_endpoint", "userinfo_endpoint"); } private Tokens obtainTokens() { final String authorizeUrl = AUTHORIZE_CODE_URL + REDIRECT_URL; // obtain authentication url with custom codes Response response = RestAssured .given() .redirects() .follow(false) .get(authorizeUrl); 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", USERNAME, "password", PASSWORD, "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<>(); params.put("grant_type", "authorization_code"); params.put("code", code); params.put("client_id", "jwtClient"); params.put("redirect_uri", REDIRECT_URL); params.put("client_secret", "jwtClientSecret"); params.put("scope", "openid"); response = RestAssured .given() .formParams(params) .post(TOKEN_URL); return new Tokens(response .jsonPath() .getString("access_token"), response .jsonPath() .getString("refresh_token")); } private static class Tokens { private final String accessToken; private final String refreshToken; public Tokens(String accessToken, String refreshToken) { this.accessToken = accessToken; this.refreshToken = refreshToken; } } } ```
/content/code_sandbox/oauth-jwt/jwt-auth-server/src/test/java/com/baeldung/jwt/AuthorizationServerLiveTest.java
java
2016-03-02T09:04:07
2024-08-06T03:02:12
spring-security-oauth
Baeldung/spring-security-oauth
1,982
1,210
```yaml server: port: 8083 spring: datasource: username: sa url: jdbc:h2:mem:testdb;DB_CLOSE_ON_EXIT=FALSE keycloak: server: contextPath: /auth adminUser: username: bael-admin password: pass realmImportFile: baeldung-realm.json ```
/content/code_sandbox/oauth-jwt/jwt-auth-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
79
```freemarker <#import "template.ftl" as layout> <@layout.registrationLayout; section> <#if section = "header"> ${msg("registerTitle")} <#elseif section = "form"> <form id="kc-register-form" class="${properties.kcFormClass!}" action="${url.registrationAction}" method="post"> <div class="${properties.kcFormGroupClass!} ${messagesPerField.printIfExists('firstName',properties.kcFormGroupErrorClass!)}"> <div class="${properties.kcLabelWrapperClass!}"> <label for="firstName" class="${properties.kcLabelClass!}">${msg("firstName")}</label> </div> <div class="${properties.kcInputWrapperClass!}"> <input type="text" id="firstName" class="${properties.kcInputClass!}" name="firstName" value="${(register.formData.firstName!'')}" /> </div> </div> <div class="${properties.kcFormGroupClass!} ${messagesPerField.printIfExists('lastName',properties.kcFormGroupErrorClass!)}"> <div class="${properties.kcLabelWrapperClass!}"> <label for="lastName" class="${properties.kcLabelClass!}">${msg("lastName")}</label> </div> <div class="${properties.kcInputWrapperClass!}"> <input type="text" id="lastName" class="${properties.kcInputClass!}" name="lastName" value="${(register.formData.lastName!'')}" /> </div> </div> <!-- dob --> <div class="form-group"> <div class="${properties.kcLabelWrapperClass!}"> <label for="user.attributes.dob" class="${properties.kcLabelClass!}">Date of birth</label> </div> <div class="${properties.kcInputWrapperClass!}"> <input type="date" class="${properties.kcInputClass!}" id="user.attributes.dob" name="user.attributes.dob" value="${(register.formData['user.attributes.dob']!'')}"/> </div> </div> <!-- end of dob --> <div class="${properties.kcFormGroupClass!} ${messagesPerField.printIfExists('email',properties.kcFormGroupErrorClass!)}"> <div class="${properties.kcLabelWrapperClass!}"> <label for="email" class="${properties.kcLabelClass!}">${msg("email")}</label> </div> <div class="${properties.kcInputWrapperClass!}"> <input type="text" id="email" class="${properties.kcInputClass!}" name="email" value="${(register.formData.email!'')}" autocomplete="email" /> </div> </div> <#if !realm.registrationEmailAsUsername> <div class="${properties.kcFormGroupClass!} ${messagesPerField.printIfExists('username',properties.kcFormGroupErrorClass!)}"> <div class="${properties.kcLabelWrapperClass!}"> <label for="username" class="${properties.kcLabelClass!}">${msg("username")}</label> </div> <div class="${properties.kcInputWrapperClass!}"> <input type="text" id="username" class="${properties.kcInputClass!}" name="username" value="${(register.formData.username!'')}" autocomplete="username" /> </div> </div> </#if> <#if passwordRequired??> <div class="${properties.kcFormGroupClass!} ${messagesPerField.printIfExists('password',properties.kcFormGroupErrorClass!)}"> <div class="${properties.kcLabelWrapperClass!}"> <label for="password" class="${properties.kcLabelClass!}">${msg("password")}</label> </div> <div class="${properties.kcInputWrapperClass!}"> <input type="password" id="password" class="${properties.kcInputClass!}" name="password" autocomplete="new-password"/> </div> </div> <div class="${properties.kcFormGroupClass!} ${messagesPerField.printIfExists('password-confirm',properties.kcFormGroupErrorClass!)}"> <div class="${properties.kcLabelWrapperClass!}"> <label for="password-confirm" class="${properties.kcLabelClass!}">${msg("passwordConfirm")}</label> </div> <div class="${properties.kcInputWrapperClass!}"> <input type="password" id="password-confirm" class="${properties.kcInputClass!}" name="password-confirm" /> </div> </div> </#if> <#if recaptchaRequired??> <div class="form-group"> <div class="${properties.kcInputWrapperClass!}"> <div class="g-recaptcha" data-size="compact" data-sitekey="${recaptchaSiteKey}"></div> </div> </div> </#if> <div class="${properties.kcFormGroupClass!}"> <div id="kc-form-options" class="${properties.kcFormOptionsClass!}"> <div class="${properties.kcFormOptionsWrapperClass!}"> <span><a href="${url.loginUrl}">${kcSanitize(msg("backToLogin"))?no_esc}</a></span> </div> </div> <div id="kc-form-buttons" class="${properties.kcFormButtonsClass!}"> <input class="${properties.kcButtonClass!} ${properties.kcButtonPrimaryClass!} ${properties.kcButtonBlockClass!} ${properties.kcButtonLargeClass!}" type="submit" value="${msg("doRegister")}"/> </div> </div> </form> </#if> </@layout.registrationLayout> ```
/content/code_sandbox/oauth-jwt/jwt-auth-server/src/main/resources/themes/custom/login/register.ftl
freemarker
2016-03-02T09:04:07
2024-08-06T03:02:12
spring-security-oauth
Baeldung/spring-security-oauth
1,982
1,235
```freemarker <#macro registrationLayout bodyClass="" displayInfo=false displayMessage=true displayRequiredFields=false displayWide=false showAnotherWayIfPresent=true> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "path_to_url"> <html xmlns="path_to_url" class="${properties.kcHtmlClass!}"> <head> <meta charset="utf-8"> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" /> <meta name="robots" content="noindex, nofollow"> <#if properties.meta?has_content> <#list properties.meta?split(' ') as meta> <meta name="${meta?split('==')[0]}" content="${meta?split('==')[1]}"/> </#list> </#if> <title>${msg("loginTitle",(realm.displayName!''))}</title> <link rel="icon" href="${url.resourcesPath}/img/favicon.ico" /> <#if properties.styles?has_content> <#list properties.styles?split(' ') as style> <link href="${url.resourcesPath}/${style}" rel="stylesheet" /> </#list> </#if> <#if properties.scripts?has_content> <#list properties.scripts?split(' ') as script> <script src="${url.resourcesPath}/${script}" type="text/javascript"></script> </#list> </#if> <#if scripts??> <#list scripts as script> <script src="${script}" type="text/javascript"></script> </#list> </#if> </head> <body class="${properties.kcBodyClass!}"> <div class="${properties.kcLoginClass!}"> <div id="kc-header" class="${properties.kcHeaderClass!}"> <div id="kc-header-wrapper" class="${properties.kcHeaderWrapperClass!}">WELCOME TO BAELDUNG</div> </div> <div class="${properties.kcFormCardClass!} <#if displayWide>${properties.kcFormCardAccountClass!}</#if>"> <header class="${properties.kcFormHeaderClass!}"> <#if realm.internationalizationEnabled && locale.supported?size gt 1> <div id="kc-locale"> <div id="kc-locale-wrapper" class="${properties.kcLocaleWrapperClass!}"> <div class="kc-dropdown" id="kc-locale-dropdown"> <a href="#" id="kc-current-locale-link">${locale.current}</a> <ul> <#list locale.supported as l> <li class="kc-dropdown-item"><a href="${l.url}">${l.label}</a></li> </#list> </ul> </div> </div> </div> </#if> <#if !(auth?has_content && auth.showUsername() && !auth.showResetCredentials())> <#if displayRequiredFields> <div class="${properties.kcContentWrapperClass!}"> <div class="${properties.kcLabelWrapperClass!} subtitle"> <span class="subtitle"><span class="required">*</span> ${msg("requiredFields")}</span> </div> <div class="col-md-10"> <h1 id="kc-page-title"><#nested "header"></h1> </div> </div> <#else> <h1 id="kc-page-title"><#nested "header"></h1> </#if> <#else> <#if displayRequiredFields> <div class="${properties.kcContentWrapperClass!}"> <div class="${properties.kcLabelWrapperClass!} subtitle"> <span class="subtitle"><span class="required">*</span> ${msg("requiredFields")}</span> </div> <div class="col-md-10"> <#nested "show-username"> <div class="${properties.kcFormGroupClass!}"> <div id="kc-username"> <label id="kc-attempted-username">${auth.attemptedUsername}</label> <a id="reset-login" href="${url.loginRestartFlowUrl}"> <div class="kc-login-tooltip"> <i class="${properties.kcResetFlowIcon!}"></i> <span class="kc-tooltip-text">${msg("restartLoginTooltip")}</span> </div> </a> </div> </div> </div> </div> <#else> <#nested "show-username"> <div class="${properties.kcFormGroupClass!}"> <div id="kc-username"> <label id="kc-attempted-username">${auth.attemptedUsername}</label> <a id="reset-login" href="${url.loginRestartFlowUrl}"> <div class="kc-login-tooltip"> <i class="${properties.kcResetFlowIcon!}"></i> <span class="kc-tooltip-text">${msg("restartLoginTooltip")}</span> </div> </a> </div> </div> </#if> </#if> </header> <div id="kc-content"> <div id="kc-content-wrapper"> <#-- App-initiated actions should not see warning messages about the need to complete the action --> <#-- during login. --> <#if displayMessage && message?has_content && (message.type != 'warning' || !isAppInitiatedAction??)> <div class="alert alert-${message.type}"> <#if message.type = 'success'><span class="${properties.kcFeedbackSuccessIcon!}"></span></#if> <#if message.type = 'warning'><span class="${properties.kcFeedbackWarningIcon!}"></span></#if> <#if message.type = 'error'><span class="${properties.kcFeedbackErrorIcon!}"></span></#if> <#if message.type = 'info'><span class="${properties.kcFeedbackInfoIcon!}"></span></#if> <span class="kc-feedback-text">${kcSanitize(message.summary)?no_esc}</span> </div> </#if> <#nested "form"> <#if auth?has_content && auth.showTryAnotherWayLink() && showAnotherWayIfPresent> <form id="kc-select-try-another-way-form" action="${url.loginAction}" method="post" <#if displayWide>class="${properties.kcContentWrapperClass!}"</#if>> <div <#if displayWide>class="${properties.kcFormSocialAccountContentClass!} ${properties.kcFormSocialAccountClass!}"</#if>> <div class="${properties.kcFormGroupClass!}"> <input type="hidden" name="tryAnotherWay" value="on" /> <a href="#" id="try-another-way" onclick="document.forms['kc-select-try-another-way-form'].submit();return false;">${msg("doTryAnotherWay")}</a> </div> </div> </form> </#if> <#if displayInfo> <div id="kc-info" class="${properties.kcSignUpClass!}"> <div id="kc-info-wrapper" class="${properties.kcInfoAreaWrapperClass!}"> <#nested "info"> </div> </div> </#if> </div> </div> </div> </div> </body> </html> </#macro> ```
/content/code_sandbox/oauth-jwt/jwt-auth-server/src/main/resources/themes/custom/login/template.ftl
freemarker
2016-03-02T09:04:07
2024-08-06T03:02:12
spring-security-oauth
Baeldung/spring-security-oauth
1,982
1,630
```freemarker <!-- ~ JBoss, Home of Professional Open Source. ~ as indicated by the @author tags. See the copyright.txt file in the ~ distribution for a full listing of individual contributors. ~ ~ This is free software; you can redistribute it and/or modify it ~ published by the Free Software Foundation; either version 2.1 of ~ ~ This software is distributed in the hope that it will be useful, ~ but WITHOUT ANY WARRANTY; without even the implied warranty of ~ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU ~ ~ You should have received a copy of the GNU Lesser General Public ~ Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA ~ 02110-1301 USA, or see the FSF site: path_to_url --> <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> <html> <head> <title>Welcome to ${productNameFull}</title> <meta charset="utf-8"> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" /> <meta name="robots" content="noindex, nofollow"> <link rel="shortcut icon" href="welcome-content/favicon.ico" type="image/x-icon"> <#if properties.styles?has_content> <#list properties.styles?split(' ') as style> <link href="${resourcesPath}/${style}" rel="stylesheet" /> </#list> </#if> </head> <body> <div class="container-fluid"> <div class="row"> <div class="col-sm-10 col-sm-offset-1 col-md-8 col-md-offset-2 col-lg-8 col-lg-offset-2"> <div class="welcome-header"> <img src="${resourcesPath}/logo.png" alt="${productName}" border="0" /> <h1>Welcome to <strong>${productNameFull}</strong></h1> </div> <div class="row"> <div class="col-xs-12 col-sm-4"> <div class="card-pf h-l"> <#if successMessage?has_content> <p class="alert success">${successMessage}</p> <#elseif errorMessage?has_content> <p class="alert error">${errorMessage}</p> <h3><img src="welcome-content/user.png">Administration Console</h3> <#elseif bootstrap> <#if localUser> <h3><img src="welcome-content/user.png">Administration Console</h3> <p>Please create an initial admin user to get started.</p> <#else> <p class="welcome-message"> <img src="welcome-content/alert.png">You need local access to create the initial admin user. <br><br>Open <a href="path_to_url">path_to_url <br>or use the add-user-keycloak script. </p> </#if> </#if> <#if bootstrap && localUser> <form method="post" class="welcome-form"> <p> <label for="username">Username</label> <input id="username" name="username" /> </p> <p> <label for="password">Password</label> <input id="password" name="password" type="password" /> </p> <p> <label for="passwordConfirmation">Password confirmation</label> <input id="passwordConfirmation" name="passwordConfirmation" type="password" /> </p> <input id="stateChecker" name="stateChecker" type="hidden" value="${stateChecker}" /> <button id="create-button" type="submit" class="btn btn-primary">Create</button> </form> </#if> <div class="welcome-primary-link"> <h3><a href="${adminUrl}"><img src="welcome-content/user.png">Administration Console <i class="fa fa-angle-right link" aria-hidden="true"></i></a></h3> <div class="description"> Centrally manage all aspects of the ${productNameFull} server </div> </div> </div> </div> <div class="col-xs-12 col-sm-4"> <div class="card-pf h-l"> <h3><a href="${properties.documentationUrl}"><img class="doc-img" src="welcome-content/admin-console.png">Documentation <i class="fa fa-angle-right link" aria-hidden="true"></i></a></h3> <div class="description"> User Guide, Admin REST API and Javadocs </div> </div> </div> <div class="col-xs-12 col-sm-4"> <#if properties.displayCommunityLinks = "true"> <div class="card-pf h-m"> <h3><a href="path_to_url"><img src="welcome-content/keycloak-project.png">Keycloak Project <i class="fa fa-angle-right link" aria-hidden="true"></i></a></h3> </div> <div class="card-pf h-m"> <h3><a href="path_to_url"><img src="welcome-content/mail.png">Mailing List <i class="fa fa-angle-right link" aria-hidden="true"></i></a></h3> </div> <div class="card-pf h-m"> <h3><a href="path_to_url"><img src="welcome-content/bug.png">Report an issue <i class="fa fa-angle-right link" aria-hidden="true"></i></a></h3> </div> </#if> </div> </div> <div class='footer'> <#if properties.displayCommunityLinks = "true"> <a href="path_to_url"><img src="welcome-content/jboss_community.png" alt="JBoss and JBoss Community"></a> </#if> </div> </div> </div> </div> </body> </html> ```
/content/code_sandbox/oauth-jwt/jwt-auth-server/src/main/resources/themes/custom/welcome/index.ftl
freemarker
2016-03-02T09:04:07
2024-08-06T03:02:12
spring-security-oauth
Baeldung/spring-security-oauth
1,982
1,326
```css .login-pf body { background: #39a5dc; background-size: cover; height: 100%; } .alert-error { background-color: #ffffff; border-color: #cc0000; color: #333333; } #kc-locale ul { display: none; position: absolute; background-color: #fff; list-style: none; right: 0; top: 20px; min-width: 100px; padding: 2px 0; border: solid 1px #bbb; } #kc-locale:hover ul { display: block; margin: 0; } #kc-locale ul li a { display: block; padding: 5px 14px; color: #000 !important; text-decoration: none; line-height: 20px; } #kc-locale ul li a:hover { color: #4d5258; background-color: #d4edfa; } #kc-locale-dropdown a { color: #4d5258; background: 0 0; padding: 0 15px 0 0; font-weight: 300; } #kc-locale-dropdown a:hover { text-decoration: none; } a#kc-current-locale-link { display: block; padding: 0 5px; } /* a#kc-current-locale-link:hover { background-color: rgba(0,0,0,0.2); } */ a#kc-current-locale-link::after { content: "\2c5"; margin-left: 4px; } .login-pf .container { padding-top: 40px; } .login-pf a:hover { color: #0099d3; } #kc-logo { width: 100%; } #kc-logo-wrapper { background-image: url(../img/keycloak-logo-2.png); background-repeat: no-repeat; height: 63px; width: 300px; margin: 62px auto 0; } div.kc-logo-text { background-image: url(../img/keycloak-logo-text.png); background-repeat: no-repeat; height: 63px; width: 300px; margin: 0 auto; } div.kc-logo-text span { display: none; } #kc-header { color: #ededed; overflow: visible; white-space: nowrap; } #kc-header-wrapper { font-size: 29px; text-transform: uppercase; letter-spacing: 3px; line-height: 1.2em; padding: 62px 10px 20px; white-space: normal; } #kc-content { width: 100%; } #kc-attempted-username{ font-size: 20px; font-family:inherit; font-weight: normal; padding-right:10px; } #kc-username{ text-align: center; } #kc-webauthn-settings-form{ padding-top:8px; } /* #kc-content-wrapper { overflow-y: hidden; } */ #kc-info { padding-bottom: 200px; margin-bottom: -200px; } #kc-info-wrapper { font-size: 13px; } #kc-form-options span { display: block; } #kc-form-options .checkbox { margin-top: 0; color: #72767b; } #kc-terms-text { margin-bottom: 20px; } #kc-registration { margin-bottom: 15px; } /* TOTP */ .subtitle { text-align: right; margin-top: 30px; color: #909090; } .required { color: #CB2915; } ol#kc-totp-settings { margin: 0; padding-left: 20px; } ul#kc-totp-supported-apps { margin-bottom: 10px; } #kc-totp-secret-qr-code { max-width:150px; max-height:150px; } #kc-totp-secret-key { background-color: #fff; color: #333333; font-size: 16px; padding: 10px 0; } /* OAuth */ #kc-oauth h3 { margin-top: 0; } #kc-oauth ul { list-style: none; padding: 0; margin: 0; } #kc-oauth ul li { border-top: 1px solid rgba(255, 255, 255, 0.1); font-size: 12px; padding: 10px 0; } #kc-oauth ul li:first-of-type { border-top: 0; } #kc-oauth .kc-role { display: inline-block; width: 50%; } /* Code */ #kc-code textarea { width: 100%; height: 8em; } /* Social */ #kc-social-providers ul { padding: 0; } #kc-social-providers li { display: block; } #kc-social-providers li:first-of-type { margin-top: 0; } .kc-login-tooltip{ position:relative; display: inline-block; } .kc-login-tooltip .kc-tooltip-text{ top:-3px; left:160%; background-color: black; visibility: hidden; color: #fff; min-width:130px; text-align: center; border-radius: 2px; box-shadow:0 1px 8px rgba(0,0,0,0.6); padding: 5px; position: absolute; opacity:0; transition:opacity 0.5s; } /* Show tooltip */ .kc-login-tooltip:hover .kc-tooltip-text { visibility: visible; opacity:0.7; } /* Arrow for tooltip */ .kc-login-tooltip .kc-tooltip-text::after { content: " "; position: absolute; top: 15px; right: 100%; margin-top: -5px; border-width: 5px; border-style: solid; border-color: transparent black transparent transparent; } .zocial, a.zocial { width: 100%; font-weight: normal; font-size: 14px; text-shadow: none; border: 0; background: #f5f5f5; color: #72767b; border-radius: 0; white-space: normal; } .zocial:before { border-right: 0; margin-right: 0; } .zocial span:before { padding: 7px 10px; font-size: 14px; } .zocial:hover { background: #ededed !important; } .zocial.facebook, .zocial.github, .zocial.google, .zocial.microsoft, .zocial.stackoverflow, .zocial.linkedin, .zocial.twitter { background-image: none; border: 0; box-shadow: none; text-shadow: none; } /* Copy of zocial windows classes to be used for microsoft's social provider button */ .zocial.microsoft:before{ content: "\f15d"; } .zocial.stackoverflow:before{ color: inherit; } @media (min-width: 768px) { #kc-container-wrapper { position: absolute; width: 100%; } .login-pf .container { padding-right: 80px; } #kc-locale { position: relative; text-align: right; z-index: 9999; } } @media (max-width: 767px) { .login-pf body { background: white; } #kc-header { padding-left: 15px; padding-right: 15px; float: none; text-align: left; } #kc-header-wrapper { font-size: 16px; font-weight: bold; padding: 20px 60px 0 0; color: #72767b; letter-spacing: 0; } div.kc-logo-text { margin: 0; width: 150px; height: 32px; background-size: 100%; } #kc-form { float: none; } #kc-info-wrapper { border-top: 1px solid rgba(255, 255, 255, 0.1); margin-top: 15px; padding-top: 15px; padding-left: 0px; padding-right: 15px; } #kc-social-providers li { display: block; margin-right: 5px; } .login-pf .container { padding-top: 15px; padding-bottom: 15px; } #kc-locale { position: absolute; width: 200px; top: 20px; right: 20px; text-align: right; z-index: 9999; } #kc-logo-wrapper { background-size: 100px 21px; height: 21px; width: 100px; margin: 20px 0 0 20px; } } @media (min-height: 646px) { #kc-container-wrapper { bottom: 12%; } } @media (max-height: 645px) { #kc-container-wrapper { padding-top: 50px; top: 20%; } } .card-pf form.form-actions .btn { float: right; margin-left: 10px; } #kc-form-buttons { margin-top: 40px; } .login-pf-page .login-pf-brand { margin-top: 20px; max-width: 360px; width: 40%; } .card-pf { background: #fff; margin: 0 auto; padding: 0 20px; max-width: 500px; border-top: 0; box-shadow: 0 0 0; } /*tablet*/ @media (max-width: 840px) { .login-pf-page .card-pf{ max-width: none; margin-left: 20px; margin-right: 20px; padding: 20px 20px 30px 20px; } } @media (max-width: 767px) { .login-pf-page .card-pf{ max-width: none; margin-left: 0; margin-right: 0; padding-top: 0; } .card-pf.login-pf-accounts{ max-width: none; } } .login-pf-page .login-pf-signup { font-size: 15px; color: #72767b; } #kc-content-wrapper .row { margin-left: 0; margin-right: 0; } @media (min-width: 768px) { .login-pf-page .login-pf-social-section:first-of-type { padding-right: 39px; border-right: 1px solid #d1d1d1; margin-right: -1px; } .login-pf-page .login-pf-social-section:last-of-type { padding-left: 40px; } .login-pf-page .login-pf-social-section .login-pf-social-link:last-of-type { margin-bottom: 0; } } .login-pf-page .login-pf-social-link { margin-bottom: 25px; } .login-pf-page .login-pf-social-link a { padding: 2px 0; } .login-pf-page.login-pf-page-accounts { margin-left: auto; margin-right: auto; } .login-pf-page .btn-primary { margin-top: 0; } .login-pf-page .list-view-pf .list-group-item { border-bottom: 1px solid #ededed; } .login-pf-page .list-view-pf-description { width: 100%; } .login-pf-page .card-pf{ margin-bottom: 10px; } #kc-form-login div.form-group:last-of-type, #kc-register-form div.form-group:last-of-type, #kc-update-profile-form div.form-group:last-of-type { margin-bottom: 0px; } #kc-back { margin-top: 5px; } form#kc-select-back-form div.login-pf-social-section { padding-left: 0px; border-left: 0px; } ```
/content/code_sandbox/oauth-jwt/jwt-auth-server/src/main/resources/themes/custom/login/resources/css/login.css
css
2016-03-02T09:04:07
2024-08-06T03:02:12
spring-security-oauth
Baeldung/spring-security-oauth
1,982
2,725
```css body { background: #fff url(../geo.png); background-size: cover; } .welcome-header { margin-top: 10px; margin-bottom: 50px; margin-left: -10px; } .welcome-header img { width: 150px; margin-bottom: 40px; } .welcome-message { margin-top: 20px; } .h-l { min-height: 370px; padding: 10px 20px 10px; overflow: hidden; } .h-l h3 { margin-bottom: 10px; } .h-m { height: 110px; padding-top: 23px; } .card-pf img { width: 22px; margin-right: 10px; vertical-align: bottom; } img.doc-img { width: auto; height: 22px; } .link { font-size: 16px; vertical-align: baseline; margin-left: 5px; } h3 { font-weight: 550; } h3 a:link, h3 a:visited { color: #333; font-weight: 550; } h3 a:hover, h3 a:hover .link { text-decoration: none; color: #00659c; } .h-l h3 a img { height: 30px; width: auto; } .description { margin-top: 30px; } .card-pf { border-top: 1px solid rgba(3, 3, 3, 0.1); box-shadow: 0 1px 1px rgba(3, 3, 3, 0.275); } .welcome-form label, .welcome-form input { display: block; width: 100%; } .welcome-form label { color: #828486; font-weight: normal; margin-top: 18px; } .welcome-form input { border: 0; border-bottom: solid 1px #cbcbcb; } .welcome-form input:focus { border-bottom: solid 1px #5e99c6; outline-width: 0; } .welcome-form button { margin-top: 10px; } .error { color: #c00; border-color: #c00; padding: 5px 10px; } .success { color: #3f9c35; border-color: #3f9c35; padding: 5px 10px; } .welcome-form + .welcome-primary-link, .welcome-message + .welcome-primary-link { display: none; } .footer img { float: right; width: 150px; margin-top: 30px; } @media (max-width: 768px) { .welcome-header { margin-top: 10px; margin-bottom: 20px; } .welcome-header img { margin-bottom: 20px; } h3 { margin-top: 10px; } .h-l, .h-m { height: auto; min-height: auto; padding: 5px 10px; } .h-l img { display: inline; margin-bottom: auto; } .description { display: none; } .footer img { margin-top: 10px; } } ```
/content/code_sandbox/oauth-jwt/jwt-auth-server/src/main/resources/themes/custom/welcome/resources/css/welcome.css
css
2016-03-02T09:04:07
2024-08-06T03:02:12
spring-security-oauth
Baeldung/spring-security-oauth
1,982
682
```java package com.baeldung.jwt; 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.jwt.config.KeycloakServerProperties; @SpringBootApplication(exclude = LiquibaseAutoConfiguration.class) @EnableConfigurationProperties(KeycloakServerProperties.class) public class JWTAuthorizationServerApp { private static final Logger LOG = LoggerFactory.getLogger(JWTAuthorizationServerApp.class); public static void main(String[] args) throws Exception { SpringApplication.run(JWTAuthorizationServerApp.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-jwt/jwt-auth-server/src/main/java/com/baeldung/jwt/JWTAuthorizationServerApp.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.jwt.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 "jwt-auth-server"; } } ```
/content/code_sandbox/oauth-jwt/jwt-auth-server/src/main/java/com/baeldung/jwt/config/SimplePlatformProvider.java
java
2016-03-02T09:04:07
2024-08-06T03:02:12
spring-security-oauth
Baeldung/spring-security-oauth
1,982
291
```css html { height: 100%; } body { background-color: #F9F9F9; margin: 0; padding: 0; height: 100%; } header .navbar { margin-bottom: 0; min-height: inherit; } .header .container { position: relative; } .navbar-title { background-image: url('../img/baeldung.png'); height: 25px; background-repeat: no-repeat; width: 123px; margin: 3px 10px 5px; text-indent: -99999px; } .navbar-pf .navbar-utility { right: 20px; top: -34px; font-size: 12px; } .navbar-pf .navbar-utility > li > a { color: #fff !important; padding-bottom: 12px; padding-top: 11px; border-left: medium none; } .container { height: 100%; background-color: #fff; } .content-area { background-color: #fff; border-color: #CECECE; border-style: solid; border-width: 0 1px; height: 100%; padding: 0 30px; } .margin-bottom { margin-bottom: 10px; } /* Sidebar */ .bs-sidebar { background-color: #f9f9f9; padding-top: 44px; padding-right: 0; padding-left: 0; z-index: 20; } .bs-sidebar ul { list-style: none; padding-left: 12px; } .bs-sidebar ul li { margin-bottom: 0.5em; margin-left: -1em; } .bs-sidebar ul li a { font-size: 14px; padding-left: 25px; color: #4d5258; line-height: 28px; display: block; border-width: 1px 0 1px 1px; border-style: solid; border-color: #f9f9f9; } .bs-sidebar ul li a:hover, .bs-sidebar ul li a:focus { text-decoration: none; color: #777777; border-right: 2px solid #aaa; } .bs-sidebar ul li.active a { background-color: #c7e5f0; border-color: #56bae0; font-weight: bold; background-image: url(../img/icon-sidebar-active.png); background-repeat: no-repeat; background-position: right center; } .bs-sidebar ul li.active a:hover { border-right: none; } .content-area h2 { font-family: "Open Sans", sans-serif; font-weight: 100; font-size: 24px; margin-bottom: 25px; margin-top: 25px; } .subtitle { text-align: right; margin-top: 30px; color: #909090; } .required { color: #CB2915; } .alert { margin-top: 30px; margin-bottom: 0; } .feedback-aligner .alert { background-position: 1.27273em center; background-repeat: no-repeat; border-radius: 2px; border-width: 1px; color: #4D5258; display: inline-block; font-size: 1.1em; line-height: 1.4em; margin: 0; padding: 0.909091em 3.63636em; position: relative; text-align: left; } .alert.alert-success { background-color: #E4F1E1; border-color: #4B9E39; } .alert.alert-error { background-color: #F8E7E7; border-color: #B91415; } .alert.alert-warning { background-color: #FEF1E9; border-color: #F17528; } .alert.alert-info { background-color: #E4F3FA; border-color: #5994B2; } .form-horizontal { border-top: 1px solid #E9E8E8; padding-top: 23px; } .form-horizontal .control-label { color: #909090; line-height: 1.4em; padding-top: 5px; position: relative; text-align: right; width: 100%; } .form-group { position: relative; } .control-label + .required { position: absolute; right: -2px; top: 0; } #kc-form-buttons { text-align: right; margin-top: 10px; } #kc-form-buttons .btn-primary { float: right; margin-left: 8px; } /* Authenticator page */ ol { padding-left: 40px; } ol li { font-size: 13px; margin-bottom: 10px; position: relative; } ol li img { margin-top: 15px; margin-bottom: 5px; border: 1px solid #eee; } hr + .form-horizontal { border: none; padding-top: 0; } .kc-dropdown{ position: relative; } .kc-dropdown > a{ display:block; padding: 11px 10px 12px; line-height: 12px; font-size: 12px; color: #fff !important; text-decoration: none; } .kc-dropdown > a::after{ content: "\2c5"; margin-left: 4px; } .kc-dropdown:hover > a{ background-color: rgba(0,0,0,0.2); } .kc-dropdown ul li a{ padding: 1px 11px; font-size: 12px; color: #000 !important; border: 1px solid #fff; text-decoration: none; display:block; line-height: 20px; } .kc-dropdown ul li a:hover{ color: #4d5258; background-color: #d4edfa; border-color: #b3d3e7; } .kc-dropdown ul{ position: absolute; z-index: 2000; list-style:none; display:none; padding: 5px 0px; margin: 0px; background-color: #fff !important; border: 1px solid #b6b6b6; border-radius: 1px; -webkit-box-shadow: 0 6px 12px rgba(0, 0, 0, 0.175); box-shadow: 0 6px 12px rgba(0, 0, 0, 0.175); background-clip: padding-box; min-width: 100px; } .kc-dropdown:hover ul{ display:block; } #kc-totp-secret-key { border: 1px solid #eee; font-size: 16px; padding: 10px; margin: 50px 0; } ```
/content/code_sandbox/oauth-jwt/jwt-auth-server/src/main/resources/themes/custom/account/resources/css/account.css
css
2016-03-02T09:04:07
2024-08-06T03:02:12
spring-security-oauth
Baeldung/spring-security-oauth
1,982
1,550
```java package com.baeldung.jwt.config; import org.keycloak.services.util.JsonConfigProviderFactory; public class RegularJsonConfigProviderFactory extends JsonConfigProviderFactory { } ```
/content/code_sandbox/oauth-jwt/jwt-auth-server/src/main/java/com/baeldung/jwt/config/RegularJsonConfigProviderFactory.java
java
2016-03-02T09:04:07
2024-08-06T03:02:12
spring-security-oauth
Baeldung/spring-security-oauth
1,982
34
```java package com.baeldung.jwt.config; import java.io.UnsupportedEncodingException; import jakarta.servlet.Filter; import jakarta.servlet.FilterChain; import jakarta.servlet.ServletRequest; import jakarta.servlet.ServletResponse; import jakarta.servlet.http.HttpServletRequest; import org.keycloak.common.ClientConnection; import org.keycloak.services.filters.AbstractRequestFilter; public class EmbeddedKeycloakRequestFilter extends AbstractRequestFilter implements Filter { @Override public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws UnsupportedEncodingException { servletRequest.setCharacterEncoding("UTF-8"); ClientConnection clientConnection = createConnection((HttpServletRequest) servletRequest); filter(clientConnection, (session) -> { try { filterChain.doFilter(servletRequest, servletResponse); } catch (Exception e) { throw new RuntimeException(e); } }); } private ClientConnection createConnection(HttpServletRequest request) { return new ClientConnection() { @Override public String getRemoteAddr() { return request.getRemoteAddr(); } @Override public String getRemoteHost() { return request.getRemoteHost(); } @Override public int getRemotePort() { return request.getRemotePort(); } @Override public String getLocalAddr() { return request.getLocalAddr(); } @Override public int getLocalPort() { return request.getLocalPort(); } }; } } ```
/content/code_sandbox/oauth-jwt/jwt-auth-server/src/main/java/com/baeldung/jwt/config/EmbeddedKeycloakRequestFilter.java
java
2016-03-02T09:04:07
2024-08-06T03:02:12
spring-security-oauth
Baeldung/spring-security-oauth
1,982
304
```java package com.baeldung.jwt.config; import org.springframework.boot.context.properties.ConfigurationProperties; @ConfigurationProperties(prefix = "keycloak.server") public class KeycloakServerProperties { String contextPath = "/auth"; String realmImportFile = "baeldung-realm.json"; AdminUser adminUser = new AdminUser(); public String getContextPath() { return contextPath; } public void setContextPath(String contextPath) { this.contextPath = contextPath; } public AdminUser getAdminUser() { return adminUser; } public void setAdminUser(AdminUser adminUser) { this.adminUser = adminUser; } public String getRealmImportFile() { return realmImportFile; } public void setRealmImportFile(String realmImportFile) { this.realmImportFile = realmImportFile; } public static class AdminUser { String username = "admin"; String password = "admin"; public String getUsername() { return username; } public void setUsername(String username) { this.username = username; } public String getPassword() { return password; } public void setPassword(String password) { this.password = password; } } } ```
/content/code_sandbox/oauth-jwt/jwt-auth-server/src/main/java/com/baeldung/jwt/config/KeycloakServerProperties.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.jwt.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-jwt/jwt-auth-server/src/main/java/com/baeldung/jwt/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.jwt.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-jwt/jwt-auth-server/src/main/java/com/baeldung/jwt/config/EmbeddedKeycloakConfig.java
java
2016-03-02T09:04:07
2024-08-06T03:02:12
spring-security-oauth
Baeldung/spring-security-oauth
1,982
670
```java package com.baeldung.jwt.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.jwt.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-jwt/jwt-auth-server/src/main/java/com/baeldung/jwt/config/EmbeddedKeycloakApplication.java
java
2016-03-02T09:04:07
2024-08-06T03:02:12
spring-security-oauth
Baeldung/spring-security-oauth
1,982
530
```java package com.baeldung.jwt; import static org.assertj.core.api.Assertions.assertThat; 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; /** * This Live Test requires: - the Authorization Server and the Resource Server * to be running * */ public class CustomClaimLiveTest { 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 userInfoResourceUrl = "path_to_url"; @Test public void your_sha256_hashs() { String accessToken = obtainAccessToken("read"); // Access resources using access token Response response = RestAssured.given() .header(HttpHeaders.AUTHORIZATION, "Bearer " + accessToken) .get(userInfoResourceUrl); assertThat(response.as(Map.class)).containsEntry("DOB", "1984-07-01"); } 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", "jwtClient"); params.put("redirect_uri", redirectUrl); params.put("client_secret", "jwtClientSecret"); response = RestAssured.given() .formParams(params) .post(tokenUrl); return response.jsonPath() .getString("access_token"); } } ```
/content/code_sandbox/oauth-jwt/jwt-resource-server/src/test/java/com/baeldung/jwt/CustomClaimLiveTest.java
java
2016-03-02T09:04:07
2024-08-06T03:02:12
spring-security-oauth
Baeldung/spring-security-oauth
1,982
552
```java package com.baeldung.jwt; 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.jwt.JWTResourceServerApp; @ExtendWith(SpringExtension.class) @SpringBootTest(classes = { JWTResourceServerApp.class }) public class ContextIntegrationTest { @Test public void whenLoadApplication_thenSuccess() { } } ```
/content/code_sandbox/oauth-jwt/jwt-resource-server/src/test/java/com/baeldung/jwt/ContextIntegrationTest.java
java
2016-03-02T09:04:07
2024-08-06T03:02:12
spring-security-oauth
Baeldung/spring-security-oauth
1,982
94
```sqlpl INSERT INTO Foo(id, name) VALUES (1, 'Foo 1'); INSERT INTO Foo(id, name) VALUES (2, 'Foo 2'); INSERT INTO Foo(id, name) VALUES (3, 'Foo 3'); ```
/content/code_sandbox/oauth-jwt/jwt-resource-server/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
49
```yaml server: port: 8081 servlet: context-path: /jwt-resource-server ####### resource server configuration properties spring: jpa: defer-datasource-initialization: true security: oauth2: resourceserver: jwt: issuer-uri: path_to_url jwk-set-uri: path_to_url ```
/content/code_sandbox/oauth-jwt/jwt-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
77
```java package com.baeldung.jwt; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; @SpringBootApplication public class JWTResourceServerApp { public static void main(String[] args) throws Exception { SpringApplication.run(JWTResourceServerApp.class, args); } } ```
/content/code_sandbox/oauth-jwt/jwt-resource-server/src/main/java/com/baeldung/jwt/JWTResourceServerApp.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.jwt; 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.jwt.web.dto.FooDto; 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 ResourceServerLiveTest { 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"; private final String userInfoResourceUrl = "path_to_url"; @SuppressWarnings("unchecked") @Test public void givenUserWithReadScope_whenGetProjectResource_thenSuccess() { String accessToken = obtainAccessToken("read"); System.out.println("ACCESS TOKEN: " + accessToken); // 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 givenUserWithOtherScope_whenGetProjectResource_thenForbidden() { String accessToken = obtainAccessToken("email"); System.out.println("ACCESS TOKEN: " + accessToken); // Access resources using access token Response response = RestAssured.given() .header(HttpHeaders.AUTHORIZATION, "Bearer " + accessToken) .get(resourceUrl); System.out.println(response.asString()); assertThat(response.getStatusCode()).isEqualTo(HttpStatus.FORBIDDEN.value()); } @SuppressWarnings("unchecked") @Test public void your_sha256_hashs() { String accessToken = obtainAccessToken("read"); System.out.println("ACCESS TOKEN: " + accessToken); // Access resources using access token Response response = RestAssured.given() .header(HttpHeaders.AUTHORIZATION, "Bearer " + accessToken) .get(userInfoResourceUrl); System.out.println(response.asString()); assertThat(response.as(Map.class)).containsEntry("user_name", "john@test.com") .containsEntry("organization", "BAELDUNG"); } @Test public void givenUserWithReadScope_whenPostNewProjectResource_thenForbidden() { String accessToken = obtainAccessToken("read"); System.out.println("ACCESS TOKEN: " + accessToken); FooDto newFoo = new FooDto(0, "newFoo"); Response response = RestAssured.given() .header(HttpHeaders.AUTHORIZATION, "Bearer " + accessToken) .body(newFoo) .post(resourceUrl); System.out.println(response.asString()); assertThat(response.getStatusCode()).isEqualTo(HttpStatus.FORBIDDEN.value()); } @Test public void givenUserWithWriteScope_whenPostNewProjectResource_thenCreated() { String accessToken = obtainAccessToken("read write"); System.out.println("ACCESS TOKEN: " + accessToken); FooDto newFoo = new FooDto(0, "newFoo"); Response response = RestAssured.given() .contentType(ContentType.JSON) .header(HttpHeaders.AUTHORIZATION, "Bearer " + accessToken) .body(newFoo) .log() .all() .post(resourceUrl); System.out.println(response.asString()); 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", "jwtClient"); params.put("redirect_uri", redirectUrl); params.put("client_secret", "jwtClientSecret"); response = RestAssured.given() .formParams(params) .post(tokenUrl); return response.jsonPath() .getString("access_token"); } } ```
/content/code_sandbox/oauth-jwt/jwt-resource-server/src/test/java/com/baeldung/jwt/ResourceServerLiveTest.java
java
2016-03-02T09:04:07
2024-08-06T03:02:12
spring-security-oauth
Baeldung/spring-security-oauth
1,982
1,085
```java package com.baeldung.jwt.persistence.repository; import org.springframework.data.repository.PagingAndSortingRepository; import com.baeldung.jwt.persistence.model.Foo; public interface IFooRepository extends PagingAndSortingRepository<Foo, Long> { } ```
/content/code_sandbox/oauth-jwt/jwt-resource-server/src/main/java/com/baeldung/jwt/persistence/repository/IFooRepository.java
java
2016-03-02T09:04:07
2024-08-06T03:02:12
spring-security-oauth
Baeldung/spring-security-oauth
1,982
49
```java package com.baeldung.jwt.persistence.model; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; @Entity public class Foo { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private Long id; private String name; protected Foo() { } public Foo(String name) { 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; 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; Foo other = (Foo) 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-jwt/jwt-resource-server/src/main/java/com/baeldung/jwt/persistence/model/Foo.java
java
2016-03-02T09:04:07
2024-08-06T03:02:12
spring-security-oauth
Baeldung/spring-security-oauth
1,982
372
```java package com.baeldung.jwt.service; import java.util.Optional; import com.baeldung.jwt.persistence.model.Foo; public interface IFooService { Optional<Foo> findById(Long id); Foo save(Foo foo); Iterable<Foo> findAll(); } ```
/content/code_sandbox/oauth-jwt/jwt-resource-server/src/main/java/com/baeldung/jwt/service/IFooService.java
java
2016-03-02T09:04:07
2024-08-06T03:02:12
spring-security-oauth
Baeldung/spring-security-oauth
1,982
56
```java package com.baeldung.jwt.service.impl; import java.util.Optional; import org.springframework.stereotype.Service; import com.baeldung.jwt.persistence.model.Foo; import com.baeldung.jwt.persistence.repository.IFooRepository; import com.baeldung.jwt.service.IFooService; @Service public class FooServiceImpl implements IFooService { private IFooRepository fooRepository; public FooServiceImpl(IFooRepository fooRepository) { this.fooRepository = fooRepository; } @Override public Optional<Foo> findById(Long id) { return fooRepository.findById(id); } @Override public Foo save(Foo foo) { return fooRepository.save(foo); } @Override public Iterable<Foo> findAll() { return fooRepository.findAll(); } } ```
/content/code_sandbox/oauth-jwt/jwt-resource-server/src/main/java/com/baeldung/jwt/service/impl/FooServiceImpl.java
java
2016-03-02T09:04:07
2024-08-06T03:02:12
spring-security-oauth
Baeldung/spring-security-oauth
1,982
163
```java package com.baeldung.jwt.spring; import java.util.Collections; import java.util.Map; import org.springframework.core.convert.converter.Converter; import org.springframework.security.oauth2.jwt.MappedJwtClaimSetConverter; public class OrganizationSubClaimAdapter implements Converter<Map<String, Object>, Map<String, Object>> { private final MappedJwtClaimSetConverter delegate = MappedJwtClaimSetConverter.withDefaults(Collections.emptyMap()); public Map<String, Object> convert(Map<String, Object> claims) { Map<String, Object> convertedClaims = this.delegate.convert(claims); String organization = convertedClaims.get("organization") != null ? (String) convertedClaims.get("organization") : "unknown"; convertedClaims.put("organization", organization.toUpperCase()); return convertedClaims; } } ```
/content/code_sandbox/oauth-jwt/jwt-resource-server/src/main/java/com/baeldung/jwt/spring/OrganizationSubClaimAdapter.java
java
2016-03-02T09:04:07
2024-08-06T03:02:12
spring-security-oauth
Baeldung/spring-security-oauth
1,982
161
```java package com.baeldung.jwt.spring; import org.springframework.boot.autoconfigure.security.oauth2.resource.OAuth2ResourceServerProperties; 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.config.annotation.web.configuration.WebSecurityConfigurerAdapter; import org.springframework.security.oauth2.jwt.JwtDecoder; import org.springframework.security.oauth2.jwt.NimbusJwtDecoder; @Configuration public class SecurityConfig extends WebSecurityConfigurerAdapter { @Override protected void configure(HttpSecurity http) throws Exception {// @formatter:off http.cors() .and() .authorizeRequests() .antMatchers(HttpMethod.GET, "/user/info", "/api/foos/**") .hasAuthority("SCOPE_read") .antMatchers(HttpMethod.POST, "/api/foos") .hasAuthority("SCOPE_write") .anyRequest() .authenticated() .and() .oauth2ResourceServer() .jwt(); }// @formatter:on @Bean JwtDecoder jwtDecoder(OAuth2ResourceServerProperties properties) { NimbusJwtDecoder jwtDecoder = NimbusJwtDecoder.withJwkSetUri(properties.getJwt().getJwkSetUri()).build(); jwtDecoder.setClaimSetConverter(new OrganizationSubClaimAdapter()); return jwtDecoder; } } ```
/content/code_sandbox/oauth-jwt/jwt-resource-server/src/main/java/com/baeldung/jwt/spring/SecurityConfig.java
java
2016-03-02T09:04:07
2024-08-06T03:02:12
spring-security-oauth
Baeldung/spring-security-oauth
1,982
285
```java package com.baeldung.jwt.web.controller; import java.util.Collections; import java.util.Map; import org.springframework.security.core.annotation.AuthenticationPrincipal; import org.springframework.security.oauth2.jwt.Jwt; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RestController; @RestController public class CustomUserAttrController { @GetMapping("/user/info/custom") public Map<String, Object> getUserInfo(@AuthenticationPrincipal Jwt principal) { return Collections.singletonMap("DOB", principal.getClaimAsString("DOB")); } } ```
/content/code_sandbox/oauth-jwt/jwt-resource-server/src/main/java/com/baeldung/jwt/web/controller/CustomUserAttrController.java
java
2016-03-02T09:04:07
2024-08-06T03:02:12
spring-security-oauth
Baeldung/spring-security-oauth
1,982
104
```java package com.baeldung.jwt.web.controller; import static org.apache.commons.lang3.RandomStringUtils.randomAlphabetic; import static org.apache.commons.lang3.RandomStringUtils.randomNumeric; import java.util.ArrayList; import java.util.Collection; import java.util.List; import org.springframework.http.HttpStatus; import org.springframework.util.StringUtils; import org.springframework.web.bind.annotation.CrossOrigin; 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.PutMapping; 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.persistence.model.Foo; import com.baeldung.jwt.service.IFooService; import com.baeldung.jwt.web.dto.FooDto; @RestController @RequestMapping(value = "/api/foos") @CrossOrigin(origins = "path_to_url") public class FooController { private IFooService fooService; public FooController(IFooService fooService) { this.fooService = fooService; } @GetMapping(value = "/{id}") public FooDto findOne(@PathVariable Long id) { return new FooDto(Long.parseLong(randomNumeric(2)), randomAlphabetic(4)); } @ResponseStatus(HttpStatus.CREATED) @PostMapping public void create(@RequestBody FooDto newFoo) { Foo entity = convertToEntity(newFoo); this.fooService.save(entity); } @GetMapping public Collection<FooDto> findAll() { Iterable<Foo> foos = this.fooService.findAll(); List<FooDto> fooDtos = new ArrayList<>(); foos.forEach(p -> fooDtos.add(convertToDto(p))); return fooDtos; } @PutMapping("/{id}") public FooDto updateFoo(@PathVariable("id") Long id, @RequestBody FooDto updatedFoo) { Foo fooEntity = convertToEntity(updatedFoo); return this.convertToDto(this.fooService.save(fooEntity)); } protected FooDto convertToDto(Foo entity) { FooDto dto = new FooDto(entity.getId(), entity.getName()); return dto; } protected Foo convertToEntity(FooDto dto) { Foo foo = new Foo(dto.getName()); if (!StringUtils.isEmpty(dto.getId())) { foo.setId(dto.getId()); } return foo; } } ```
/content/code_sandbox/oauth-jwt/jwt-resource-server/src/main/java/com/baeldung/jwt/web/controller/FooController.java
java
2016-03-02T09:04:07
2024-08-06T03:02:12
spring-security-oauth
Baeldung/spring-security-oauth
1,982
505
```java package com.baeldung.jwt.web.controller; import java.util.Collections; import java.util.Hashtable; import java.util.Map; import org.springframework.security.core.annotation.AuthenticationPrincipal; import org.springframework.security.oauth2.jwt.Jwt; import org.springframework.web.bind.annotation.CrossOrigin; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RestController; @RestController public class UserInfoController { @CrossOrigin(origins = "path_to_url") @GetMapping("/user/info") public Map<String, Object> getUserInfo(@AuthenticationPrincipal Jwt principal) { Map<String, String> map = new Hashtable<String, String>(); map.put("user_name", principal.getClaimAsString("preferred_username")); map.put("organization", principal.getClaimAsString("organization")); return Collections.unmodifiableMap(map); } } ```
/content/code_sandbox/oauth-jwt/jwt-resource-server/src/main/java/com/baeldung/jwt/web/controller/UserInfoController.java
java
2016-03-02T09:04:07
2024-08-06T03:02:12
spring-security-oauth
Baeldung/spring-security-oauth
1,982
165
```java package com.baeldung.jwt.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-jwt/jwt-resource-server/src/main/java/com/baeldung/jwt/web/dto/FooDto.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; import static org.assertj.core.api.Assertions.assertThat; 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; public class AuthorizationServerLiveTest { @Test public void givenAuthorizationCodeGrant_whenObtainAccessToken_thenSuccess() { String accessToken = obtainAccessToken(); assertThat(accessToken).isNotBlank(); } @Test public void your_sha256_hashdpointIsAvailable() { final String oidcDiscoveryUrl = "path_to_url"; Response response = RestAssured.given() .redirects() .follow(false) .get(oidcDiscoveryUrl); assertThat(HttpStatus.OK.value()).isEqualTo(response.getStatusCode()); System.out.println(response.asString()); assertThat(response.jsonPath() .getMap("$.")).containsKeys("issuer", "authorization_endpoint", "token_endpoint", "userinfo_endpoint"); } private String obtainAccessToken() { final String redirectUrl = "path_to_url"; final String authorizeUrl = "path_to_url" + redirectUrl; final String tokenUrl = "path_to_url"; // obtain authentication url with custom codes Response response = RestAssured.given() .redirects() .follow(false) .get(authorizeUrl); 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", "fooClient"); params.put("redirect_uri", redirectUrl); params.put("client_secret", "fooClientSecret"); response = RestAssured.given() .formParams(params) .post(tokenUrl); return response.jsonPath() .getString("access_token"); } } ```
/content/code_sandbox/oauth-resource-server/authorization-server/src/test/java/com/baeldung/jwt/AuthorizationServerLiveTest.java
java
2016-03-02T09:04:07
2024-08-06T03:02:12
spring-security-oauth
Baeldung/spring-security-oauth
1,982
565
```java package com.baeldung.jwt; 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.authserver.AuthorizationServerApp; @ExtendWith(SpringExtension.class) @SpringBootTest(classes = { AuthorizationServerApp.class }) public class ContextIntegrationTest { @Test public void whenLoadApplication_thenSuccess() { } } ```
/content/code_sandbox/oauth-resource-server/authorization-server/src/test/java/com/baeldung/jwt/ContextIntegrationTest.java
java
2016-03-02T09:04:07
2024-08-06T03:02:12
spring-security-oauth
Baeldung/spring-security-oauth
1,982
93
```yaml server: port: 8083 spring: datasource: username: sa url: jdbc:h2:mem:testdb keycloak: server: contextPath: /auth adminUser: username: bael-admin password: pass realmImportFile: feign-realm.json ```
/content/code_sandbox/oauth-resource-server/authorization-server/src/main/resources/application-feign.yml
yaml
2016-03-02T09:04:07
2024-08-06T03:02:12
spring-security-oauth
Baeldung/spring-security-oauth
1,982
71
```yaml server: port: 8083 spring: datasource: username: sa url: jdbc:h2:mem:testdb;DB_CLOSE_ON_EXIT=FALSE keycloak: server: contextPath: /auth adminUser: username: bael-admin password: pass realmImportFile: baeldung-realm.json ```
/content/code_sandbox/oauth-resource-server/authorization-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
```yaml server: port: 8083 spring: datasource: username: sa url: jdbc:h2:mem:testdb keycloak: server: contextPath: /auth adminUser: username: bael-admin password: pass realmImportFile: customer-realm.json ```
/content/code_sandbox/oauth-resource-server/authorization-server/src/main/resources/application-customer.yml
yaml
2016-03-02T09:04:07
2024-08-06T03:02:12
spring-security-oauth
Baeldung/spring-security-oauth
1,982
70
```java package com.baeldung.authserver; 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.authserver.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-resource-server/authorization-server/src/main/java/com/baeldung/authserver/AuthorizationServerApp.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.authserver.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 "authorization-server"; } } ```
/content/code_sandbox/oauth-resource-server/authorization-server/src/main/java/com/baeldung/authserver/config/SimplePlatformProvider.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.authserver.config; import org.keycloak.services.util.JsonConfigProviderFactory; public class RegularJsonConfigProviderFactory extends JsonConfigProviderFactory { } ```
/content/code_sandbox/oauth-resource-server/authorization-server/src/main/java/com/baeldung/authserver/config/RegularJsonConfigProviderFactory.java
java
2016-03-02T09:04:07
2024-08-06T03:02:12
spring-security-oauth
Baeldung/spring-security-oauth
1,982
35
```java package com.baeldung.authserver.config; import java.io.UnsupportedEncodingException; import jakarta.servlet.Filter; import jakarta.servlet.FilterChain; import jakarta.servlet.ServletRequest; import jakarta.servlet.ServletResponse; import jakarta.servlet.http.HttpServletRequest; import org.keycloak.common.ClientConnection; import org.keycloak.services.filters.AbstractRequestFilter; public class EmbeddedKeycloakRequestFilter extends AbstractRequestFilter implements Filter { @Override public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws UnsupportedEncodingException { servletRequest.setCharacterEncoding("UTF-8"); ClientConnection clientConnection = createConnection((HttpServletRequest) servletRequest); filter(clientConnection, (session) -> { try { filterChain.doFilter(servletRequest, servletResponse); } catch (Exception e) { throw new RuntimeException(e); } }); } private ClientConnection createConnection(HttpServletRequest request) { return new ClientConnection() { @Override public String getRemoteAddr() { return request.getRemoteAddr(); } @Override public String getRemoteHost() { return request.getRemoteHost(); } @Override public int getRemotePort() { return request.getRemotePort(); } @Override public String getLocalAddr() { return request.getLocalAddr(); } @Override public int getLocalPort() { return request.getLocalPort(); } }; } } ```
/content/code_sandbox/oauth-resource-server/authorization-server/src/main/java/com/baeldung/authserver/config/EmbeddedKeycloakRequestFilter.java
java
2016-03-02T09:04:07
2024-08-06T03:02:12
spring-security-oauth
Baeldung/spring-security-oauth
1,982
305
```java package com.baeldung.authserver.config; import org.springframework.boot.context.properties.ConfigurationProperties; @ConfigurationProperties(prefix = "keycloak.server") public class KeycloakServerProperties { String contextPath = "/auth"; String realmImportFile = "baeldung-realm.json"; AdminUser adminUser = new AdminUser(); public String getContextPath() { return contextPath; } public void setContextPath(String contextPath) { this.contextPath = contextPath; } public AdminUser getAdminUser() { return adminUser; } public void setAdminUser(AdminUser adminUser) { this.adminUser = adminUser; } public String getRealmImportFile() { return realmImportFile; } public void setRealmImportFile(String realmImportFile) { this.realmImportFile = realmImportFile; } public static class AdminUser { String username = "admin"; String password = "admin"; public String getUsername() { return username; } public void setUsername(String username) { this.username = username; } public String getPassword() { return password; } public void setPassword(String password) { this.password = password; } } } ```
/content/code_sandbox/oauth-resource-server/authorization-server/src/main/java/com/baeldung/authserver/config/KeycloakServerProperties.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.authserver.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-resource-server/authorization-server/src/main/java/com/baeldung/authserver/config/Resteasy3Provider.java
java
2016-03-02T09:04:07
2024-08-06T03:02:12
spring-security-oauth
Baeldung/spring-security-oauth
1,982
199
```java package com.baeldung.authserver.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.authserver.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-resource-server/authorization-server/src/main/java/com/baeldung/authserver/config/EmbeddedKeycloakApplication.java
java
2016-03-02T09:04:07
2024-08-06T03:02:12
spring-security-oauth
Baeldung/spring-security-oauth
1,982
531
```java package com.baeldung.authserver.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-resource-server/authorization-server/src/main/java/com/baeldung/authserver/config/EmbeddedKeycloakConfig.java
java
2016-03-02T09:04:07
2024-08-06T03:02:12
spring-security-oauth
Baeldung/spring-security-oauth
1,982
665
```java package com.baeldung.jwt; 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 /* the configuration requires the AS to be running */ public class SpringContextLiveTest { @Test public void whenLoadApplication_thenSuccess() { } } ```
/content/code_sandbox/oauth-resource-server/resource-server-jwt/src/test/java/com/baeldung/jwt/SpringContextLiveTest.java
java
2016-03-02T09:04:07
2024-08-06T03:02:12
spring-security-oauth
Baeldung/spring-security-oauth
1,982
86
```yaml server: port: 8081 servlet: context-path: /resource-server-jwt ####### resource server configuration properties spring: security: oauth2: resourceserver: jwt: issuer-uri: path_to_url ```
/content/code_sandbox/oauth-resource-server/resource-server-jwt/src/main/resources/application-feign.yml
yaml
2016-03-02T09:04:07
2024-08-06T03:02:12
spring-security-oauth
Baeldung/spring-security-oauth
1,982
54
```java package com.baeldung.jwt; 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.jwt.resource.Foo; 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 JWTResourceServerLiveTest { 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_whenGetFooResource_thenSuccess() { String accessToken = obtainAccessToken("read"); // Access resources using access token Response response = RestAssured.given() .header(HttpHeaders.AUTHORIZATION, "Bearer " + accessToken) .get(resourceUrl); assertThat(response.as(List.class)).hasSizeGreaterThan(0); } @Test public void givenUserWithReadScope_whenPostNewFooResource_thenForbidden() { String accessToken = obtainAccessToken("read"); Foo newFoo = new Foo(Long.parseLong(randomNumeric(2)), randomAlphabetic(4)); Response response = RestAssured.given() .header(HttpHeaders.AUTHORIZATION, "Bearer " + accessToken) .body(newFoo) .post(resourceUrl); assertThat(response.getStatusCode()).isEqualTo(HttpStatus.FORBIDDEN.value()); } @Test public void givenUserWithWriteScope_whenPostNewFooResource_thenCreated() { String accessToken = obtainAccessToken("read write"); Foo newFoo = new Foo(Long.parseLong(randomNumeric(2)), randomAlphabetic(4)); Response response = RestAssured.given() .contentType(ContentType.JSON) .header(HttpHeaders.AUTHORIZATION, "Bearer " + accessToken) .body(newFoo) .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", "fooClient"); params.put("redirect_uri", redirectUrl); params.put("client_secret", "fooClientSecret"); response = RestAssured.given() .formParams(params) .post(tokenUrl); return response.jsonPath() .getString("access_token"); } } ```
/content/code_sandbox/oauth-resource-server/resource-server-jwt/src/test/java/com/baeldung/jwt/JWTResourceServerLiveTest.java
java
2016-03-02T09:04:07
2024-08-06T03:02:12
spring-security-oauth
Baeldung/spring-security-oauth
1,982
825
```java package com.baeldung.jwt.resource; public class Payment { private String id; private double amount; public String getId() { return id; } public void setId(String id) { this.id = id; } public double getAmount() { return amount; } public void setAmount(double amount) { this.amount = amount; } } ```
/content/code_sandbox/oauth-resource-server/resource-server-jwt/src/main/java/com/baeldung/jwt/resource/Payment.java
java
2016-03-02T09:04:07
2024-08-06T03:02:12
spring-security-oauth
Baeldung/spring-security-oauth
1,982
82
```java package com.baeldung.jwt.config; 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 JWTSecurityConfig { @Bean public SecurityFilterChain filterChain(HttpSecurity http) throws Exception { http.authorizeRequests(authz -> authz.antMatchers(HttpMethod.GET, "/foos/**") .hasAuthority("SCOPE_read") .antMatchers(HttpMethod.POST, "/foos") .hasAuthority("SCOPE_write") .anyRequest() .authenticated()) .oauth2ResourceServer(oauth2 -> oauth2.jwt()); return http.build(); } } ```
/content/code_sandbox/oauth-resource-server/resource-server-jwt/src/main/java/com/baeldung/jwt/config/JWTSecurityConfig.java
java
2016-03-02T09:04:07
2024-08-06T03:02:12
spring-security-oauth
Baeldung/spring-security-oauth
1,982
158
```java package com.baeldung.jwt.resource; 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-resource-server/resource-server-jwt/src/main/java/com/baeldung/jwt/resource/Foo.java
java
2016-03-02T09:04:07
2024-08-06T03:02:12
spring-security-oauth
Baeldung/spring-security-oauth
1,982
121