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.config; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.boot.web.servlet.support.SpringBootServletInitializer; @SpringBootApplication public class ResourceServerApplication extends SpringBootServletInitializer { public static void main(String[] args) { SpringApplication.run(ResourceServerApplication.class, args); } } ```
/content/code_sandbox/oauth-legacy/oauth-resource-server-legacy-2/src/main/java/com/baeldung/config/ResourceServerApplication.java
java
2016-03-02T09:04:07
2024-08-06T03:02:12
spring-security-oauth
Baeldung/spring-security-oauth
1,982
69
```java package com.baeldung.config; import org.springframework.context.annotation.ComponentScan; import org.springframework.context.annotation.Configuration; import org.springframework.web.servlet.config.annotation.WebMvcConfigurer; @Configuration // @EnableWebMvc @ComponentScan({ "com.baeldung.web.controller" }) public class ResourceServerWebConfig implements WebMvcConfigurer { // } ```
/content/code_sandbox/oauth-legacy/oauth-resource-server-legacy-2/src/main/java/com/baeldung/config/ResourceServerWebConfig.java
java
2016-03-02T09:04:07
2024-08-06T03:02:12
spring-security-oauth
Baeldung/spring-security-oauth
1,982
68
```java package com.baeldung.config; import java.net.MalformedURLException; import java.net.URL; import java.util.Arrays; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.Primary; import org.springframework.security.config.annotation.web.builders.HttpSecurity; import org.springframework.security.config.http.SessionCreationPolicy; import org.springframework.security.oauth2.config.annotation.web.configuration.EnableResourceServer; import org.springframework.security.oauth2.config.annotation.web.configuration.ResourceServerConfigurerAdapter; import org.springframework.security.oauth2.config.annotation.web.configurers.ResourceServerSecurityConfigurer; import org.springframework.security.oauth2.provider.token.DefaultTokenServices; import org.springframework.security.oauth2.provider.token.TokenStore; import org.springframework.security.oauth2.provider.token.store.DelegatingJwtClaimsSetVerifier; import org.springframework.security.oauth2.provider.token.store.IssuerClaimVerifier; import org.springframework.security.oauth2.provider.token.store.JwtAccessTokenConverter; import org.springframework.security.oauth2.provider.token.store.JwtClaimsSetVerifier; import org.springframework.security.oauth2.provider.token.store.JwtTokenStore; @Configuration @EnableResourceServer public class OAuth2ResourceServerConfig extends ResourceServerConfigurerAdapter { @Override public void configure(final HttpSecurity http) throws Exception { http.sessionManagement().sessionCreationPolicy(SessionCreationPolicy.IF_REQUIRED).and() .authorizeRequests().antMatchers("/swagger*", "/v2/**", "/webjars/**") //.access("#oauth2.hasScope('read')").anyRequest() .permitAll(); } // JWT token store @Override public void configure(final ResourceServerSecurityConfigurer config) { config.tokenServices(tokenServices()); } @Bean public TokenStore tokenStore() { return new JwtTokenStore(accessTokenConverter()); } @Bean public JwtAccessTokenConverter accessTokenConverter() { final JwtAccessTokenConverter converter = new JwtAccessTokenConverter(); converter.setSigningKey("123"); converter.setJwtClaimsSetVerifier(jwtClaimsSetVerifier()); // final Resource resource = new ClassPathResource("public.txt"); // String publicKey = null; // try { // publicKey = IOUtils.toString(resource.getInputStream(), Charset.defaultCharset()); // } catch (final IOException e) { // throw new RuntimeException(e); // } // converter.setVerifierKey(publicKey); return converter; } @Bean public JwtClaimsSetVerifier jwtClaimsSetVerifier() { return new DelegatingJwtClaimsSetVerifier(Arrays.asList(issuerClaimVerifier(), customJwtClaimVerifier())); } @Bean public JwtClaimsSetVerifier issuerClaimVerifier() { try { return new IssuerClaimVerifier(new URL("path_to_url")); } catch (final MalformedURLException e) { throw new RuntimeException(e); } } @Bean public JwtClaimsSetVerifier customJwtClaimVerifier() { return new CustomClaimVerifier(); } @Bean @Primary public DefaultTokenServices tokenServices() { final DefaultTokenServices defaultTokenServices = new DefaultTokenServices(); defaultTokenServices.setTokenStore(tokenStore()); return defaultTokenServices; } } ```
/content/code_sandbox/oauth-legacy/oauth-resource-server-legacy-2/src/main/java/com/baeldung/config/OAuth2ResourceServerConfig.java
java
2016-03-02T09:04:07
2024-08-06T03:02:12
spring-security-oauth
Baeldung/spring-security-oauth
1,982
647
```java package com.baeldung.config; import java.util.Arrays; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import springfox.documentation.builders.AuthorizationCodeGrantBuilder; import springfox.documentation.builders.OAuthBuilder; import springfox.documentation.builders.PathSelectors; import springfox.documentation.builders.RequestHandlerSelectors; import springfox.documentation.service.AuthorizationScope; import springfox.documentation.service.GrantType; import springfox.documentation.service.SecurityReference; import springfox.documentation.service.SecurityScheme; import springfox.documentation.service.TokenEndpoint; import springfox.documentation.service.TokenRequestEndpoint; import springfox.documentation.spi.DocumentationType; import springfox.documentation.spi.service.contexts.SecurityContext; import springfox.documentation.spring.web.plugins.Docket; import springfox.documentation.swagger.web.SecurityConfiguration; import springfox.documentation.swagger.web.SecurityConfigurationBuilder; import springfox.documentation.swagger2.annotations.EnableSwagger2; @Configuration @EnableSwagger2 public class SwaggerConfig { public static final String AUTH_SERVER = "path_to_url"; public static final String CLIENT_ID = "fooClientIdPassword"; public static final String CLIENT_SECRET = "secret"; @Bean public Docket api() { return new Docket(DocumentationType.SWAGGER_2).select() .apis(RequestHandlerSelectors.any()) .paths(PathSelectors.any()) .build() .securitySchemes(Arrays.asList(securityScheme())) .securityContexts(Arrays.asList(securityContext())); } @Bean public SecurityConfiguration security() { return SecurityConfigurationBuilder.builder() .clientId(CLIENT_ID) .clientSecret(CLIENT_SECRET) .scopeSeparator(" ") .useBasicAuthenticationWithAccessCodeGrant(true) .build(); } private SecurityScheme securityScheme() { GrantType grantType = new AuthorizationCodeGrantBuilder() .tokenEndpoint(new TokenEndpoint(AUTH_SERVER + "/token", "oauthtoken")) .tokenRequestEndpoint( new TokenRequestEndpoint(AUTH_SERVER + "/authorize", CLIENT_ID, CLIENT_ID)) .build(); SecurityScheme oauth = new OAuthBuilder().name("spring_oauth") .grantTypes(Arrays.asList(grantType)) .scopes(Arrays.asList(scopes())) .build(); return oauth; } private SecurityContext securityContext() { return SecurityContext.builder() .securityReferences( Arrays.asList(new SecurityReference("spring_oauth", scopes()))) .forPaths(PathSelectors.regex("/foos.*")) .build(); } private AuthorizationScope[] scopes() { AuthorizationScope[] scopes = { new AuthorizationScope("read", "for read operations"), new AuthorizationScope("write", "for write operations"), new AuthorizationScope("foo", "Access foo API") }; return scopes; } } ```
/content/code_sandbox/oauth-legacy/oauth-resource-server-legacy-2/src/main/java/com/baeldung/config/SwaggerConfig.java
java
2016-03-02T09:04:07
2024-08-06T03:02:12
spring-security-oauth
Baeldung/spring-security-oauth
1,982
559
```java package com.baeldung.web.controller; import static org.apache.commons.lang3.RandomStringUtils.randomAlphabetic; import static org.apache.commons.lang3.RandomStringUtils.randomNumeric; import org.springframework.http.HttpStatus; import org.springframework.security.access.prepost.PreAuthorize; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.ResponseBody; import org.springframework.web.bind.annotation.ResponseStatus; import com.baeldung.web.dto.Bar; @Controller public class BarController { public BarController() { super(); } // API - read @PreAuthorize("#oauth2.hasScope('bar') and #oauth2.hasScope('read')") @RequestMapping(method = RequestMethod.GET, value = "/bars/{id}") @ResponseBody public Bar findById(@PathVariable final long id) { return new Bar(Long.parseLong(randomNumeric(2)), randomAlphabetic(4)); } // API - write @PreAuthorize("#oauth2.hasScope('bar') and #oauth2.hasScope('write') and hasRole('ROLE_ADMIN')") @RequestMapping(method = RequestMethod.POST, value = "/bars") @ResponseStatus(HttpStatus.CREATED) @ResponseBody public Bar create(@RequestBody final Bar bar) { bar.setId(Long.parseLong(randomNumeric(2))); return bar; } } ```
/content/code_sandbox/oauth-legacy/oauth-resource-server-legacy-2/src/main/java/com/baeldung/web/controller/BarController.java
java
2016-03-02T09:04:07
2024-08-06T03:02:12
spring-security-oauth
Baeldung/spring-security-oauth
1,982
295
```java package com.baeldung.web.controller; import static org.apache.commons.lang3.RandomStringUtils.randomAlphabetic; import static org.apache.commons.lang3.RandomStringUtils.randomNumeric; import org.springframework.http.HttpStatus; import org.springframework.security.access.prepost.PreAuthorize; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.ResponseBody; import org.springframework.web.bind.annotation.ResponseStatus; import com.baeldung.web.dto.Foo; @Controller public class FooController { public FooController() { super(); } // API - read @PreAuthorize("#oauth2.hasScope('foo') and #oauth2.hasScope('read')") @RequestMapping(method = RequestMethod.GET, value = "/foos/{id}") @ResponseBody public Foo findById(@PathVariable final long id) { return new Foo(Long.parseLong(randomNumeric(2)), randomAlphabetic(4)); } // API - write @PreAuthorize("#oauth2.hasScope('foo') and #oauth2.hasScope('write')") @RequestMapping(method = RequestMethod.POST, value = "/foos") @ResponseStatus(HttpStatus.CREATED) @ResponseBody public Foo create(@RequestBody final Foo foo) { foo.setId(Long.parseLong(randomNumeric(2))); return foo; } } ```
/content/code_sandbox/oauth-legacy/oauth-resource-server-legacy-2/src/main/java/com/baeldung/web/controller/FooController.java
java
2016-03-02T09:04:07
2024-08-06T03:02:12
spring-security-oauth
Baeldung/spring-security-oauth
1,982
291
```java package com.baeldung.web.controller; import java.util.Map; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.security.access.prepost.PreAuthorize; import org.springframework.security.oauth2.common.OAuth2AccessToken; import org.springframework.security.oauth2.provider.OAuth2Authentication; import org.springframework.security.oauth2.provider.authentication.OAuth2AuthenticationDetails; import org.springframework.security.oauth2.provider.token.TokenStore; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.ResponseBody; @Controller public class UserController { @Autowired private TokenStore tokenStore; @PreAuthorize("#oauth2.hasScope('read')") @RequestMapping(method = RequestMethod.GET, value = "/users/extra") @ResponseBody public Map<String, Object> getExtraInfo(OAuth2Authentication auth) { final OAuth2AuthenticationDetails details = (OAuth2AuthenticationDetails) auth.getDetails(); final OAuth2AccessToken accessToken = tokenStore.readAccessToken(details.getTokenValue()); System.out.println(accessToken); return accessToken.getAdditionalInformation(); } } ```
/content/code_sandbox/oauth-legacy/oauth-resource-server-legacy-2/src/main/java/com/baeldung/web/controller/UserController.java
java
2016-03-02T09:04:07
2024-08-06T03:02:12
spring-security-oauth
Baeldung/spring-security-oauth
1,982
226
```java package com.baeldung.web.dto; public class Bar { private long id; private String name; public Bar() { super(); } public Bar(final long id, final String name) { super(); this.id = id; this.name = name; } // public long getId() { return id; } public void setId(final long id) { this.id = id; } public String getName() { return name; } public void setName(final String name) { this.name = name; } } ```
/content/code_sandbox/oauth-legacy/oauth-resource-server-legacy-2/src/main/java/com/baeldung/web/dto/Bar.java
java
2016-03-02T09:04:07
2024-08-06T03:02:12
spring-security-oauth
Baeldung/spring-security-oauth
1,982
123
```java package com.baeldung.test; import static org.hamcrest.Matchers.is; import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.*; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.*; import static org.springframework.security.test.web.servlet.request.SecurityMockMvcRequestPostProcessors.*; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.security.web.FilterChainProxy; import org.springframework.test.context.junit4.SpringRunner; import org.springframework.test.context.web.WebAppConfiguration; import org.springframework.test.web.servlet.MockMvc; import org.springframework.test.web.servlet.ResultActions; import org.springframework.test.web.servlet.setup.MockMvcBuilders; import org.springframework.util.LinkedMultiValueMap; import org.springframework.util.MultiValueMap; import org.springframework.web.context.WebApplicationContext; import com.baeldung.config.AuthorizationServerApplication; import org.springframework.boot.json.JacksonJsonParser; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.test.context.ActiveProfiles; @RunWith(SpringRunner.class) @WebAppConfiguration @SpringBootTest(classes = AuthorizationServerApplication.class) @ActiveProfiles("mvc") public class OAuthMvcTest { @Autowired private WebApplicationContext wac; @Autowired private FilterChainProxy springSecurityFilterChain; private MockMvc mockMvc; private static final String CLIENT_ID = "fooClientIdPassword"; private static final String CLIENT_SECRET = "secret"; private static final String CONTENT_TYPE = "application/json;charset=UTF-8"; private static final String EMAIL = "jim@yahoo.com"; private static final String NAME = "Jim"; @Before public void setup() { this.mockMvc = MockMvcBuilders.webAppContextSetup(this.wac).addFilter(springSecurityFilterChain).build(); } private String obtainAccessToken(String username, String password) throws Exception { final MultiValueMap<String, String> params = new LinkedMultiValueMap<>(); params.add("grant_type", "password"); params.add("client_id", CLIENT_ID); params.add("username", username); params.add("password", password); // @formatter:off ResultActions result = mockMvc.perform(post("/oauth/token") .params(params) .with(httpBasic(CLIENT_ID, CLIENT_SECRET)) .accept(CONTENT_TYPE)) .andExpect(status().isOk()) .andExpect(content().contentType(CONTENT_TYPE)); // @formatter:on String resultString = result.andReturn().getResponse().getContentAsString(); JacksonJsonParser jsonParser = new JacksonJsonParser(); return jsonParser.parseMap(resultString).get("access_token").toString(); } @Test public void givenNoToken_whenGetSecureRequest_thenUnauthorized() throws Exception { mockMvc.perform(get("/employee").param("email", EMAIL)).andExpect(status().isUnauthorized()); } @Test public void givenInvalidRole_whenGetSecureRequest_thenForbidden() throws Exception { final String accessToken = obtainAccessToken("user1", "pass"); System.out.println("token:" + accessToken); mockMvc.perform(get("/employee").header("Authorization", "Bearer " + accessToken).param("email", EMAIL)).andExpect(status().isForbidden()); } @Test public void givenToken_whenPostGetSecureRequest_thenOk() throws Exception { final String accessToken = obtainAccessToken("admin", "nimda"); String employeeString = "{\"email\":\"" + EMAIL + "\",\"name\":\"" + NAME + "\",\"age\":30}"; // @formatter:off mockMvc.perform(post("/employee") .header("Authorization", "Bearer " + accessToken) .contentType(CONTENT_TYPE) .content(employeeString) .accept(CONTENT_TYPE)) .andExpect(status().isCreated()); mockMvc.perform(get("/employee") .param("email", EMAIL) .header("Authorization", "Bearer " + accessToken) .accept(CONTENT_TYPE)) .andExpect(status().isOk()) .andExpect(content().contentType(CONTENT_TYPE)) .andExpect(jsonPath("$.name", is(NAME))); // @formatter:on } } ```
/content/code_sandbox/oauth-legacy/oauth-authorization-server-legacy/src/test/java/com/baeldung/test/OAuthMvcTest.java
java
2016-03-02T09:04:07
2024-08-06T03:02:12
spring-security-oauth
Baeldung/spring-security-oauth
1,982
837
```java package com.baeldung.test; import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.Mockito.when; import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; import java.util.ArrayList; import java.util.List; import java.util.stream.IntStream; import org.codehaus.jackson.map.ObjectMapper; import org.codehaus.jackson.type.TypeReference; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.boot.test.mock.mockito.SpyBean; import org.springframework.security.oauth2.common.DefaultOAuth2AccessToken; import org.springframework.security.oauth2.common.OAuth2AccessToken; import org.springframework.security.oauth2.provider.token.TokenStore; import org.springframework.test.context.junit4.SpringRunner; import org.springframework.test.web.servlet.MockMvc; import com.baeldung.config.AuthorizationServerApplication; import com.baeldung.controller.TokenController; @RunWith(SpringRunner.class) @SpringBootTest(classes = { AuthorizationServerApplication.class, TokenController.class }, webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT) @AutoConfigureMockMvc public class TokenControllerIntegrationTest { @Autowired private TokenController sut; @Autowired private MockMvc mockMvc; @SpyBean private TokenStore tokenStore; private ObjectMapper mapper = new ObjectMapper(); @Test public void shouldLoadContext() { assertThat(sut).isNotNull(); } @Test public void shouldReturnEmptyListOfTokens() throws Exception { List<String> tokens = retrieveTokens(); assertThat(tokens).isEmpty(); } @Test public void shouldReturnEmptyListOfTokensWhenTokenStoreReturnNull() throws Exception { when(tokenStore.findTokensByClientId("sampleClientId")).thenReturn(null); List<String> tokens = retrieveTokens(); assertThat(tokens).isEmpty(); } @Test public void shouldReturnNotEmptyListOfTokens() throws Exception { when(tokenStore.findTokensByClientId("sampleClientId")).thenReturn(generateTokens(1)); List<String> tokens = retrieveTokens(); assertThat(tokens).hasSize(1); } @Test public void shouldReturnListOfTokens() throws Exception { when(tokenStore.findTokensByClientId("sampleClientId")).thenReturn(generateTokens(10)); List<String> tokens = retrieveTokens(); assertThat(tokens).hasSize(10); } private List<String> retrieveTokens() throws Exception { return mapper.readValue(mockMvc.perform(get("/tokens")).andExpect(status().isOk()).andReturn().getResponse().getContentAsString(), new TypeReference<List<String>>() { }); } private List<OAuth2AccessToken> generateTokens(int count) { List<OAuth2AccessToken> result = new ArrayList<>(); IntStream.range(0, count).forEach(n -> result.add(new DefaultOAuth2AccessToken("token" + n))); return result; } } ```
/content/code_sandbox/oauth-legacy/oauth-authorization-server-legacy/src/test/java/com/baeldung/test/TokenControllerIntegrationTest.java
java
2016-03-02T09:04:07
2024-08-06T03:02:12
spring-security-oauth
Baeldung/spring-security-oauth
1,982
607
```java package com.baeldung.test; import static org.hamcrest.CoreMatchers.equalTo; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertThat; import java.util.HashMap; import java.util.Map; import org.junit.Test; import io.restassured.RestAssured; import io.restassured.response.Response; // need both oauth-authorization-server-legacy and oauth-resource-server-legacy-1 to be running public class TokenRevocationLiveTest { @Test public void whenObtainingAccessToken_thenCorrect() { final Response authServerResponse = obtainAccessToken("fooClientIdPassword", "john", "123"); final String accessToken = authServerResponse.jsonPath().getString("access_token"); assertNotNull(accessToken); final Response resourceServerResponse = RestAssured.given().header("Authorization", "Bearer " + accessToken).get("path_to_url"); assertThat(resourceServerResponse.getStatusCode(), equalTo(200)); } // private Response 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); return RestAssured.given().auth().preemptive().basic(clientId, "secret").and().with().params(params).when().post("path_to_url"); // response.jsonPath().getString("refresh_token"); // response.jsonPath().getString("access_token") } private String obtainRefreshToken(String clientId, final String refreshToken) { final Map<String, String> params = new HashMap<String, String>(); params.put("grant_type", "refresh_token"); params.put("client_id", clientId); params.put("refresh_token", refreshToken); final Response response = RestAssured.given().auth().preemptive().basic(clientId, "secret").and().with().params(params).when().post("path_to_url"); return response.jsonPath().getString("access_token"); } private void authorizeClient(String clientId) { final Map<String, String> params = new HashMap<String, String>(); params.put("response_type", "code"); params.put("client_id", clientId); params.put("scope", "read,write"); final Response response = RestAssured.given().auth().preemptive().basic(clientId, "secret").and().with().params(params).when().post("path_to_url"); } } ```
/content/code_sandbox/oauth-legacy/oauth-authorization-server-legacy/src/test/java/com/baeldung/test/TokenRevocationLiveTest.java
java
2016-03-02T09:04:07
2024-08-06T03:02:12
spring-security-oauth
Baeldung/spring-security-oauth
1,982
523
```java package com.baeldung.test; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.boot.test.context.SpringBootTest.WebEnvironment; import org.springframework.test.context.junit4.SpringRunner; import com.baeldung.config.AuthorizationServerApplication; @RunWith(SpringRunner.class) @SpringBootTest(classes = AuthorizationServerApplication.class, webEnvironment = WebEnvironment.RANDOM_PORT) public class AuthServerIntegrationTest { @Test public void whenLoadApplication_thenSuccess() { } } ```
/content/code_sandbox/oauth-legacy/oauth-authorization-server-legacy/src/test/java/com/baeldung/test/AuthServerIntegrationTest.java
java
2016-03-02T09:04:07
2024-08-06T03:02:12
spring-security-oauth
Baeldung/spring-security-oauth
1,982
103
```sqlpl /* client_secret column is set as the encrypted value of "secret" - the password for the clients */ INSERT INTO oauth_client_details (client_id, client_secret, scope, authorized_grant_types, web_server_redirect_uri, authorities, access_token_validity, refresh_token_validity, additional_information, autoapprove) VALUES ('fooClientIdPassword', '$2a$10$F2dXfNuFjqezxIZp0ad5OeegW43cRdSiPgEtcetHspiNrUCi3iI6O', 'foo,read,write', 'password,authorization_code,refresh_token,client_credentials', null, null, 36000, 36000, null, true); INSERT INTO oauth_client_details (client_id, client_secret, scope, authorized_grant_types, web_server_redirect_uri, authorities, access_token_validity, refresh_token_validity, additional_information, autoapprove) VALUES ('sampleClientId', '$2a$10$F2dXfNuFjqezxIZp0ad5OeegW43cRdSiPgEtcetHspiNrUCi3iI6O', 'read,write,foo,bar', 'implicit', null, null, 36000, 36000, null, false); INSERT INTO oauth_client_details (client_id, client_secret, scope, authorized_grant_types, web_server_redirect_uri, authorities, access_token_validity, refresh_token_validity, additional_information, autoapprove) VALUES ('barClientIdPassword', '$2a$10$F2dXfNuFjqezxIZp0ad5OeegW43cRdSiPgEtcetHspiNrUCi3iI6O', 'bar,read,write', 'password,authorization_code,refresh_token', null, null, 36000, 36000, null, true); ```
/content/code_sandbox/oauth-legacy/oauth-authorization-server-legacy/src/main/resources/data.sql
sqlpl
2016-03-02T09:04:07
2024-08-06T03:02:12
spring-security-oauth
Baeldung/spring-security-oauth
1,982
411
```java package com.baeldung.model; public class Employee { private String email; private String name; public Employee() { } public Employee(String email, String name) { super(); this.email = email; this.name = name; } public String getEmail() { return email; } public void setEmail(String email) { this.email = email; } public String getName() { return name; } public void setName(String name) { this.name = name; } } ```
/content/code_sandbox/oauth-legacy/oauth-authorization-server-legacy/src/main/java/com/baeldung/model/Employee.java
java
2016-03-02T09:04:07
2024-08-06T03:02:12
spring-security-oauth
Baeldung/spring-security-oauth
1,982
113
```sqlpl --------------- H2 --------------- drop table if exists oauth_client_details; create table oauth_client_details ( client_id VARCHAR(255) PRIMARY KEY, resource_ids VARCHAR(255), client_secret VARCHAR(255), scope VARCHAR(255), authorized_grant_types VARCHAR(255), web_server_redirect_uri VARCHAR(255), authorities VARCHAR(255), access_token_validity INTEGER, refresh_token_validity INTEGER, additional_information VARCHAR(4096), autoapprove VARCHAR(255) ); create table if not exists oauth_client_token ( token_id VARCHAR(255), token LONGVARBINARY, authentication_id VARCHAR(255) PRIMARY KEY, user_name VARCHAR(255), client_id VARCHAR(255) ); create table if not exists oauth_access_token ( token_id VARCHAR(255), token LONGVARBINARY, authentication_id VARCHAR(255) PRIMARY KEY, user_name VARCHAR(255), client_id VARCHAR(255), authentication LONGVARBINARY, refresh_token VARCHAR(255) ); create table if not exists oauth_refresh_token ( token_id VARCHAR(255), token LONGVARBINARY, authentication LONGVARBINARY ); create table if not exists oauth_code ( code VARCHAR(255), authentication LONGVARBINARY ); create table if not exists oauth_approvals ( userId VARCHAR(255), clientId VARCHAR(255), scope VARCHAR(255), status VARCHAR(10), expiresAt TIMESTAMP, lastModifiedAt TIMESTAMP ); create table if not exists ClientDetails ( appId VARCHAR(255) PRIMARY KEY, resourceIds VARCHAR(255), appSecret VARCHAR(255), scope VARCHAR(255), grantTypes VARCHAR(255), redirectUrl VARCHAR(255), authorities VARCHAR(255), access_token_validity INTEGER, refresh_token_validity INTEGER, additionalInformation VARCHAR(4096), autoApproveScopes VARCHAR(255) ); --------------- MySQL --------------- --drop table if exists oauth_client_details; --create table oauth_client_details ( -- client_id VARCHAR(255) PRIMARY KEY, -- resource_ids VARCHAR(255), -- client_secret VARCHAR(255), -- scope VARCHAR(255), -- authorized_grant_types VARCHAR(255), -- web_server_redirect_uri VARCHAR(255), -- authorities VARCHAR(255), -- access_token_validity INTEGER, -- refresh_token_validity INTEGER, -- additional_information VARCHAR(4096), -- autoapprove VARCHAR(255) --); -- --create table if not exists oauth_client_token ( -- token_id VARCHAR(255), -- token LONG VARBINARY, -- authentication_id VARCHAR(255) PRIMARY KEY, -- user_name VARCHAR(255), -- client_id VARCHAR(255) --); -- --create table if not exists oauth_access_token ( -- token_id VARCHAR(255), -- token LONG VARBINARY, -- authentication_id VARCHAR(255) PRIMARY KEY, -- user_name VARCHAR(255), -- client_id VARCHAR(255), -- authentication LONG VARBINARY, -- refresh_token VARCHAR(255) --); -- --create table if not exists oauth_refresh_token ( -- token_id VARCHAR(255), -- token LONG VARBINARY, -- authentication LONG VARBINARY --); -- --create table if not exists oauth_code ( -- code VARCHAR(255), authentication LONG VARBINARY --); -- --create table if not exists oauth_approvals ( -- userId VARCHAR(255), -- clientId VARCHAR(255), -- scope VARCHAR(255), -- status VARCHAR(10), -- expiresAt TIMESTAMP, -- lastModifiedAt TIMESTAMP --); -- --create table if not exists ClientDetails ( -- appId VARCHAR(255) PRIMARY KEY, -- resourceIds VARCHAR(255), -- appSecret VARCHAR(255), -- scope VARCHAR(255), -- grantTypes VARCHAR(255), -- redirectUrl VARCHAR(255), -- authorities VARCHAR(255), -- access_token_validity INTEGER, -- refresh_token_validity INTEGER, -- additionalInformation VARCHAR(4096), -- autoApproveScopes VARCHAR(255) --); ```
/content/code_sandbox/oauth-legacy/oauth-authorization-server-legacy/src/main/resources/schema.sql
sqlpl
2016-03-02T09:04:07
2024-08-06T03:02:12
spring-security-oauth
Baeldung/spring-security-oauth
1,982
859
```java package com.baeldung.config; import java.util.Arrays; import javax.sql.DataSource; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Qualifier; import org.springframework.beans.factory.annotation.Value; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.Primary; import org.springframework.context.annotation.PropertySource; import org.springframework.core.env.Environment; import org.springframework.core.io.Resource; import org.springframework.jdbc.datasource.DriverManagerDataSource; import org.springframework.jdbc.datasource.init.DataSourceInitializer; import org.springframework.jdbc.datasource.init.DatabasePopulator; import org.springframework.jdbc.datasource.init.ResourceDatabasePopulator; import org.springframework.security.authentication.AuthenticationManager; import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder; import org.springframework.security.oauth2.config.annotation.configurers.ClientDetailsServiceConfigurer; import org.springframework.security.oauth2.config.annotation.web.configuration.AuthorizationServerConfigurerAdapter; import org.springframework.security.oauth2.config.annotation.web.configuration.EnableAuthorizationServer; import org.springframework.security.oauth2.config.annotation.web.configurers.AuthorizationServerEndpointsConfigurer; import org.springframework.security.oauth2.config.annotation.web.configurers.AuthorizationServerSecurityConfigurer; import org.springframework.security.oauth2.provider.token.DefaultTokenServices; import org.springframework.security.oauth2.provider.token.TokenEnhancer; import org.springframework.security.oauth2.provider.token.TokenEnhancerChain; import org.springframework.security.oauth2.provider.token.TokenStore; import org.springframework.security.oauth2.provider.token.store.JdbcTokenStore; //@Configuration //@PropertySource({ "classpath:persistence.properties" }) //@EnableAuthorizationServer public class OAuth2AuthorizationServerConfig extends AuthorizationServerConfigurerAdapter { @Autowired private Environment env; @Autowired @Qualifier("authenticationManagerBean") private AuthenticationManager authenticationManager; @Value("classpath:schema.sql") private Resource schemaScript; @Value("classpath:data.sql") private Resource dataScript; @Override public void configure(final AuthorizationServerSecurityConfigurer oauthServer) throws Exception { oauthServer.tokenKeyAccess("permitAll()").checkTokenAccess("isAuthenticated()"); } @Override public void configure(final ClientDetailsServiceConfigurer clients) throws Exception { clients.jdbc(dataSource()).passwordEncoder(passwordEncoder()); } @Override public void configure(final AuthorizationServerEndpointsConfigurer endpoints) throws Exception { final TokenEnhancerChain tokenEnhancerChain = new TokenEnhancerChain(); tokenEnhancerChain.setTokenEnhancers(Arrays.asList(tokenEnhancer())); endpoints.tokenStore(tokenStore()).tokenEnhancer(tokenEnhancerChain).authenticationManager(authenticationManager); } @Bean @Primary public DefaultTokenServices tokenServices() { final DefaultTokenServices defaultTokenServices = new DefaultTokenServices(); defaultTokenServices.setTokenStore(tokenStore()); defaultTokenServices.setSupportRefreshToken(true); return defaultTokenServices; } @Bean public TokenEnhancer tokenEnhancer() { return new CustomTokenEnhancer(); } // JDBC token store configuration @Bean public DataSourceInitializer dataSourceInitializer(final DataSource dataSource) { final DataSourceInitializer initializer = new DataSourceInitializer(); initializer.setDataSource(dataSource); initializer.setDatabasePopulator(databasePopulator()); return initializer; } private DatabasePopulator databasePopulator() { final ResourceDatabasePopulator populator = new ResourceDatabasePopulator(); populator.addScript(schemaScript); populator.addScript(dataScript); return populator; } @Bean public DataSource dataSource() { final DriverManagerDataSource dataSource = new DriverManagerDataSource(); dataSource.setDriverClassName(env.getProperty("jdbc.driverClassName")); dataSource.setUrl(env.getProperty("jdbc.url")); dataSource.setUsername(env.getProperty("jdbc.user")); dataSource.setPassword(env.getProperty("jdbc.pass")); return dataSource; } @Bean public TokenStore tokenStore() { return new JdbcTokenStore(dataSource()); } @Bean public BCryptPasswordEncoder passwordEncoder() { return new BCryptPasswordEncoder(); } } ```
/content/code_sandbox/oauth-legacy/oauth-authorization-server-legacy/src/main/java/com/baeldung/config/OAuth2AuthorizationServerConfig.java
java
2016-03-02T09:04:07
2024-08-06T03:02:12
spring-security-oauth
Baeldung/spring-security-oauth
1,982
808
```java package com.baeldung.config; import java.util.Arrays; import javax.sql.DataSource; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Qualifier; import org.springframework.beans.factory.annotation.Value; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.Primary; import org.springframework.context.annotation.PropertySource; import org.springframework.core.env.Environment; import org.springframework.core.io.Resource; import org.springframework.jdbc.datasource.DriverManagerDataSource; import org.springframework.jdbc.datasource.init.DataSourceInitializer; import org.springframework.jdbc.datasource.init.DatabasePopulator; import org.springframework.jdbc.datasource.init.ResourceDatabasePopulator; import org.springframework.security.authentication.AuthenticationManager; import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder; import org.springframework.security.oauth2.config.annotation.configurers.ClientDetailsServiceConfigurer; import org.springframework.security.oauth2.config.annotation.web.configuration.AuthorizationServerConfigurerAdapter; import org.springframework.security.oauth2.config.annotation.web.configuration.EnableAuthorizationServer; import org.springframework.security.oauth2.config.annotation.web.configurers.AuthorizationServerEndpointsConfigurer; import org.springframework.security.oauth2.config.annotation.web.configurers.AuthorizationServerSecurityConfigurer; import org.springframework.security.oauth2.provider.token.DefaultTokenServices; import org.springframework.security.oauth2.provider.token.TokenEnhancer; import org.springframework.security.oauth2.provider.token.TokenEnhancerChain; import org.springframework.security.oauth2.provider.token.TokenStore; import org.springframework.security.oauth2.provider.token.store.JdbcTokenStore; //@Configuration //@PropertySource({ "classpath:persistence.properties" }) //@EnableAuthorizationServer public class OAuth2AuthorizationServerConfigInMemory extends AuthorizationServerConfigurerAdapter { @Autowired private Environment env; @Autowired @Qualifier("authenticationManagerBean") private AuthenticationManager authenticationManager; @Value("classpath:schema.sql") private Resource schemaScript; @Override public void configure(final AuthorizationServerSecurityConfigurer oauthServer) throws Exception { oauthServer.tokenKeyAccess("permitAll()").checkTokenAccess("isAuthenticated()"); } @Override public void configure(final ClientDetailsServiceConfigurer clients) throws Exception {// @formatter:off clients.inMemory() .withClient("sampleClientId") .authorizedGrantTypes("implicit") .scopes("read", "write", "foo", "bar") .autoApprove(false).accessTokenValiditySeconds(3600) .and() .withClient("fooClientIdPassword") .secret(passwordEncoder().encode("secret")) .authorizedGrantTypes("password", "authorization_code", "refresh_token", "client_credentials") .scopes("foo", "read", "write") .accessTokenValiditySeconds(3600) // 1 hour .refreshTokenValiditySeconds(2592000) // 30 days .and() .withClient("barClientIdPassword") .secret(passwordEncoder().encode("secret")) .authorizedGrantTypes("password", "authorization_code", "refresh_token") .scopes("bar", "read", "write") .accessTokenValiditySeconds(3600) // 1 hour .refreshTokenValiditySeconds(2592000) // 30 days ; } // @formatter:on @Override public void configure(final AuthorizationServerEndpointsConfigurer endpoints) throws Exception { // @formatter:off final TokenEnhancerChain tokenEnhancerChain = new TokenEnhancerChain(); tokenEnhancerChain.setTokenEnhancers(Arrays.asList(tokenEnhancer())); endpoints.tokenStore(tokenStore()) // .accessTokenConverter(accessTokenConverter()) .tokenEnhancer(tokenEnhancerChain).authenticationManager(authenticationManager); // @formatter:on } /* @Bean public TokenStore tokenStore() { return new JwtTokenStore(accessTokenConverter()); } @Bean public JwtAccessTokenConverter accessTokenConverter() { final JwtAccessTokenConverter converter = new JwtAccessTokenConverter(); // converter.setSigningKey("123"); final KeyStoreKeyFactory keyStoreKeyFactory = new KeyStoreKeyFactory(new ClassPathResource("mytest.jks"), "mypass".toCharArray()); converter.setKeyPair(keyStoreKeyFactory.getKeyPair("mytest")); return converter; } */ @Bean @Primary public DefaultTokenServices tokenServices() { final DefaultTokenServices defaultTokenServices = new DefaultTokenServices(); defaultTokenServices.setTokenStore(tokenStore()); defaultTokenServices.setSupportRefreshToken(true); return defaultTokenServices; } @Bean public TokenEnhancer tokenEnhancer() { return new CustomTokenEnhancer(); } // JDBC token store configuration @Bean public DataSourceInitializer dataSourceInitializer(final DataSource dataSource) { final DataSourceInitializer initializer = new DataSourceInitializer(); initializer.setDataSource(dataSource); initializer.setDatabasePopulator(databasePopulator()); return initializer; } private DatabasePopulator databasePopulator() { final ResourceDatabasePopulator populator = new ResourceDatabasePopulator(); populator.addScript(schemaScript); return populator; } @Bean public DataSource dataSource() { final DriverManagerDataSource dataSource = new DriverManagerDataSource(); dataSource.setDriverClassName(env.getProperty("jdbc.driverClassName")); dataSource.setUrl(env.getProperty("jdbc.url")); dataSource.setUsername(env.getProperty("jdbc.user")); dataSource.setPassword(env.getProperty("jdbc.pass")); return dataSource; } @Bean public TokenStore tokenStore() { return new JdbcTokenStore(dataSource()); } @Bean public BCryptPasswordEncoder passwordEncoder() { return new BCryptPasswordEncoder(); } } ```
/content/code_sandbox/oauth-legacy/oauth-authorization-server-legacy/src/main/java/com/baeldung/config/OAuth2AuthorizationServerConfigInMemory.java
java
2016-03-02T09:04:07
2024-08-06T03:02:12
spring-security-oauth
Baeldung/spring-security-oauth
1,982
1,150
```java package com.baeldung.config; import static org.apache.commons.lang3.RandomStringUtils.randomAlphabetic; import java.util.HashMap; import java.util.Map; import org.springframework.security.oauth2.common.DefaultOAuth2AccessToken; import org.springframework.security.oauth2.common.OAuth2AccessToken; import org.springframework.security.oauth2.provider.OAuth2Authentication; import org.springframework.security.oauth2.provider.token.TokenEnhancer; public class CustomTokenEnhancer implements TokenEnhancer { @Override public OAuth2AccessToken enhance(OAuth2AccessToken accessToken, OAuth2Authentication authentication) { final Map<String, Object> additionalInfo = new HashMap<>(); additionalInfo.put("organization", authentication.getName() + randomAlphabetic(4)); ((DefaultOAuth2AccessToken) accessToken).setAdditionalInformation(additionalInfo); return accessToken; } } ```
/content/code_sandbox/oauth-legacy/oauth-authorization-server-legacy/src/main/java/com/baeldung/config/CustomTokenEnhancer.java
java
2016-03-02T09:04:07
2024-08-06T03:02:12
spring-security-oauth
Baeldung/spring-security-oauth
1,982
167
```java package com.baeldung.config; import javax.annotation.Resource; import javax.servlet.http.HttpServletRequest; import org.springframework.security.oauth2.provider.token.ConsumerTokenServices; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.ResponseBody; import org.springframework.security.oauth2.provider.endpoint.FrameworkEndpoint; @FrameworkEndpoint public class RevokeTokenEndpoint { @Resource(name = "tokenServices") ConsumerTokenServices tokenServices; @RequestMapping(method = RequestMethod.DELETE, value = "/oauth/token") @ResponseBody public void revokeToken(HttpServletRequest request) { String authorization = request.getHeader("Authorization"); if (authorization != null && authorization.contains("Bearer")) { String tokenId = authorization.substring("Bearer".length() + 1); tokenServices.revokeToken(tokenId); } } } ```
/content/code_sandbox/oauth-legacy/oauth-authorization-server-legacy/src/main/java/com/baeldung/config/RevokeTokenEndpoint.java
java
2016-03-02T09:04:07
2024-08-06T03:02:12
spring-security-oauth
Baeldung/spring-security-oauth
1,982
171
```java package com.baeldung.config; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.security.authentication.AuthenticationManager; import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder; import org.springframework.security.config.annotation.web.builders.HttpSecurity; import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter; import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder; @Configuration public class WebSecurityConfig extends WebSecurityConfigurerAdapter { @Autowired private BCryptPasswordEncoder passwordEncoder; @Autowired public void globalUserDetails(final AuthenticationManagerBuilder auth) throws Exception { // @formatter:off auth.inMemoryAuthentication() .withUser("john").password(passwordEncoder.encode("123")).roles("USER").and() .withUser("tom").password(passwordEncoder.encode("111")).roles("ADMIN").and() .withUser("user1").password(passwordEncoder.encode("pass")).roles("USER").and() .withUser("admin").password(passwordEncoder.encode("nimda")).roles("ADMIN"); }// @formatter:on @Override @Bean public AuthenticationManager authenticationManagerBean() throws Exception { return super.authenticationManagerBean(); } @Override protected void configure(final HttpSecurity http) throws Exception { // @formatter:off http.authorizeRequests().antMatchers("/login").permitAll() .antMatchers("/oauth/token/revokeById/**").permitAll() .antMatchers("/tokens/**").permitAll() .anyRequest().authenticated() .and().formLogin().permitAll() .and().csrf().disable(); // @formatter:on } } ```
/content/code_sandbox/oauth-legacy/oauth-authorization-server-legacy/src/main/java/com/baeldung/config/WebSecurityConfig.java
java
2016-03-02T09:04:07
2024-08-06T03:02:12
spring-security-oauth
Baeldung/spring-security-oauth
1,982
353
```java package com.baeldung.config; import java.util.ArrayList; import java.util.List; import org.springframework.http.HttpStatus; import org.springframework.http.MediaType; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.ResponseBody; import org.springframework.web.bind.annotation.ResponseStatus; import com.baeldung.model.Employee; import java.util.Optional; @Controller public class EmployeeController { private List<Employee> employees = new ArrayList<>(); @GetMapping("/employee") @ResponseBody public Optional<Employee> getEmployee(@RequestParam String email) { return employees.stream().filter(x -> x.getEmail().equals(email)).findAny(); } @PostMapping(value = "/employee", consumes = MediaType.APPLICATION_JSON_VALUE) @ResponseStatus(HttpStatus.CREATED) public void postMessage(@RequestBody Employee employee) { employees.add(employee); } } ```
/content/code_sandbox/oauth-legacy/oauth-authorization-server-legacy/src/main/java/com/baeldung/config/EmployeeController.java
java
2016-03-02T09:04:07
2024-08-06T03:02:12
spring-security-oauth
Baeldung/spring-security-oauth
1,982
197
```java package com.baeldung.config; import java.util.Arrays; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Qualifier; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.Primary; import org.springframework.security.authentication.AuthenticationManager; import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder; import org.springframework.security.oauth2.config.annotation.configurers.ClientDetailsServiceConfigurer; import org.springframework.security.oauth2.config.annotation.web.configuration.AuthorizationServerConfigurerAdapter; import org.springframework.security.oauth2.config.annotation.web.configuration.EnableAuthorizationServer; import org.springframework.security.oauth2.config.annotation.web.configurers.AuthorizationServerEndpointsConfigurer; import org.springframework.security.oauth2.config.annotation.web.configurers.AuthorizationServerSecurityConfigurer; import org.springframework.security.oauth2.provider.token.DefaultTokenServices; import org.springframework.security.oauth2.provider.token.TokenEnhancer; import org.springframework.security.oauth2.provider.token.TokenEnhancerChain; import org.springframework.security.oauth2.provider.token.TokenStore; import org.springframework.security.oauth2.provider.token.store.JwtAccessTokenConverter; import org.springframework.security.oauth2.provider.token.store.JwtTokenStore; @Configuration @EnableAuthorizationServer public class OAuth2AuthorizationServerConfigJwt extends AuthorizationServerConfigurerAdapter { @Autowired @Qualifier("authenticationManagerBean") private AuthenticationManager authenticationManager; @Override public void configure(final AuthorizationServerSecurityConfigurer oauthServer) throws Exception { oauthServer.tokenKeyAccess("permitAll()").checkTokenAccess("isAuthenticated()"); } @Override public void configure(final ClientDetailsServiceConfigurer clients) throws Exception { // @formatter:off clients.inMemory() .withClient("sampleClientId") .authorizedGrantTypes("implicit") .scopes("read", "write", "foo", "bar") .autoApprove(false) .accessTokenValiditySeconds(3600) .redirectUris("path_to_url","path_to_url") .and() .withClient("fooClientIdPassword") .secret(passwordEncoder().encode("secret")) .authorizedGrantTypes("password", "authorization_code", "refresh_token", "client_credentials") .scopes("foo", "read", "write") .accessTokenValiditySeconds(3600) // 1 hour .refreshTokenValiditySeconds(2592000) // 30 days .redirectUris("path_to_url","path_to_url","path_to_url", "path_to_url", "path_to_url", "path_to_url", "path_to_url") .and() .withClient("barClientIdPassword") .secret(passwordEncoder().encode("secret")) .authorizedGrantTypes("password", "authorization_code", "refresh_token") .scopes("bar", "read", "write") .accessTokenValiditySeconds(3600) // 1 hour .refreshTokenValiditySeconds(2592000) // 30 days .and() .withClient("testImplicitClientId") .authorizedGrantTypes("implicit") .scopes("read", "write", "foo", "bar") .autoApprove(true) .redirectUris("path_to_url"); } // @formatter:on @Bean @Primary public DefaultTokenServices tokenServices() { final DefaultTokenServices defaultTokenServices = new DefaultTokenServices(); defaultTokenServices.setTokenStore(tokenStore()); defaultTokenServices.setSupportRefreshToken(true); return defaultTokenServices; } @Override public void configure(final AuthorizationServerEndpointsConfigurer endpoints) throws Exception { final TokenEnhancerChain tokenEnhancerChain = new TokenEnhancerChain(); tokenEnhancerChain.setTokenEnhancers(Arrays.asList(tokenEnhancer(), accessTokenConverter())); endpoints.tokenStore(tokenStore()).tokenEnhancer(tokenEnhancerChain).authenticationManager(authenticationManager); } @Bean public TokenStore tokenStore() { return new JwtTokenStore(accessTokenConverter()); } @Bean public JwtAccessTokenConverter accessTokenConverter() { final JwtAccessTokenConverter converter = new JwtAccessTokenConverter(); converter.setSigningKey("123"); // final KeyStoreKeyFactory keyStoreKeyFactory = new KeyStoreKeyFactory(new ClassPathResource("mytest.jks"), "mypass".toCharArray()); // converter.setKeyPair(keyStoreKeyFactory.getKeyPair("mytest")); return converter; } @Bean public TokenEnhancer tokenEnhancer() { return new CustomTokenEnhancer(); } @Bean public BCryptPasswordEncoder passwordEncoder() { return new BCryptPasswordEncoder(); } } ```
/content/code_sandbox/oauth-legacy/oauth-authorization-server-legacy/src/main/java/com/baeldung/config/OAuth2AuthorizationServerConfigJwt.java
java
2016-03-02T09:04:07
2024-08-06T03:02:12
spring-security-oauth
Baeldung/spring-security-oauth
1,982
955
```java package com.baeldung.config; import org.springframework.context.annotation.Configuration; import org.springframework.security.config.annotation.web.builders.HttpSecurity; import org.springframework.security.oauth2.config.annotation.web.configuration.EnableResourceServer; import org.springframework.security.oauth2.config.annotation.web.configuration.ResourceServerConfigurerAdapter; import org.springframework.context.annotation.Profile; @EnableResourceServer @Configuration @Profile("mvc") // This isn't the main/standard Resource Server of the project (that's in a different module) // This is the Resource Server for the Testing OAuth2 with Spring MVC article: path_to_url // Notice that it's only active via the mvc profile public class OAuth2ResourceServerConfig extends ResourceServerConfigurerAdapter { @Override public void configure(HttpSecurity http) throws Exception { http.authorizeRequests().antMatchers("/employee").hasRole("ADMIN"); } } ```
/content/code_sandbox/oauth-legacy/oauth-authorization-server-legacy/src/main/java/com/baeldung/config/OAuth2ResourceServerConfig.java
java
2016-03-02T09:04:07
2024-08-06T03:02:12
spring-security-oauth
Baeldung/spring-security-oauth
1,982
174
```java package com.baeldung.config; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.boot.web.servlet.support.SpringBootServletInitializer; @SpringBootApplication(scanBasePackages = "com.baeldung") public class AuthorizationServerApplication extends SpringBootServletInitializer { public static void main(String[] args) { SpringApplication.run(AuthorizationServerApplication.class, args); } } ```
/content/code_sandbox/oauth-legacy/oauth-authorization-server-legacy/src/main/java/com/baeldung/config/AuthorizationServerApplication.java
java
2016-03-02T09:04:07
2024-08-06T03:02:12
spring-security-oauth
Baeldung/spring-security-oauth
1,982
80
```java package com.baeldung.controller; import java.util.Collection; import java.util.Collections; import java.util.List; import java.util.Optional; import java.util.stream.Collectors; import javax.annotation.Resource; import javax.servlet.http.HttpServletRequest; import org.springframework.security.oauth2.common.OAuth2AccessToken; import org.springframework.security.oauth2.provider.token.ConsumerTokenServices; import org.springframework.security.oauth2.provider.token.TokenStore; import org.springframework.security.oauth2.provider.token.store.JdbcTokenStore; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.ResponseBody; @Controller public class TokenController { @Resource(name = "tokenServices") private ConsumerTokenServices tokenServices; @Resource(name = "tokenStore") private TokenStore tokenStore; @RequestMapping(method = RequestMethod.POST, value = "/oauth/token/revokeById/{tokenId}") @ResponseBody public void revokeToken(HttpServletRequest request, @PathVariable String tokenId) { tokenServices.revokeToken(tokenId); } @RequestMapping(method = RequestMethod.GET, value = "/tokens") @ResponseBody public List<String> getTokens() { Collection<OAuth2AccessToken> tokens = tokenStore.findTokensByClientId("sampleClientId"); return Optional.ofNullable(tokens).orElse(Collections.emptyList()).stream().map(OAuth2AccessToken::getValue).collect(Collectors.toList()); } @RequestMapping(method = RequestMethod.POST, value = "/tokens/revokeRefreshToken/{tokenId:.*}") @ResponseBody public String revokeRefreshToken(@PathVariable String tokenId) { if (tokenStore instanceof JdbcTokenStore) { ((JdbcTokenStore) tokenStore).removeRefreshToken(tokenId); } return tokenId; } } ```
/content/code_sandbox/oauth-legacy/oauth-authorization-server-legacy/src/main/java/com/baeldung/controller/TokenController.java
java
2016-03-02T09:04:07
2024-08-06T03:02:12
spring-security-oauth
Baeldung/spring-security-oauth
1,982
366
```java package com.baeldung.live; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; import io.restassured.RestAssured; import io.restassured.response.Response; import java.util.HashMap; import java.util.Map; import org.junit.Test; import org.springframework.http.MediaType; //Before running this live test make sure both authorization server and first resource server are running public class PasswordFlowLiveTest { @Test public void givenUser_whenUseFooClient_thenOkForFooResourceOnly() { final String accessToken = obtainAccessToken("fooClientIdPassword", "john", "123"); final Response fooResponse = RestAssured.given().header("Authorization", "Bearer " + accessToken) .get("path_to_url"); assertEquals(200, fooResponse.getStatusCode()); assertNotNull(fooResponse.jsonPath().get("name")); final Response barResponse = RestAssured.given().header("Authorization", "Bearer " + accessToken) .get("path_to_url"); assertEquals(403, barResponse.getStatusCode()); } @Test public void givenUser_whenUseBarClient_thenOkForBarResourceReadOnly() { final String accessToken = obtainAccessToken("barClientIdPassword", "john", "123"); final Response fooResponse = RestAssured.given().header("Authorization", "Bearer " + accessToken) .get("path_to_url"); assertEquals(403, fooResponse.getStatusCode()); final Response barReadResponse = RestAssured.given().header("Authorization", "Bearer " + accessToken) .get("path_to_url"); assertEquals(200, barReadResponse.getStatusCode()); assertNotNull(barReadResponse.jsonPath().get("name")); final Response barWritResponse = RestAssured.given().contentType(MediaType.APPLICATION_JSON_VALUE) .header("Authorization", "Bearer " + accessToken).body("{\"id\":1,\"name\":\"MyBar\"}") .post("path_to_url"); assertEquals(403, barWritResponse.getStatusCode()); } @Test public void givenAdmin_whenUseBarClient_thenOkForBarResourceReadWrite() { final String accessToken = obtainAccessToken("barClientIdPassword", "tom", "111"); final Response fooResponse = RestAssured.given().header("Authorization", "Bearer " + accessToken) .get("path_to_url"); assertEquals(403, fooResponse.getStatusCode()); final Response barResponse = RestAssured.given().header("Authorization", "Bearer " + accessToken) .get("path_to_url"); assertEquals(200, barResponse.getStatusCode()); assertNotNull(barResponse.jsonPath().get("name")); final Response barWritResponse = RestAssured.given().contentType(MediaType.APPLICATION_JSON_VALUE) .header("Authorization", "Bearer " + accessToken).body("{\"id\":1,\"name\":\"MyBar\"}") .post("path_to_url"); assertEquals(201, barWritResponse.getStatusCode()); assertEquals("MyBar", barWritResponse.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); final Response response = RestAssured.given().auth().preemptive().basic(clientId, "secret").and().with() .params(params).when().post("path_to_url"); return response.jsonPath().getString("access_token"); } } ```
/content/code_sandbox/oauth-legacy/oauth-resource-server-legacy-1/src/test/java/com/baeldung/live/PasswordFlowLiveTest.java
java
2016-03-02T09:04:07
2024-08-06T03:02:12
spring-security-oauth
Baeldung/spring-security-oauth
1,982
736
```java package com.baeldung.live; 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 first resource server are running public class ImplicitFlowLiveTest { public final static String AUTH_SERVER = "path_to_url"; public final static String RESOURCE_SERVER = "path_to_url"; @Test public void givenUser_whenUseFooClient_thenOkForFooResourceOnly() { final String accessToken = obtainAccessToken("testImplicitClientId", "john", "123"); final Response fooResponse = RestAssured.given().header("Authorization", "Bearer " + accessToken).get(RESOURCE_SERVER + "/foos/1"); assertEquals(200, fooResponse.getStatusCode()); assertNotNull(fooResponse.jsonPath().get("name")); } private String obtainAccessToken(String clientId, String username, String password) { final String redirectUrl = "path_to_url"; final String authorizeUrl = AUTH_SERVER + "/oauth/authorize"; // user login Response response = RestAssured.given().formParams("username", username, "password", password).post(AUTH_SERVER + "/login"); final String cookieValue = response.getCookie("JSESSIONID"); // get access token final Map<String, String> params = new HashMap<String, String>(); params.put("response_type", "token"); params.put("client_id", clientId); params.put("redirect_uri", redirectUrl); response = RestAssured.given().cookie("JSESSIONID", cookieValue).formParams(params).post(authorizeUrl); final String location = response.getHeader(HttpHeaders.LOCATION); System.out.println("Location => " + location); assertEquals(HttpStatus.FOUND.value(), response.getStatusCode()); final String accessToken = location.split("#|=|&")[2]; return accessToken; } } ```
/content/code_sandbox/oauth-legacy/oauth-resource-server-legacy-1/src/test/java/com/baeldung/live/ImplicitFlowLiveTest.java
java
2016-03-02T09:04:07
2024-08-06T03:02:12
spring-security-oauth
Baeldung/spring-security-oauth
1,982
432
```java package com.baeldung.live; 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 first 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"; @Test public void givenUser_whenUseFooClient_thenOkForFooResourceOnly() { final String accessToken = obtainAccessTokenWithAuthorizationCode("fooClientIdPassword", "john", "123"); final Response fooResponse = RestAssured.given().header("Authorization", "Bearer " + accessToken).get(RESOURCE_SERVER + "/foos/1"); assertEquals(200, fooResponse.getStatusCode()); assertNotNull(fooResponse.jsonPath().get("name")); final Response barResponse = RestAssured.given().header("Authorization", "Bearer " + accessToken).get(RESOURCE_SERVER + "/bars/1"); assertEquals(403, barResponse.getStatusCode()); } private String obtainAccessTokenWithAuthorizationCode(String clientId, String username, String password) { final String redirectUrl = "path_to_url"; final String authorizeUrl = AUTH_SERVER + "/oauth/authorize?response_type=code&client_id=" + clientId + "&redirect_uri=" + redirectUrl; final String tokenUrl = AUTH_SERVER + "/oauth/token"; // user login Response response = RestAssured.given().formParams("username", username, "password", password).post(AUTH_SERVER + "/login"); final String cookieValue = response.getCookie("JSESSIONID"); // get authorization code System.out.println(RestAssured.given().cookie("JSESSIONID", cookieValue).get(authorizeUrl).asString()); Map<String, String> params = new HashMap<String, String>(); params.put("user_oauth_approval", "true"); params.put("authorize", "Authorize"); params.put("scope.read", "true"); params.put("scope.foo", "true"); response = RestAssured.given().cookie("JSESSIONID", cookieValue).formParams(params).post(authorizeUrl); assertEquals(HttpStatus.FOUND.value(), response.getStatusCode()); final String location = response.getHeader(HttpHeaders.LOCATION); final String code = location.substring(location.indexOf("code=") + 5); // get access token params = new HashMap<String, String>(); params.put("grant_type", "authorization_code"); params.put("code", code); params.put("client_id", clientId); params.put("redirect_uri", redirectUrl); response = RestAssured.given().auth().basic(clientId, "secret").formParams(params).post(tokenUrl); return response.jsonPath().getString("access_token"); } } ```
/content/code_sandbox/oauth-legacy/oauth-resource-server-legacy-1/src/test/java/com/baeldung/live/AuthorizationCodeLiveTest.java
java
2016-03-02T09:04:07
2024-08-06T03:02:12
spring-security-oauth
Baeldung/spring-security-oauth
1,982
626
```java package com.baeldung.test; import static org.junit.Assert.assertTrue; import io.restassured.RestAssured; import io.restassured.response.Response; import java.util.HashMap; import java.util.Map; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.boot.test.context.SpringBootTest.WebEnvironment; import org.springframework.security.oauth2.provider.OAuth2Authentication; import org.springframework.security.oauth2.provider.token.store.JwtTokenStore; import org.springframework.test.context.junit4.SpringRunner; import com.baeldung.config.ResourceServerApplication; //Before running this test make sure authorization server is running @RunWith(SpringRunner.class) @SpringBootTest(classes = ResourceServerApplication.class, webEnvironment = WebEnvironment.RANDOM_PORT) public class AuthenticationClaimsIntegrationTest { @Autowired private JwtTokenStore tokenStore; @Test public void whenTokenDontContainIssuer_thenSuccess() { final String tokenValue = obtainAccessToken("fooClientIdPassword", "john", "123"); final OAuth2Authentication auth = tokenStore.readAuthentication(tokenValue); System.out.println(tokenValue); System.out.println(auth); assertTrue(auth.isAuthenticated()); System.out.println(auth.getDetails()); Map<String, Object> details = (Map<String, Object>) auth.getDetails(); assertTrue(details.containsKey("organization")); System.out.println(details.get("organization")); } 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); final Response response = RestAssured.given().auth().preemptive().basic(clientId, "secret").and().with().params(params).when().post("path_to_url"); return response.jsonPath().getString("access_token"); } } ```
/content/code_sandbox/oauth-legacy/oauth-resource-server-legacy-1/src/test/java/com/baeldung/test/AuthenticationClaimsIntegrationTest.java
java
2016-03-02T09:04:07
2024-08-06T03:02:12
spring-security-oauth
Baeldung/spring-security-oauth
1,982
408
```java package com.baeldung.config; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Primary; import org.springframework.security.config.annotation.web.builders.HttpSecurity; import org.springframework.security.config.http.SessionCreationPolicy; import org.springframework.security.oauth2.config.annotation.web.configuration.ResourceServerConfigurerAdapter; import org.springframework.security.oauth2.provider.token.RemoteTokenServices; //@Configuration //@EnableResourceServer public class OAuth2ResourceServerConfigRemoteTokenService extends ResourceServerConfigurerAdapter { @Override public void configure(final HttpSecurity http) throws Exception { // @formatter:off http.sessionManagement().sessionCreationPolicy(SessionCreationPolicy.IF_REQUIRED) .and() .authorizeRequests().anyRequest().permitAll(); // @formatter:on } @Primary @Bean public RemoteTokenServices tokenServices() { final RemoteTokenServices tokenService = new RemoteTokenServices(); tokenService.setCheckTokenEndpointUrl("path_to_url"); tokenService.setClientId("fooClientIdPassword"); tokenService.setClientSecret("secret"); return tokenService; } } ```
/content/code_sandbox/oauth-legacy/oauth-resource-server-legacy-1/src/main/java/com/baeldung/config/OAuth2ResourceServerConfigRemoteTokenService.java
java
2016-03-02T09:04:07
2024-08-06T03:02:12
spring-security-oauth
Baeldung/spring-security-oauth
1,982
225
```java package com.baeldung.config; import java.util.Map; import org.springframework.security.oauth2.provider.OAuth2Authentication; import org.springframework.security.oauth2.provider.token.DefaultAccessTokenConverter; import org.springframework.stereotype.Component; @Component public class CustomAccessTokenConverter extends DefaultAccessTokenConverter { @Override public OAuth2Authentication extractAuthentication(Map<String, ?> claims) { OAuth2Authentication authentication = super.extractAuthentication(claims); authentication.setDetails(claims); return authentication; } } ```
/content/code_sandbox/oauth-legacy/oauth-resource-server-legacy-1/src/main/java/com/baeldung/config/CustomAccessTokenConverter.java
java
2016-03-02T09:04:07
2024-08-06T03:02:12
spring-security-oauth
Baeldung/spring-security-oauth
1,982
99
```java package com.baeldung.config; import org.springframework.context.annotation.ComponentScan; import org.springframework.context.annotation.Configuration; import org.springframework.web.servlet.config.annotation.EnableWebMvc; import org.springframework.web.servlet.config.annotation.WebMvcConfigurer; @Configuration @EnableWebMvc @ComponentScan({ "com.baeldung.web.controller" }) public class ResourceServerWebConfig implements WebMvcConfigurer { // } ```
/content/code_sandbox/oauth-legacy/oauth-resource-server-legacy-1/src/main/java/com/baeldung/config/ResourceServerWebConfig.java
java
2016-03-02T09:04:07
2024-08-06T03:02:12
spring-security-oauth
Baeldung/spring-security-oauth
1,982
77
```java package com.baeldung.config; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.Primary; import org.springframework.security.config.annotation.web.builders.HttpSecurity; import org.springframework.security.config.http.SessionCreationPolicy; import org.springframework.security.oauth2.config.annotation.web.configuration.EnableResourceServer; import org.springframework.security.oauth2.config.annotation.web.configuration.ResourceServerConfigurerAdapter; import org.springframework.security.oauth2.config.annotation.web.configurers.ResourceServerSecurityConfigurer; import org.springframework.security.oauth2.provider.token.DefaultTokenServices; import org.springframework.security.oauth2.provider.token.TokenStore; import org.springframework.security.oauth2.provider.token.store.JwtAccessTokenConverter; import org.springframework.security.oauth2.provider.token.store.JwtTokenStore; @Configuration @EnableResourceServer public class OAuth2ResourceServerConfigJwt extends ResourceServerConfigurerAdapter { @Autowired private CustomAccessTokenConverter customAccessTokenConverter; @Override public void configure(final HttpSecurity http) throws Exception { // @formatter:off http.sessionManagement().sessionCreationPolicy(SessionCreationPolicy.IF_REQUIRED) .and() .authorizeRequests().anyRequest().permitAll(); // @formatter:on } @Override public void configure(final ResourceServerSecurityConfigurer config) { config.tokenServices(tokenServices()); } @Bean public TokenStore tokenStore() { return new JwtTokenStore(accessTokenConverter()); } @Bean public JwtAccessTokenConverter accessTokenConverter() { final JwtAccessTokenConverter converter = new JwtAccessTokenConverter(); converter.setAccessTokenConverter(customAccessTokenConverter); converter.setSigningKey("123"); // final Resource resource = new ClassPathResource("public.txt"); // String publicKey = null; // try { // publicKey = IOUtils.toString(resource.getInputStream()); // } catch (final IOException e) { // throw new RuntimeException(e); // } // converter.setVerifierKey(publicKey); return converter; } @Bean @Primary public DefaultTokenServices tokenServices() { final DefaultTokenServices defaultTokenServices = new DefaultTokenServices(); defaultTokenServices.setTokenStore(tokenStore()); return defaultTokenServices; } } ```
/content/code_sandbox/oauth-legacy/oauth-resource-server-legacy-1/src/main/java/com/baeldung/config/OAuth2ResourceServerConfigJwt.java
java
2016-03-02T09:04:07
2024-08-06T03:02:12
spring-security-oauth
Baeldung/spring-security-oauth
1,982
459
```java package com.baeldung.config; import javax.sql.DataSource; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Primary; import org.springframework.core.env.Environment; import org.springframework.jdbc.datasource.DriverManagerDataSource; import org.springframework.security.config.annotation.web.builders.HttpSecurity; import org.springframework.security.config.http.SessionCreationPolicy; import org.springframework.security.oauth2.config.annotation.web.configuration.ResourceServerConfigurerAdapter; import org.springframework.security.oauth2.config.annotation.web.configurers.ResourceServerSecurityConfigurer; import org.springframework.security.oauth2.provider.token.DefaultTokenServices; import org.springframework.security.oauth2.provider.token.TokenStore; import org.springframework.security.oauth2.provider.token.store.JdbcTokenStore; //@Configuration //@PropertySource({ "classpath:persistence.properties" }) //@EnableResourceServer public class OAuth2ResourceServerConfig extends ResourceServerConfigurerAdapter { @Autowired private Environment env; // @Override public void configure(final HttpSecurity http) throws Exception { // @formatter:off http.sessionManagement().sessionCreationPolicy(SessionCreationPolicy.IF_REQUIRED) .and() .authorizeRequests().anyRequest().permitAll(); // @formatter:on } @Override public void configure(final ResourceServerSecurityConfigurer config) { config.tokenServices(tokenServices()); } @Bean @Primary public DefaultTokenServices tokenServices() { final DefaultTokenServices defaultTokenServices = new DefaultTokenServices(); defaultTokenServices.setTokenStore(tokenStore()); return defaultTokenServices; } // JDBC token store configuration @Bean public DataSource dataSource() { final DriverManagerDataSource dataSource = new DriverManagerDataSource(); dataSource.setDriverClassName(env.getProperty("jdbc.driverClassName")); dataSource.setUrl(env.getProperty("jdbc.url")); dataSource.setUsername(env.getProperty("jdbc.user")); dataSource.setPassword(env.getProperty("jdbc.pass")); return dataSource; } @Bean public TokenStore tokenStore() { return new JdbcTokenStore(dataSource()); } } ```
/content/code_sandbox/oauth-legacy/oauth-resource-server-legacy-1/src/main/java/com/baeldung/config/OAuth2ResourceServerConfig.java
java
2016-03-02T09:04:07
2024-08-06T03:02:12
spring-security-oauth
Baeldung/spring-security-oauth
1,982
414
```java package com.baeldung.web.controller; import java.util.Map; import org.springframework.security.access.prepost.PreAuthorize; import org.springframework.security.core.Authentication; import org.springframework.security.oauth2.provider.authentication.OAuth2AuthenticationDetails; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.ResponseBody; @Controller public class UserController { @PreAuthorize("#oauth2.hasScope('read')") @RequestMapping(method = RequestMethod.GET, value = "/users/extra") @ResponseBody public Map<String, Object> getExtraInfo(Authentication auth) { OAuth2AuthenticationDetails oauthDetails = (OAuth2AuthenticationDetails) auth.getDetails(); Map<String, Object> details = (Map<String, Object>) oauthDetails.getDecodedDetails(); System.out.println("User organization is " + details.get("organization")); return details; } } ```
/content/code_sandbox/oauth-legacy/oauth-resource-server-legacy-1/src/main/java/com/baeldung/web/controller/UserController.java
java
2016-03-02T09:04:07
2024-08-06T03:02:12
spring-security-oauth
Baeldung/spring-security-oauth
1,982
188
```html <div> <nav class="navbar navbar-default"> <div class="container-fluid"> <div class="navbar-header"> <a class="navbar-brand" th:href="@{/}">Spring Security OAuth</a> </div> </div><!-- /.container-fluid --> </nav> <oauth site="path_to_url" client-id="sampleClientId" redirect-uri="path_to_url" scope="read write foo bar" template="oauthTemp"> </oauth> <script src="path_to_url"></script> <script src="path_to_url"></script> <script src="path_to_url"></script> <script src="path_to_url"></script> <script th:src="@{/resources/oauth-ng.js}"></script> <script> /*<![CDATA[*/ var app = angular.module('myApp', ["ngResource","ngRoute","oauth"]); app.config(function($locationProvider) { $locationProvider.html5Mode({ enabled: true, requireBase: false }).hashPrefix('!'); }); app.config(['$httpProvider', function ($httpProvider) { $httpProvider.interceptors.push(function ($q,$rootScope) { return { 'responseError': function (responseError) { $rootScope.message = responseError.statusText; console.log("error here"); console.log(responseError); return $q.reject(responseError); } }; }); }]); app.controller('mainCtrl', function($scope,$resource,$http,$rootScope) { $scope.$on('oauth:login', function(event, token) { $http.defaults.headers.common.Authorization= 'Bearer ' + token.access_token; console.log('Authorized third party app with token', token.access_token); $scope.token=token.access_token; }); $scope.foo = {id:0 , name:"sample foo"}; $scope.foos = $resource("path_to_url",{fooId:'@id'}); $scope.getFoo = function(){ $scope.foo = $scope.foos.get({fooId:$scope.foo.id}); } $scope.createFoo = function(){ if($scope.foo.name.length==0) { $rootScope.message = "Foo name can not be empty"; return; } $scope.foo.id = null; $scope.foo = $scope.foos.save($scope.foo, function(){ $rootScope.message = "Foo Created Successfully"; }); } // bar $scope.bar = {id:0 , name:"sample bar"}; $scope.bars = $resource("path_to_url",{barId:'@id'}); $scope.getBar = function(){ $scope.bar = $scope.bars.get({barId:$scope.bar.id}); } $scope.createBar = function(){ if($scope.bar.name.length==0) { $rootScope.message = "Bar name can not be empty"; return; } $scope.bar.id = null; $scope.bar = $scope.bars.save($scope.bar, function(){ $rootScope.message = "Bar Created Successfully"; }); } $scope.revokeToken = $resource("path_to_url",{tokenId:'@tokenId'}); $scope.tokens = $resource("path_to_url"); $scope.getTokens = function(){ $scope.tokenList = $scope.tokens.query(); } $scope.revokeAccessToken = function(){ if ($scope.tokenToRevoke && $scope.tokenToRevoke.length !=0){ $scope.revokeToken.save({tokenId:$scope.tokenToRevoke}); $rootScope.message="Token:"+$scope.tokenToRevoke+" was revoked!"; $scope.tokenToRevoke=""; } } }); /*]]>*/ </script> </div> ```
/content/code_sandbox/oauth-legacy/oauth-ui-implicit-angularjs-legacy/src/main/resources/templates/header.html
html
2016-03-02T09:04:07
2024-08-06T03:02:12
spring-security-oauth
Baeldung/spring-security-oauth
1,982
795
```html <div class="container"> <span class="col-sm-12"> <a href="#" class="btn btn-primary btn-lg" ng-show="show=='logged-out'" ng-click="login()">Login</a> <a href="#" class="btn btn-primary btn-lg" ng-show="show=='denied'" ng-click="login()">Access denied. Try again.</a> <a href="#" class="btn btn-primary btn-lg" ng-show="show=='logged-in'" ng-click="logout()">Logout.</a> </span> </div> ```
/content/code_sandbox/oauth-legacy/oauth-ui-implicit-angularjs-legacy/src/main/resources/templates/oauthTemp.html
html
2016-03-02T09:04:07
2024-08-06T03:02:12
spring-security-oauth
Baeldung/spring-security-oauth
1,982
121
```html <!DOCTYPE html> <html lang="en"> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <title>Spring Security OAuth</title> <link rel="stylesheet" href="path_to_url"/> </head> <body ng-app="myApp" ng-controller="mainCtrl"> <div th:include="header"></div> <div class="container"> <div class="alert alert-info" ng-show="message">{{message}}</div> <h1>Foo Details</h1> <div class="col-sm-6"> <div class="col-sm-12"> <label class="col-sm-2">ID</label> <span class="col-sm-10"><input class="form-control" ng-model="foo.id"/></span> </div> <div class="col-sm-12"> <label class="col-sm-2">Name</label> <span class="col-sm-10"><input class="form-control" ng-model="foo.name"/></span> </div> <div class="col-sm-12"> <a class="btn btn-default" href="#" ng-click="getFoo()">Get Foo</a> <a class="btn btn-default" href="#" ng-click="createFoo()">Create Foo</a> </div> </div> <br/> <hr/> <br/> <br/> <br/> <h1>Bar Details</h1> <div class="col-sm-6"> <div class="col-sm-12"> <label class="col-sm-2">ID</label> <span class="col-sm-10"><input class="form-control" ng-model="bar.id"/></span> </div> <div class="col-sm-12"> <label class="col-sm-2">Name</label> <span class="col-sm-10"><input class="form-control" ng-model="bar.name"/></span> </div> <div class="col-sm-12"> <a class="btn btn-default" href="#" ng-click="getBar()">Get Bar</a> <a class="btn btn-default" href="#" ng-click="createBar()">Create Bar</a> </div> <br/><br/><br/><br/> <a class="btn btn-info" href="#" ng-click="getTokens()">Get tokens</a> <br/> Valid tokens: <ul> <li ng-repeat="token in tokenList">{{token}}</li> </ul> Your current token: {{token}} <br/><br /> <label class="col-sm-2">Token to revoke:</label> <span class="col-sm-10"><input class="form-control" ng-model="tokenToRevoke"/></span> <a class="btn btn-info" href="#" ng-click="revokeAccessToken()">Revoke Token</a> </div> </div> </body> </html> ```
/content/code_sandbox/oauth-legacy/oauth-ui-implicit-angularjs-legacy/src/main/resources/templates/index.html
html
2016-03-02T09:04:07
2024-08-06T03:02:12
spring-security-oauth
Baeldung/spring-security-oauth
1,982
572
```javascript /* oauth-ng - v0.4.2 - 2015-08-27 */ 'use strict'; // App libraries angular.module('oauth', [ 'oauth.directive', // login directive 'oauth.accessToken', // access token service 'oauth.endpoint', // oauth endpoint service 'oauth.profile', // profile model 'oauth.storage', // storage 'oauth.interceptor', // bearer token interceptor 'oauth.configuration' // token appender ]) .config(['$locationProvider','$httpProvider', function($locationProvider, $httpProvider) { $httpProvider.interceptors.push('ExpiredInterceptor'); }]); 'use strict'; var accessTokenService = angular.module('oauth.accessToken', []); accessTokenService.factory('AccessToken', ['Storage', '$rootScope', '$location', '$interval', function(Storage, $rootScope, $location, $interval){ var service = { token: null }, oAuth2HashTokens = [ //per path_to_url#section-4.2.2 'access_token', 'token_type', 'expires_in', 'scope', 'state', 'error','error_description' ]; /** * Returns the access token. */ service.get = function(){ return this.token; }; /** * Sets and returns the access token. It tries (in order) the following strategies: * - takes the token from the fragment URI * - takes the token from the sessionStorage */ service.set = function(){ this.setTokenFromString($location.hash()); //If hash is present in URL always use it, cuz its coming from oAuth2 provider redirect if(null === service.token){ setTokenFromSession(); } return this.token; }; /** * Delete the access token and remove the session. * @returns {null} */ service.destroy = function(){ Storage.delete('token'); this.token = null; return this.token; }; /** * Tells if the access token is expired. */ service.expired = function(){ return (this.token && this.token.expires_at && new Date(this.token.expires_at) < new Date()); }; /** * Get the access token from a string and save it * @param hash */ service.setTokenFromString = function(hash){ var params = getTokenFromString(hash); if(params){ removeFragment(); setToken(params); setExpiresAt(); // We have to save it again to make sure expires_at is set // and the expiry event is set up properly setToken(this.token); $rootScope.$broadcast('oauth:login', service.token); } }; /* * * * * * * * * * * PRIVATE METHODS * * * * * * * * * * */ /** * Set the access token from the sessionStorage. */ var setTokenFromSession = function(){ var params = Storage.get('token'); if (params) { setToken(params); } }; /** * Set the access token. * * @param params * @returns {*|{}} */ var setToken = function(params){ service.token = service.token || {}; // init the token angular.extend(service.token, params); // set the access token params setTokenInSession(); // save the token into the session setExpiresAtEvent(); // event to fire when the token expires return service.token; }; /** * Parse the fragment URI and return an object * @param hash * @returns {{}} */ var getTokenFromString = function(hash){ var params = {}, regex = /([^&=]+)=([^&]*)/g, m; while ((m = regex.exec(hash)) !== null) { params[decodeURIComponent(m[1])] = decodeURIComponent(m[2]); } if(params.access_token || params.error){ return params; } }; /** * Save the access token into the session */ var setTokenInSession = function(){ Storage.set('token', service.token); }; /** * Set the access token expiration date (useful for refresh logics) */ var setExpiresAt = function(){ if (!service.token) { return; } if(typeof(service.token.expires_in) !== 'undefined' && service.token.expires_in !== null) { var expires_at = new Date(); expires_at.setSeconds(expires_at.getSeconds() + parseInt(service.token.expires_in)-60); // 60 seconds less to secure browser and response latency service.token.expires_at = expires_at; } else { service.token.expires_at = null; } }; /** * Set the timeout at which the expired event is fired */ var setExpiresAtEvent = function(){ // Don't bother if there's no expires token if (typeof(service.token.expires_at) === 'undefined' || service.token.expires_at === null) { return; } var time = (new Date(service.token.expires_at))-(new Date()); if(time && time > 0){ $interval(function(){ $rootScope.$broadcast('oauth:expired', service.token); }, time, 1); } }; /** * Remove the oAuth2 pieces from the hash fragment */ var removeFragment = function(){ var curHash = $location.hash(); angular.forEach(oAuth2HashTokens,function(hashKey){ var re = new RegExp('&'+hashKey+'(=[^&]*)?|^'+hashKey+'(=[^&]*)?&?'); curHash = curHash.replace(re,''); }); $location.hash(curHash); }; return service; }]); 'use strict'; var endpointClient = angular.module('oauth.endpoint', []); endpointClient.factory('Endpoint', function() { var service = {}; /* * Defines the authorization URL */ service.set = function(configuration) { this.config = configuration; return this.get(); }; /* * Returns the authorization URL */ service.get = function( overrides ) { var params = angular.extend( {}, service.config, overrides); var oAuthScope = (params.scope) ? encodeURIComponent(params.scope) : '', state = (params.state) ? encodeURIComponent(params.state) : '', authPathHasQuery = (params.authorizePath.indexOf('?') === -1) ? false : true, appendChar = (authPathHasQuery) ? '&' : '?', //if authorizePath has ? already append OAuth2 params responseType = (params.responseType) ? encodeURIComponent(params.responseType) : ''; var url = params.site + params.authorizePath + appendChar + 'response_type=' + responseType + '&' + 'client_id=' + encodeURIComponent(params.clientId) + '&' + 'redirect_uri=' + encodeURIComponent(params.redirectUri) + '&' + 'scope=' + oAuthScope + '&' + 'state=' + state; if( params.nonce ) { url = url + '&nonce=' + params.nonce; } return url; }; /* * Redirects the app to the authorization URL */ service.redirect = function( overrides ) { var targetLocation = this.get( overrides ); window.location.replace(targetLocation); }; return service; }); 'use strict'; var profileClient = angular.module('oauth.profile', []); profileClient.factory('Profile', ['$http', 'AccessToken', '$rootScope', function($http, AccessToken, $rootScope) { var service = {}; var profile; service.find = function(uri) { var promise = $http.get(uri, { headers: headers() }); promise.success(function(response) { profile = response; $rootScope.$broadcast('oauth:profile', profile); }); return promise; }; service.get = function() { return profile; }; service.set = function(resource) { profile = resource; return profile; }; var headers = function() { return { Authorization: 'Bearer ' + AccessToken.get().access_token }; }; return service; }]); 'use strict'; var storageService = angular.module('oauth.storage', ['ngStorage']); storageService.factory('Storage', ['$rootScope', '$sessionStorage', '$localStorage', function($rootScope, $sessionStorage, $localStorage){ var service = { storage: $sessionStorage // By default }; /** * Deletes the item from storage, * Returns the item's previous value */ service.delete = function (name) { var stored = this.get(name); delete this.storage[name]; return stored; }; /** * Returns the item from storage */ service.get = function (name) { return this.storage[name]; }; /** * Sets the item in storage to the value specified * Returns the item's value */ service.set = function (name, value) { this.storage[name] = value; return this.get(name); }; /** * Change the storage service being used */ service.use = function (storage) { if (storage === 'sessionStorage') { this.storage = $sessionStorage; } else if (storage === 'localStorage') { this.storage = $localStorage; } }; return service; }]); 'use strict'; var oauthConfigurationService = angular.module('oauth.configuration', []); oauthConfigurationService.provider('OAuthConfiguration', function() { var _config = {}; this.init = function(config, httpProvider) { _config.protectedResources = config.protectedResources || []; httpProvider.interceptors.push('AuthInterceptor'); }; this.$get = function() { return { getConfig: function() { return _config; } }; }; }) .factory('AuthInterceptor', function($q, $rootScope, OAuthConfiguration, AccessToken) { return { 'request': function(config) { OAuthConfiguration.getConfig().protectedResources.forEach(function(resource) { // If the url is one of the protected resources, we want to see if there's a token and then // add the token if it exists. if (config.url.indexOf(resource) > -1) { var token = AccessToken.get(); if (token) { config.headers.Authorization = 'Bearer ' + token.access_token; } } }); return config; } }; }); 'use strict'; var interceptorService = angular.module('oauth.interceptor', []); interceptorService.factory('ExpiredInterceptor', ['Storage', '$rootScope', function (Storage, $rootScope) { var service = {}; service.request = function(config) { var token = Storage.get('token'); if (token && expired(token)) { $rootScope.$broadcast('oauth:expired', token); } return config; }; var expired = function(token) { return (token && token.expires_at && new Date(token.expires_at) < new Date()); }; return service; }]); 'use strict'; var directives = angular.module('oauth.directive', []); directives.directive('oauth', [ 'AccessToken', 'Endpoint', 'Profile', 'Storage', '$location', '$rootScope', '$compile', '$http', '$templateCache', function(AccessToken, Endpoint, Profile, Storage, $location, $rootScope, $compile, $http, $templateCache) { var definition = { restrict: 'AE', replace: true, scope: { site: '@', // (required) set the oauth server host (e.g. path_to_url clientId: '@', // (required) client id redirectUri: '@', // (required) client redirect uri responseType: '@', // (optional) response type, defaults to token (use 'token' for implicit flow and 'code' for authorization code flow scope: '@', // (optional) scope profileUri: '@', // (optional) user profile uri (e.g path_to_url template: '@', // (optional) template to render (e.g bower_components/oauth-ng/dist/views/templates/default.html) text: '@', // (optional) login text authorizePath: '@', // (optional) authorization url state: '@', // (optional) An arbitrary unique string created by your app to guard against Cross-site Request Forgery storage: '@' // (optional) Store token in 'sessionStorage' or 'localStorage', defaults to 'sessionStorage' } }; definition.link = function postLink(scope, element) { scope.show = 'none'; scope.$watch('clientId', function() { init(); }); var init = function() { initAttributes(); // sets defaults Storage.use(scope.storage);// set storage compile(); // compiles the desired layout Endpoint.set(scope); // sets the oauth authorization url AccessToken.set(scope); // sets the access token object (if existing, from fragment or session) initProfile(scope); // gets the profile resource (if existing the access token) initView(); // sets the view (logged in or out) }; var initAttributes = function() { scope.authorizePath = scope.authorizePath || '/oauth/authorize'; scope.tokenPath = scope.tokenPath || '/oauth/token'; scope.template = scope.template || 'bower_components/oauth-ng/dist/views/templates/default.html'; scope.responseType = scope.responseType || 'token'; scope.text = scope.text || 'Sign In'; scope.state = scope.state || undefined; scope.scope = scope.scope || undefined; scope.storage = scope.storage || 'sessionStorage'; }; var compile = function() { $http.get(scope.template, { cache: $templateCache }).success(function(html) { element.html(html); $compile(element.contents())(scope); }); }; var initProfile = function(scope) { var token = AccessToken.get(); if (token && token.access_token && scope.profileUri) { Profile.find(scope.profileUri).success(function(response) { scope.profile = response; }); } }; var initView = function() { var token = AccessToken.get(); if (!token) { return loggedOut(); // without access token it's logged out } if (token.access_token) { return authorized(); // if there is the access token we are done } if (token.error) { return denied(); // if the request has been denied we fire the denied event } }; scope.login = function() { Endpoint.redirect(); }; scope.logout = function() { AccessToken.destroy(scope); $rootScope.$broadcast('oauth:logout'); loggedOut(); }; scope.$on('oauth:expired', function() { AccessToken.destroy(scope); scope.show = 'logged-out'; }); // user is authorized var authorized = function() { $rootScope.$broadcast('oauth:authorized', AccessToken.get()); scope.show = 'logged-in'; }; // set the oauth directive to the logged-out status var loggedOut = function() { $rootScope.$broadcast('oauth:loggedOut'); scope.show = 'logged-out'; }; // set the oauth directive to the denied status var denied = function() { scope.show = 'denied'; $rootScope.$broadcast('oauth:denied'); }; // Updates the template at runtime scope.$on('oauth:template:update', function(event, template) { scope.template = template; compile(scope); }); // Hack to update the directive content on logout // TODO think to a cleaner solution scope.$on('$routeChangeSuccess', function () { init(); }); }; return definition; } ]); ```
/content/code_sandbox/oauth-legacy/oauth-ui-implicit-angularjs-legacy/src/main/resources/oauth-ng.js
javascript
2016-03-02T09:04:07
2024-08-06T03:02:12
spring-security-oauth
Baeldung/spring-security-oauth
1,982
3,414
```java package com.baeldung.config; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.context.support.PropertySourcesPlaceholderConfigurer; import org.springframework.web.servlet.config.annotation.DefaultServletHandlerConfigurer; import org.springframework.web.servlet.config.annotation.EnableWebMvc; import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry; import org.springframework.web.servlet.config.annotation.ViewControllerRegistry; import org.springframework.web.servlet.config.annotation.WebMvcConfigurer; @Configuration @EnableWebMvc public class UiWebConfig implements WebMvcConfigurer { @Bean public static PropertySourcesPlaceholderConfigurer propertySourcesPlaceholderConfigurer() { return new PropertySourcesPlaceholderConfigurer(); } @Override public void configureDefaultServletHandling(final DefaultServletHandlerConfigurer configurer) { configurer.enable(); } @Override public void addViewControllers(final ViewControllerRegistry registry) { registry.addViewController("/").setViewName("forward:/index"); registry.addViewController("/oauthTemp"); registry.addViewController("/index"); } @Override public void addResourceHandlers(final ResourceHandlerRegistry registry) { registry.addResourceHandler("/resources/**").addResourceLocations("/resources/"); } } ```
/content/code_sandbox/oauth-legacy/oauth-ui-implicit-angularjs-legacy/src/main/java/com/baeldung/config/UiWebConfig.java
java
2016-03-02T09:04:07
2024-08-06T03:02:12
spring-security-oauth
Baeldung/spring-security-oauth
1,982
240
```java package com.baeldung.config; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.boot.web.servlet.support.SpringBootServletInitializer; @SpringBootApplication public class UiApplication extends SpringBootServletInitializer { public static void main(String[] args) { SpringApplication.run(UiApplication.class, args); } } ```
/content/code_sandbox/oauth-legacy/oauth-ui-implicit-angularjs-legacy/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
68
```java package com.baeldung.test; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.boot.test.context.SpringBootTest.WebEnvironment; import org.springframework.test.context.junit4.SpringRunner; import com.baeldung.ResourceServerApplication1; @RunWith(SpringRunner.class) @SpringBootTest(classes = ResourceServerApplication1.class, webEnvironment = WebEnvironment.RANDOM_PORT) public class ResourceServer1IntegrationTest { @Test public void whenLoadApplication_thenSuccess() { } } ```
/content/code_sandbox/oauth-legacy/oauth-microservices/2x/resource-server-mvc-2/src/test/java/com/baeldung/test/ResourceServer1IntegrationTest.java
java
2016-03-02T09:04:07
2024-08-06T03:02:12
spring-security-oauth
Baeldung/spring-security-oauth
1,982
105
```yaml spring: application: name: resource-server-mvc-1 server: port: 8870 eureka: instance: hostname: localhost port: 8761 client: serviceUrl: defaultZone: path_to_url{eureka.instance.hostname}:${eureka.instance.port}/eureka/ security: oauth2: resource: jwt: keyValue: "abc" id: fooScope serviceId: ${PREFIX:}resource ```
/content/code_sandbox/oauth-legacy/oauth-microservices/2x/resource-server-mvc-2/src/main/resources/application.yml
yaml
2016-03-02T09:04:07
2024-08-06T03:02:12
spring-security-oauth
Baeldung/spring-security-oauth
1,982
105
```java package com.baeldung.config; import org.springframework.context.annotation.Configuration; import org.springframework.security.config.annotation.web.builders.HttpSecurity; import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity; import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter; @EnableWebSecurity @Configuration public class WebSecurityConfig extends WebSecurityConfigurerAdapter { @Override protected void configure(HttpSecurity http) throws Exception { http.httpBasic().disable(); } } ```
/content/code_sandbox/oauth-legacy/oauth-microservices/2x/resource-server-mvc-2/src/main/java/com/baeldung/config/WebSecurityConfig.java
java
2016-03-02T09:04:07
2024-08-06T03:02:12
spring-security-oauth
Baeldung/spring-security-oauth
1,982
93
```java package com.baeldung; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.boot.web.servlet.support.SpringBootServletInitializer; import org.springframework.security.oauth2.config.annotation.web.configuration.EnableResourceServer; @SpringBootApplication @EnableResourceServer public class ResourceServerApplication1 extends SpringBootServletInitializer { public static void main(String[] args) { SpringApplication.run(ResourceServerApplication1.class, args); } } ```
/content/code_sandbox/oauth-legacy/oauth-microservices/2x/resource-server-mvc-2/src/main/java/com/baeldung/ResourceServerApplication1.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.web; import java.security.Principal; import org.springframework.security.access.prepost.PreAuthorize; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.ResponseBody; @Controller @RequestMapping("/") public class HelloController { @RequestMapping(method = RequestMethod.GET) @ResponseBody public String helloWorld(Principal principal) { return principal == null ? "Hello anonymous" : "Hello " + principal.getName(); } @PreAuthorize("#oauth2.hasScope('fooScope') and hasRole('ROLE_ADMIN')") @RequestMapping(value = "secret", method = RequestMethod.GET) @ResponseBody public String helloSecret(Principal principal) { return principal == null ? "Hello anonymous" : "S3CR3T - Hello " + principal.getName(); } } ```
/content/code_sandbox/oauth-legacy/oauth-microservices/2x/resource-server-mvc-2/src/main/java/com/baeldung/web/HelloController.java
java
2016-03-02T09:04:07
2024-08-06T03:02:12
spring-security-oauth
Baeldung/spring-security-oauth
1,982
180
```yaml spring: aop: proxy-target-class: true application: name: api-gateway-zuul-2 server: port: 8765 eureka: instance: hostname: localhost non-secure-port: 8761 client: serviceUrl: defaultZone: path_to_url{eureka.instance.hostname}:${eureka.instance.non-secure-port}/eureka/ zuul: routes: uaa-service: sensitiveHeaders: path: /uaa/** stripPrefix: false add-proxy-headers: true security: oauth2: sso: loginPath: /login client: accessTokenUri: path_to_url userAuthorizationUri: /uaa/oauth/authorize clientId: acme clientSecret: acmesecret resource: jwt: keyValue: "abc" id: openid serviceId: ${PREFIX:}resource logging: level.org.springframework.security: DEBUG # path_to_url ```
/content/code_sandbox/oauth-legacy/oauth-microservices/2x/api-gateway-zuul-2/src/main/resources/application.yml
yaml
2016-03-02T09:04:07
2024-08-06T03:02:12
spring-security-oauth
Baeldung/spring-security-oauth
1,982
221
```java package com.baeldung; import java.util.ArrayList; import java.util.List; import java.util.stream.Collectors; import java.util.stream.Stream; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.boot.autoconfigure.security.oauth2.resource.UserInfoRestTemplateCustomizer; import org.springframework.cloud.client.loadbalancer.LoadBalancerInterceptor; import org.springframework.cloud.netflix.zuul.EnableZuulProxy; import org.springframework.context.annotation.Bean; import org.springframework.http.client.ClientHttpRequestInterceptor; import org.springframework.security.oauth2.client.token.AccessTokenProviderChain; import org.springframework.security.oauth2.client.token.grant.client.ClientCredentialsAccessTokenProvider; import org.springframework.security.oauth2.client.token.grant.code.AuthorizationCodeAccessTokenProvider; import org.springframework.security.oauth2.client.token.grant.implicit.ImplicitAccessTokenProvider; import org.springframework.security.oauth2.client.token.grant.password.ResourceOwnerPasswordAccessTokenProvider; @SpringBootApplication @EnableZuulProxy // @EnableDiscoveryClient public class ApiGatewayApplication { @Bean UserInfoRestTemplateCustomizer userInfoRestTemplateCustomizer(LoadBalancerInterceptor loadBalancerInterceptor) { return template -> { List<ClientHttpRequestInterceptor> interceptors = new ArrayList<>(); interceptors.add(loadBalancerInterceptor); AccessTokenProviderChain accessTokenProviderChain = Stream.of( // @formatter:off new AuthorizationCodeAccessTokenProvider(), new ImplicitAccessTokenProvider(), new ResourceOwnerPasswordAccessTokenProvider(), new ClientCredentialsAccessTokenProvider() )// @formatter:on .peek(tp -> tp.setInterceptors(interceptors)).collect(Collectors.collectingAndThen(Collectors.toList(), AccessTokenProviderChain::new)); template.setAccessTokenProvider(accessTokenProviderChain); }; } public static void main(String[] args) { SpringApplication.run(ApiGatewayApplication.class, args); } } ```
/content/code_sandbox/oauth-legacy/oauth-microservices/2x/api-gateway-zuul-2/src/main/java/com/baeldung/ApiGatewayApplication.java
java
2016-03-02T09:04:07
2024-08-06T03:02:12
spring-security-oauth
Baeldung/spring-security-oauth
1,982
366
```java package com.baeldung.security; import org.springframework.security.oauth2.client.filter.OAuth2ClientContextFilter; import org.springframework.security.oauth2.client.resource.UserRedirectRequiredException; import org.springframework.security.web.DefaultRedirectStrategy; import org.springframework.security.web.RedirectStrategy; import org.springframework.web.util.UriComponentsBuilder; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.IOException; import java.util.Map; class DynamicOauth2ClientContextFilter extends OAuth2ClientContextFilter { private RedirectStrategy redirectStrategy = new DefaultRedirectStrategy(); @Override protected void redirectUser(UserRedirectRequiredException e, HttpServletRequest request, HttpServletResponse response) throws IOException { String redirectUri = e.getRedirectUri(); UriComponentsBuilder builder = UriComponentsBuilder.fromUriString(redirectUri); Map<String, String> requestParams = e.getRequestParams(); for (Map.Entry<String, String> param : requestParams.entrySet()) { builder.queryParam(param.getKey(), param.getValue()); } if (e.getStateKey() != null) { builder.queryParam("state", e.getStateKey()); } String url = getBaseUrl(request) + builder.build().encode().toUriString(); this.redirectStrategy.sendRedirect(request, response, url); } @Override public void setRedirectStrategy(RedirectStrategy redirectStrategy) { this.redirectStrategy = redirectStrategy; } private String getBaseUrl(HttpServletRequest request) { StringBuffer url = request.getRequestURL(); return url.substring(0, url.length() - request.getRequestURI().length() + request.getContextPath().length()); } } ```
/content/code_sandbox/oauth-legacy/oauth-microservices/2x/api-gateway-zuul-2/src/main/java/com/baeldung/security/DynamicOauth2ClientContextFilter.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.demo; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.test.context.junit4.SpringRunner; @RunWith(SpringRunner.class) @SpringBootTest public class ApiGatewayApplicationTests { @Test public void contextLoads() { } } ```
/content/code_sandbox/oauth-legacy/oauth-microservices/2x/api-cloud-gateway-2/src/test/java/com/baeldung/demo/ApiGatewayApplicationTests.java
java
2016-03-02T09:04:07
2024-08-06T03:02:12
spring-security-oauth
Baeldung/spring-security-oauth
1,982
63
```yaml spring: cloud: gateway: routes: - id: foos uri: path_to_url predicates: - After=2017-01-20T17:42:47.789-07:00[America/Denver] ```
/content/code_sandbox/oauth-legacy/oauth-microservices/2x/api-cloud-gateway-2/src/main/resources/application.yml
yaml
2016-03-02T09:04:07
2024-08-06T03:02:12
spring-security-oauth
Baeldung/spring-security-oauth
1,982
58
```java package com.baeldung.gateway; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.cloud.gateway.route.RouteLocator; import org.springframework.cloud.gateway.route.builder.RouteLocatorBuilder; import org.springframework.context.annotation.Bean; @SpringBootApplication public class ApiGatewayApplication { @Bean public RouteLocator routeLocator(RouteLocatorBuilder builder) {// @formatter:off return builder.routes() .route(r -> r.path("/foos/**") // .filters(f -> f.stripPrefix(1)) .uri("path_to_url") ).build(); }// @formatter:on public static void main(String[] args) { SpringApplication.run(ApiGatewayApplication.class, args); } } ```
/content/code_sandbox/oauth-legacy/oauth-microservices/2x/api-cloud-gateway-2/src/main/java/com/baeldung/gateway/ApiGatewayApplication.java
java
2016-03-02T09:04:07
2024-08-06T03:02:12
spring-security-oauth
Baeldung/spring-security-oauth
1,982
148
```java package com.baeldung.security; import java.io.IOException; import java.util.regex.Pattern; import javax.servlet.Filter; import javax.servlet.FilterChain; import javax.servlet.ServletException; import javax.servlet.http.Cookie; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.autoconfigure.security.oauth2.client.EnableOAuth2Sso; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.Primary; import org.springframework.core.annotation.Order; import org.springframework.security.authentication.AuthenticationManager; import org.springframework.security.config.annotation.web.builders.HttpSecurity; import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter; import org.springframework.security.oauth2.client.filter.OAuth2ClientContextFilter; import org.springframework.security.oauth2.config.annotation.web.configuration.EnableResourceServer; import org.springframework.security.oauth2.provider.authentication.OAuth2AuthenticationManager; import org.springframework.security.oauth2.provider.authentication.OAuth2AuthenticationProcessingFilter; import org.springframework.security.oauth2.provider.token.ResourceServerTokenServices; import org.springframework.security.web.authentication.preauth.AbstractPreAuthenticatedProcessingFilter; import org.springframework.security.web.csrf.CsrfFilter; import org.springframework.security.web.csrf.CsrfToken; import org.springframework.security.web.csrf.CsrfTokenRepository; import org.springframework.security.web.csrf.HttpSessionCsrfTokenRepository; import org.springframework.security.web.util.matcher.AntPathRequestMatcher; import org.springframework.security.web.util.matcher.RequestMatcher; import org.springframework.web.filter.OncePerRequestFilter; @Configuration @EnableOAuth2Sso @EnableResourceServer @Order(value = 0) public class SecurityConfiguration extends WebSecurityConfigurerAdapter { private static final String CSRF_COOKIE_NAME = "XSRF-TOKEN"; private static final String CSRF_HEADER_NAME = "X-XSRF-TOKEN"; @Autowired private ResourceServerTokenServices resourceServerTokenServices; @Bean @Primary public OAuth2ClientContextFilter dynamicOauth2ClientContextFilter() { return new DynamicOauth2ClientContextFilter(); } @Override public void configure(HttpSecurity http) throws Exception { // @formatter:off http.authorizeRequests() .antMatchers("/authorization-server-2/**", "/login").permitAll() .anyRequest().authenticated() .and().csrf().requireCsrfProtectionMatcher(csrfRequestMatcher()).csrfTokenRepository(csrfTokenRepository()) .and().addFilterAfter(csrfHeaderFilter(), CsrfFilter.class).addFilterAfter(oAuth2AuthenticationProcessingFilter(), AbstractPreAuthenticatedProcessingFilter.class) .logout().permitAll().logoutSuccessUrl("/"); } // @formatter:on private OAuth2AuthenticationProcessingFilter oAuth2AuthenticationProcessingFilter() { OAuth2AuthenticationProcessingFilter oAuth2AuthenticationProcessingFilter = new OAuth2AuthenticationProcessingFilter(); oAuth2AuthenticationProcessingFilter.setAuthenticationManager(oauthAuthenticationManager()); oAuth2AuthenticationProcessingFilter.setStateless(false); return oAuth2AuthenticationProcessingFilter; } private AuthenticationManager oauthAuthenticationManager() { OAuth2AuthenticationManager oAuth2AuthenticationManager = new OAuth2AuthenticationManager(); oAuth2AuthenticationManager.setResourceId("apigateway"); oAuth2AuthenticationManager.setTokenServices(resourceServerTokenServices); oAuth2AuthenticationManager.setClientDetailsService(null); return oAuth2AuthenticationManager; } private RequestMatcher csrfRequestMatcher() { return new RequestMatcher() { // Always allow the HTTP GET method private final Pattern allowedMethods = Pattern.compile("^(GET|HEAD|OPTIONS|TRACE)$"); // Disable CSFR protection on the following urls: private final AntPathRequestMatcher[] requestMatchers = { new AntPathRequestMatcher("/authorization-server-2/**") }; @Override public boolean matches(HttpServletRequest request) { if (allowedMethods.matcher(request.getMethod()).matches()) { return false; } for (AntPathRequestMatcher matcher : requestMatchers) { if (matcher.matches(request)) { return false; } } return true; } }; } private static Filter csrfHeaderFilter() { return new OncePerRequestFilter() { @Override protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException { CsrfToken csrf = (CsrfToken) request.getAttribute(CsrfToken.class.getName()); if (csrf != null) { Cookie cookie = new Cookie(CSRF_COOKIE_NAME, csrf.getToken()); cookie.setPath("/"); cookie.setSecure(true); response.addCookie(cookie); } filterChain.doFilter(request, response); } }; } private static CsrfTokenRepository csrfTokenRepository() { HttpSessionCsrfTokenRepository repository = new HttpSessionCsrfTokenRepository(); repository.setHeaderName(CSRF_HEADER_NAME); return repository; } } ```
/content/code_sandbox/oauth-legacy/oauth-microservices/2x/api-gateway-zuul-2/src/main/java/com/baeldung/security/SecurityConfiguration.java
java
2016-03-02T09:04:07
2024-08-06T03:02:12
spring-security-oauth
Baeldung/spring-security-oauth
1,982
1,001
```yaml spring: application: name: service-registry-2 server: port: 8761 eureka: instance: hostname: localhost port: ${server.port} client: registerWithEureka: false fetchRegistry: false serviceUrl: defaultZone: path_to_url{eureka.instance.hostname}:${server.port}/eureka/ server: waitTimeInMsWhenSyncEmpty: 0 ```
/content/code_sandbox/oauth-legacy/oauth-microservices/2x/service-registry-2/src/main/resources/application.yml
yaml
2016-03-02T09:04:07
2024-08-06T03:02:12
spring-security-oauth
Baeldung/spring-security-oauth
1,982
97
```java package com.baeldung; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.cloud.netflix.eureka.server.EnableEurekaServer; @SpringBootApplication @EnableEurekaServer public class ServiceRegistryApplication { public static void main(String[] args) { SpringApplication.run(ServiceRegistryApplication.class, args); } } ```
/content/code_sandbox/oauth-legacy/oauth-microservices/2x/service-registry-2/src/main/java/com/baeldung/ServiceRegistryApplication.java
java
2016-03-02T09:04:07
2024-08-06T03:02:12
spring-security-oauth
Baeldung/spring-security-oauth
1,982
69
```java package com.baeldung.test; import static org.hamcrest.Matchers.is; import static org.springframework.security.test.web.servlet.request.SecurityMockMvcRequestPostProcessors.httpBasic; import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.content; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; import org.junit.Before; import org.junit.Ignore; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.json.JacksonJsonParser; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.security.web.FilterChainProxy; import org.springframework.test.context.junit4.SpringRunner; import org.springframework.test.context.web.WebAppConfiguration; import org.springframework.test.web.servlet.MockMvc; import org.springframework.test.web.servlet.ResultActions; import org.springframework.test.web.servlet.setup.MockMvcBuilders; import org.springframework.util.LinkedMultiValueMap; import org.springframework.util.MultiValueMap; import org.springframework.web.context.WebApplicationContext; import com.baeldung.AuthorizationServerApplication; @RunWith(SpringRunner.class) @WebAppConfiguration @SpringBootTest(classes = AuthorizationServerApplication.class) @Ignore public class OAuthMvcTest { @Autowired private WebApplicationContext wac; @Autowired private FilterChainProxy springSecurityFilterChain; private MockMvc mockMvc; private static final String CLIENT_ID = "fooClientId"; private static final String CLIENT_SECRET = "secret"; private static final String CONTENT_TYPE = "application/json;charset=UTF-8"; private static final String EMAIL = "jim@yahoo.com"; private static final String NAME = "Jim"; @Before public void setup() { this.mockMvc = MockMvcBuilders.webAppContextSetup(this.wac).addFilter(springSecurityFilterChain).build(); } private String obtainAccessToken(String username, String password) throws Exception { final MultiValueMap<String, String> params = new LinkedMultiValueMap<>(); params.add("grant_type", "password"); params.add("client_id", CLIENT_ID); params.add("username", username); params.add("password", password); // @formatter:off ResultActions result = mockMvc.perform(post("/oauth/token") .params(params) .with(httpBasic(CLIENT_ID, CLIENT_SECRET)) .accept(CONTENT_TYPE)) .andExpect(status().isOk()) .andExpect(content().contentType(CONTENT_TYPE)); // @formatter:on String resultString = result.andReturn().getResponse().getContentAsString(); JacksonJsonParser jsonParser = new JacksonJsonParser(); return jsonParser.parseMap(resultString).get("access_token").toString(); } @Test public void givenNoToken_whenGetSecureRequest_thenUnauthorized() throws Exception { mockMvc.perform(get("/employee").param("email", EMAIL)).andExpect(status().isUnauthorized()); } @Test public void givenInvalidRole_whenGetSecureRequest_thenForbidden() throws Exception { final String accessToken = obtainAccessToken("user1", "pass"); System.out.println("token:" + accessToken); mockMvc.perform(get("/employee").header("Authorization", "Bearer " + accessToken).param("email", EMAIL)).andExpect(status().isForbidden()); } @Test public void givenToken_whenPostGetSecureRequest_thenOk() throws Exception { final String accessToken = obtainAccessToken("admin", "nimda"); String employeeString = "{\"email\":\"" + EMAIL + "\",\"name\":\"" + NAME + "\",\"age\":30}"; // @formatter:off mockMvc.perform(post("/employee") .header("Authorization", "Bearer " + accessToken) .contentType(CONTENT_TYPE) .content(employeeString) .accept(CONTENT_TYPE)) .andExpect(status().isCreated()); mockMvc.perform(get("/employee") .param("email", EMAIL) .header("Authorization", "Bearer " + accessToken) .accept(CONTENT_TYPE)) .andExpect(status().isOk()) .andExpect(content().contentType(CONTENT_TYPE)) .andExpect(jsonPath("$.name", is(NAME))); // @formatter:on } } ```
/content/code_sandbox/oauth-legacy/oauth-microservices/2x/authorization-server-2/src/test/java/com/baeldung/test/OAuthMvcTest.java
java
2016-03-02T09:04:07
2024-08-06T03:02:12
spring-security-oauth
Baeldung/spring-security-oauth
1,982
873
```java package com.baeldung.test; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.boot.test.context.SpringBootTest.WebEnvironment; import org.springframework.test.context.junit4.SpringRunner; import com.baeldung.AuthorizationServerApplication; @RunWith(SpringRunner.class) @SpringBootTest(classes = AuthorizationServerApplication.class, webEnvironment = WebEnvironment.RANDOM_PORT) public class AuthServerIntegrationTest { @Test public void whenLoadApplication_thenSuccess() { } } ```
/content/code_sandbox/oauth-legacy/oauth-microservices/2x/authorization-server-2/src/test/java/com/baeldung/test/AuthServerIntegrationTest.java
java
2016-03-02T09:04:07
2024-08-06T03:02:12
spring-security-oauth
Baeldung/spring-security-oauth
1,982
102
```yaml spring: application: name: authorization-server-2 server: port: 8769 servlet: context-path: /uaa use-forward-headers: false eureka: instance: hostname: localhost port: 8761 client: serviceUrl: defaultZone: path_to_url{eureka.instance.hostname}:${eureka.instance.port}/eureka/ logging: level.org.springframework.security: DEBUG # path_to_url ```
/content/code_sandbox/oauth-legacy/oauth-microservices/2x/authorization-server-2/src/main/resources/application.yml
yaml
2016-03-02T09:04:07
2024-08-06T03:02:12
spring-security-oauth
Baeldung/spring-security-oauth
1,982
104
```java package com.baeldung.test; import static org.junit.Assert.assertNotNull; import java.util.HashMap; import java.util.Map; import org.junit.Ignore; import org.junit.Test; import io.restassured.RestAssured; import io.restassured.response.Response; @Ignore public class AuthorizationServerLiveTest { @Test public void whenObtainingAccessToken_thenOK() { final Response authServerResponse = obtainAccessToken("fooClientId", "secret", "john", "123"); final String accessToken = authServerResponse.jsonPath().getString("access_token"); assertNotNull(accessToken); } // private Response obtainAccessToken(final String clientId, final String clientSecret, final String username, final 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); return RestAssured.given().auth().preemptive().basic(clientId, clientSecret).and().with().params(params).when().post("path_to_url"); // response.jsonPath().getString("refresh_token"); // response.jsonPath().getString("access_token") } } ```
/content/code_sandbox/oauth-legacy/oauth-microservices/2x/authorization-server-2/src/test/java/com/baeldung/test/AuthorizationServerLiveTest.java
java
2016-03-02T09:04:07
2024-08-06T03:02:12
spring-security-oauth
Baeldung/spring-security-oauth
1,982
259
```freemarker <html> <head> </head> <body> <div class="container"> <form role="form" action="login" method="post"> <div class="form-group"> <label for="username">Username:</label> <input type="text" class="form-control" id="username" name="username"/> </div> <div class="form-group"> <label for="password">Password:</label> <input type="password" class="form-control" id="password" name="password"/> </div> <input type="hidden" id="csrf_token" name="${_csrf.parameterName}" value="${_csrf.token}"/> <button type="submit" class="btn btn-primary">Submit</button> </form> </div> </body> </html> ```
/content/code_sandbox/oauth-legacy/oauth-microservices/2x/authorization-server-2/src/main/resources/templates/login.ftl
freemarker
2016-03-02T09:04:07
2024-08-06T03:02:12
spring-security-oauth
Baeldung/spring-security-oauth
1,982
172
```freemarker <html> <head> </head> <body> <div class="container"> <h2>Please Confirm</h2> <p> Do you authorize "${authorizationRequest.clientId}" at "${authorizationRequest.redirectUri}" to access your protected resources with scope ${authorizationRequest.scope?join(", ")}. </p> <form id="confirmationForm" name="confirmationForm" action="../oauth/authorize" method="post"> <input name="user_oauth_approval" value="true" type="hidden"/> <input type="hidden" id="csrf_token" name="${_csrf.parameterName}" value="${_csrf.token}"/> <button class="btn btn-primary" type="submit">Approve</button> </form> <form id="denyForm" name="confirmationForm" action="../oauth/authorize" method="post"> <input name="user_oauth_approval" value="false" type="hidden"/> <input type="hidden" id="csrf_token" name="${_csrf.parameterName}" value="${_csrf.token}"/> <button class="btn btn-primary" type="submit">Deny</button> </form> </div> </body> </html> ```
/content/code_sandbox/oauth-legacy/oauth-microservices/2x/authorization-server-2/src/main/resources/templates/authorize.ftl
freemarker
2016-03-02T09:04:07
2024-08-06T03:02:12
spring-security-oauth
Baeldung/spring-security-oauth
1,982
258
```java package com.baeldung; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.boot.web.servlet.support.SpringBootServletInitializer; @SpringBootApplication public class AuthorizationServerApplication extends SpringBootServletInitializer { public static void main(String[] args) { SpringApplication.run(AuthorizationServerApplication.class, args); } } ```
/content/code_sandbox/oauth-legacy/oauth-microservices/2x/authorization-server-2/src/main/java/com/baeldung/AuthorizationServerApplication.java
java
2016-03-02T09:04:07
2024-08-06T03:02:12
spring-security-oauth
Baeldung/spring-security-oauth
1,982
70
```java package com.baeldung.config; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Qualifier; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.security.authentication.AuthenticationManager; import org.springframework.security.oauth2.config.annotation.configurers.ClientDetailsServiceConfigurer; import org.springframework.security.oauth2.config.annotation.web.configuration.AuthorizationServerConfigurerAdapter; import org.springframework.security.oauth2.config.annotation.web.configuration.EnableAuthorizationServer; import org.springframework.security.oauth2.config.annotation.web.configurers.AuthorizationServerEndpointsConfigurer; import org.springframework.security.oauth2.config.annotation.web.configurers.AuthorizationServerSecurityConfigurer; import org.springframework.security.oauth2.provider.token.TokenStore; import org.springframework.security.oauth2.provider.token.store.JwtAccessTokenConverter; import org.springframework.security.oauth2.provider.token.store.JwtTokenStore; @Configuration @EnableAuthorizationServer public class OAuth2AuthorizationServerConfig extends AuthorizationServerConfigurerAdapter { @Autowired @Qualifier("authenticationManagerBean") private AuthenticationManager authenticationManager; @Override public void configure(ClientDetailsServiceConfigurer clients) throws Exception { clients.inMemory().withClient("fooClient").secret("fooSecret").authorizedGrantTypes("authorization_code", "refresh_token").scopes("fooScope"); } @Override public void configure(AuthorizationServerSecurityConfigurer oauthServer) throws Exception { oauthServer.tokenKeyAccess("permitAll()").checkTokenAccess("isAuthenticated()"); } @Override public void configure(AuthorizationServerEndpointsConfigurer endpoints) throws Exception { endpoints.tokenStore(tokenStore()).authenticationManager(authenticationManager).accessTokenConverter(jwtAccessTokenConverter()); } @Bean public TokenStore tokenStore() { return new JwtTokenStore(jwtAccessTokenConverter()); } @Bean public JwtAccessTokenConverter jwtAccessTokenConverter() { JwtAccessTokenConverter converter = new JwtAccessTokenConverter(); converter.setSigningKey("abc"); return converter; } } ```
/content/code_sandbox/oauth-legacy/oauth-microservices/2x/authorization-server-2/src/main/java/com/baeldung/config/OAuth2AuthorizationServerConfig.java
java
2016-03-02T09:04:07
2024-08-06T03:02:12
spring-security-oauth
Baeldung/spring-security-oauth
1,982
395
```java package com.baeldung.config; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.autoconfigure.security.SecurityProperties; import org.springframework.cloud.client.discovery.EnableDiscoveryClient; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.core.annotation.Order; import org.springframework.security.authentication.AuthenticationManager; import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder; import org.springframework.security.config.annotation.web.builders.HttpSecurity; import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter; import org.springframework.security.crypto.password.NoOpPasswordEncoder; @Order(SecurityProperties.BASIC_AUTH_ORDER - 6) @Configuration @EnableDiscoveryClient public class WebSecurityConfig extends WebSecurityConfigurerAdapter { @Override protected void configure(HttpSecurity http) throws Exception { // @formatter:off http .authorizeRequests() .anyRequest().authenticated() .and().formLogin().loginPage("/login").permitAll(); }// @formatter:on @Autowired public void globalUserDetails(final AuthenticationManagerBuilder auth) throws Exception { // @formatter:off auth.inMemoryAuthentication() .withUser("user").password("password").roles("USER") .and().withUser("admin").password("admin").roles("ADMIN"); }// @formatter:on @Override @Bean public AuthenticationManager authenticationManagerBean() throws Exception { return super.authenticationManagerBean(); } @SuppressWarnings("deprecation") @Bean public static NoOpPasswordEncoder passwordEncoder() { return (NoOpPasswordEncoder) NoOpPasswordEncoder.getInstance(); } } ```
/content/code_sandbox/oauth-legacy/oauth-microservices/2x/authorization-server-2/src/main/java/com/baeldung/config/WebSecurityConfig.java
java
2016-03-02T09:04:07
2024-08-06T03:02:12
spring-security-oauth
Baeldung/spring-security-oauth
1,982
329
```java package com.baeldung.config; import org.springframework.boot.web.servlet.FilterRegistrationBean; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.core.Ordered; import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity; import org.springframework.web.filter.ForwardedHeaderFilter; import org.springframework.web.servlet.config.annotation.EnableWebMvc; import org.springframework.web.servlet.config.annotation.ViewControllerRegistry; import org.springframework.web.servlet.config.annotation.WebMvcConfigurer; @Configuration @EnableWebSecurity @EnableWebMvc public class WebConfig implements WebMvcConfigurer { @Bean FilterRegistrationBean forwardedHeaderFilter() { FilterRegistrationBean filterRegBean = new FilterRegistrationBean(); filterRegBean.setFilter(new ForwardedHeaderFilter()); filterRegBean.setOrder(Ordered.HIGHEST_PRECEDENCE); return filterRegBean; } @Override public void addViewControllers(ViewControllerRegistry registry) { registry.addViewController("/login").setViewName("login"); registry.addViewController("/oauth/confirm_access").setViewName("authorize"); } } ```
/content/code_sandbox/oauth-legacy/oauth-microservices/2x/authorization-server-2/src/main/java/com/baeldung/config/WebConfig.java
java
2016-03-02T09:04:07
2024-08-06T03:02:12
spring-security-oauth
Baeldung/spring-security-oauth
1,982
223
```java package com.baeldung.test; import static org.hamcrest.CoreMatchers.equalTo; import static org.junit.Assert.assertThat; import java.util.HashMap; import java.util.Map; import org.junit.Ignore; import org.junit.Test; import io.restassured.RestAssured; import io.restassured.response.Response; @Ignore public class ResourceServerRestLiveTest { @Test public void givenAccessToken_whenConsumingFoos_thenOK() { final String accessToken = obtainAccessTokenViaPasswordGrant("john", "123"); final Response resourceServerResponse = RestAssured.given().header("Authorization", "Bearer " + accessToken).get("path_to_url"); assertThat(resourceServerResponse.getStatusCode(), equalTo(200)); } @Test public void your_sha256_hashdden() { final String accessToken = obtainAccessTokenViaPasswordGrant("john", "123"); final Response resourceServerResponse = RestAssured.given().header("Authorization", "Bearer " + accessToken).get("path_to_url"); assertThat(resourceServerResponse.getStatusCode(), equalTo(403)); } @Test public void givenUserWithAdminAccess_whenConsumingAdminOperation_thenOK() { final String accessToken = obtainAccessTokenViaPasswordGrant("tom", "111"); final Response resourceServerResponse = RestAssured.given().header("Authorization", "Bearer " + accessToken).get("path_to_url"); assertThat(resourceServerResponse.getStatusCode(), equalTo(200)); } // private String obtainAccessTokenViaPasswordGrant(final String username, final String password) { final Response authServerResponse = obtainAccessTokenViaPasswordGrantRaw("fooClientId", "secret", username, password); final String accessToken = authServerResponse.jsonPath().getString("access_token"); return accessToken; } private Response obtainAccessTokenViaPasswordGrantRaw(final String clientId, final String clientSecret, final String username, final 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); return RestAssured.given().auth().preemptive().basic(clientId, clientSecret).and().with().params(params).when().post("path_to_url"); // response.jsonPath().getString("refresh_token"); // response.jsonPath().getString("access_token") } } ```
/content/code_sandbox/oauth-legacy/oauth-microservices/2x/resource-server-rest-2/src/test/java/com/baeldung/test/ResourceServerRestLiveTest.java
java
2016-03-02T09:04:07
2024-08-06T03:02:12
spring-security-oauth
Baeldung/spring-security-oauth
1,982
501
```java package com.baeldung.test; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.boot.test.context.SpringBootTest.WebEnvironment; import org.springframework.test.context.junit4.SpringRunner; import com.baeldung.ResourceServerApplication2; @RunWith(SpringRunner.class) @SpringBootTest(classes = ResourceServerApplication2.class, webEnvironment = WebEnvironment.RANDOM_PORT) public class ResourceServer2IntegrationTest { @Test public void whenLoadApplication_thenSuccess() { } } ```
/content/code_sandbox/oauth-legacy/oauth-microservices/2x/resource-server-rest-2/src/test/java/com/baeldung/test/ResourceServer2IntegrationTest.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; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.boot.web.servlet.support.SpringBootServletInitializer; @SpringBootApplication public class ResourceServerApplication2 extends SpringBootServletInitializer { public static void main(String[] args) { SpringApplication.run(ResourceServerApplication2.class, args); } } ```
/content/code_sandbox/oauth-legacy/oauth-microservices/2x/resource-server-rest-2/src/main/java/com/baeldung/ResourceServerApplication2.java
java
2016-03-02T09:04:07
2024-08-06T03:02:12
spring-security-oauth
Baeldung/spring-security-oauth
1,982
70
```java package com.baeldung.test; import static org.hamcrest.CoreMatchers.equalTo; import static org.junit.Assert.assertThat; import java.util.HashMap; import java.util.Map; import org.junit.Ignore; import org.junit.Test; import io.restassured.RestAssured; import io.restassured.response.Response; @Ignore public class ResourceServer2LiveTest { @Test public void your_sha256_hashdden() { final String accessToken = obtainAccessTokenViaPasswordGrant("john", "123"); final Response resourceServerResponse = RestAssured.given().header("Authorization", "Bearer " + accessToken).get("path_to_url"); assertThat(resourceServerResponse.getStatusCode(), equalTo(403)); } // private String obtainAccessTokenViaPasswordGrant(final String username, final String password) { final Response authServerResponse = obtainAccessTokenViaPasswordGrantRaw("fooClientId", "secret", username, password); final String accessToken = authServerResponse.jsonPath().getString("access_token"); return accessToken; } private Response obtainAccessTokenViaPasswordGrantRaw(final String clientId, final String clientSecret, final String username, final 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); return RestAssured.given().auth().preemptive().basic(clientId, clientSecret).and().with().params(params).when().post("path_to_url"); // response.jsonPath().getString("refresh_token"); // response.jsonPath().getString("access_token") } } ```
/content/code_sandbox/oauth-legacy/oauth-microservices/2x/resource-server-rest-2/src/test/java/com/baeldung/test/ResourceServer2LiveTest.java
java
2016-03-02T09:04:07
2024-08-06T03:02:12
spring-security-oauth
Baeldung/spring-security-oauth
1,982
346
```java package com.baeldung.service; import static org.apache.commons.lang3.RandomStringUtils.randomAlphabetic; import static org.apache.commons.lang3.RandomStringUtils.randomNumeric; import org.springframework.security.access.prepost.PreAuthorize; import org.springframework.stereotype.Service; import com.baeldung.web.dto.Third; @Service public class ThirdService { @PreAuthorize("hasRole('ROLE_ADMIN')") public Third findById(long id) { return new Third(Long.parseLong(randomNumeric(2)), randomAlphabetic(4)); } } ```
/content/code_sandbox/oauth-legacy/oauth-microservices/2x/resource-server-rest-2/src/main/java/com/baeldung/service/ThirdService.java
java
2016-03-02T09:04:07
2024-08-06T03:02:12
spring-security-oauth
Baeldung/spring-security-oauth
1,982
107
```java package com.baeldung.web.controller; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.ResponseBody; import com.baeldung.service.ThirdService; import com.baeldung.web.dto.Third; @Controller public class ThirdController { private ThirdService thirdService; public ThirdController(ThirdService thirdService) { this.thirdService = thirdService; } // API @RequestMapping(method = RequestMethod.GET, value = "/third/{id}") @ResponseBody public Third findById(@PathVariable final long id) { return thirdService.findById(id); } } ```
/content/code_sandbox/oauth-legacy/oauth-microservices/2x/resource-server-rest-2/src/main/java/com/baeldung/web/controller/ThirdController.java
java
2016-03-02T09:04:07
2024-08-06T03:02:12
spring-security-oauth
Baeldung/spring-security-oauth
1,982
147
```java package com.baeldung.config; import java.net.MalformedURLException; import java.net.URL; import java.util.Arrays; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.Primary; import org.springframework.security.config.annotation.web.builders.HttpSecurity; import org.springframework.security.config.http.SessionCreationPolicy; import org.springframework.security.oauth2.config.annotation.web.configuration.EnableResourceServer; import org.springframework.security.oauth2.config.annotation.web.configuration.ResourceServerConfigurerAdapter; import org.springframework.security.oauth2.config.annotation.web.configurers.ResourceServerSecurityConfigurer; import org.springframework.security.oauth2.provider.token.DefaultTokenServices; import org.springframework.security.oauth2.provider.token.TokenStore; import org.springframework.security.oauth2.provider.token.store.DelegatingJwtClaimsSetVerifier; import org.springframework.security.oauth2.provider.token.store.IssuerClaimVerifier; import org.springframework.security.oauth2.provider.token.store.JwtAccessTokenConverter; import org.springframework.security.oauth2.provider.token.store.JwtClaimsSetVerifier; import org.springframework.security.oauth2.provider.token.store.JwtTokenStore; @Configuration @EnableResourceServer public class OAuth2ResourceServerConfig extends ResourceServerConfigurerAdapter { @Override public void configure(final HttpSecurity http) throws Exception { http.sessionManagement().sessionCreationPolicy(SessionCreationPolicy.IF_REQUIRED).and().authorizeRequests() // .access("#oauth2.hasScope('readScope')") .anyRequest().permitAll(); } // JWT token store @Override public void configure(final ResourceServerSecurityConfigurer config) { config.tokenServices(tokenServices()); } @Bean public TokenStore tokenStore() { return new JwtTokenStore(accessTokenConverter()); } @Bean public JwtAccessTokenConverter accessTokenConverter() { final JwtAccessTokenConverter converter = new JwtAccessTokenConverter(); converter.setSigningKey("123"); converter.setJwtClaimsSetVerifier(jwtClaimsSetVerifier()); return converter; } @Bean public JwtClaimsSetVerifier jwtClaimsSetVerifier() { return new DelegatingJwtClaimsSetVerifier(Arrays.asList(issuerClaimVerifier())); } @Bean public JwtClaimsSetVerifier issuerClaimVerifier() { try { return new IssuerClaimVerifier(new URL("path_to_url")); } catch (final MalformedURLException e) { throw new RuntimeException(e); } } @Bean @Primary public DefaultTokenServices tokenServices() { final DefaultTokenServices defaultTokenServices = new DefaultTokenServices(); defaultTokenServices.setTokenStore(tokenStore()); return defaultTokenServices; } } ```
/content/code_sandbox/oauth-legacy/oauth-microservices/2x/resource-server-rest-2/src/main/java/com/baeldung/config/OAuth2ResourceServerConfig.java
java
2016-03-02T09:04:07
2024-08-06T03:02:12
spring-security-oauth
Baeldung/spring-security-oauth
1,982
532
```java package com.baeldung.web.controller; import static org.apache.commons.lang3.RandomStringUtils.randomAlphabetic; import static org.apache.commons.lang3.RandomStringUtils.randomNumeric; import org.springframework.http.HttpStatus; import org.springframework.security.access.prepost.PreAuthorize; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.ResponseBody; import org.springframework.web.bind.annotation.ResponseStatus; import com.baeldung.web.dto.Bar; @Controller public class BarController { // API - write, secured with scopes @PreAuthorize("hasRole('ROLE_ADMIN')") @RequestMapping(method = RequestMethod.GET, value = "/bars/{id}") @ResponseBody public Bar findById(@PathVariable final long id) { return new Bar(Long.parseLong(randomNumeric(2)), randomAlphabetic(4)); } // API - write, secured with scopes @PreAuthorize("#oauth2.hasScope('barScope') and #oauth2.hasScope('writeScope') and hasRole('ROLE_ADMIN')") @RequestMapping(method = RequestMethod.POST, value = "/bars") @ResponseStatus(HttpStatus.CREATED) @ResponseBody public Bar create(@RequestBody final Bar bar) { bar.setId(Long.parseLong(randomNumeric(2))); return bar; } } ```
/content/code_sandbox/oauth-legacy/oauth-microservices/2x/resource-server-rest-2/src/main/java/com/baeldung/web/controller/BarController.java
java
2016-03-02T09:04:07
2024-08-06T03:02:12
spring-security-oauth
Baeldung/spring-security-oauth
1,982
284
```java package com.baeldung.web.controller; import static org.apache.commons.lang3.RandomStringUtils.randomAlphabetic; import static org.apache.commons.lang3.RandomStringUtils.randomNumeric; import org.springframework.http.HttpStatus; import org.springframework.security.access.prepost.PreAuthorize; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.ResponseBody; import org.springframework.web.bind.annotation.ResponseStatus; import com.baeldung.web.dto.Foo; @Controller public class FooController { // API - read @PreAuthorize("#oauth2.hasScope('fooScope') and #oauth2.hasScope('readScope')") @RequestMapping(method = RequestMethod.GET, value = "/foos/{id}") @ResponseBody public Foo findById(@PathVariable final long id) { return new Foo(Long.parseLong(randomNumeric(2)), randomAlphabetic(4)); } // API - write @PreAuthorize("#oauth2.hasScope('fooScope') and #oauth2.hasScope('writeScope')") @RequestMapping(method = RequestMethod.POST, value = "/foos") @ResponseStatus(HttpStatus.CREATED) @ResponseBody public Foo create(@RequestBody final Foo foo) { foo.setId(Long.parseLong(randomNumeric(2))); return foo; } } ```
/content/code_sandbox/oauth-legacy/oauth-microservices/2x/resource-server-rest-2/src/main/java/com/baeldung/web/controller/FooController.java
java
2016-03-02T09:04:07
2024-08-06T03:02:12
spring-security-oauth
Baeldung/spring-security-oauth
1,982
284
```java package com.baeldung.web.dto; import lombok.AllArgsConstructor; import lombok.Data; import lombok.NoArgsConstructor; @Data @AllArgsConstructor @NoArgsConstructor public class Third { private long id; private String name; } ```
/content/code_sandbox/oauth-legacy/oauth-microservices/2x/resource-server-rest-2/src/main/java/com/baeldung/web/dto/Third.java
java
2016-03-02T09:04:07
2024-08-06T03:02:12
spring-security-oauth
Baeldung/spring-security-oauth
1,982
42
```java package com.baeldung.web.dto; import lombok.AllArgsConstructor; import lombok.Data; import lombok.NoArgsConstructor; @Data @AllArgsConstructor @NoArgsConstructor public class Bar { private long id; private String name; } ```
/content/code_sandbox/oauth-legacy/oauth-microservices/2x/resource-server-rest-2/src/main/java/com/baeldung/web/dto/Bar.java
java
2016-03-02T09:04:07
2024-08-06T03:02:12
spring-security-oauth
Baeldung/spring-security-oauth
1,982
42
```java package com.baeldung.web.controller; import java.util.Map; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.security.access.prepost.PreAuthorize; import org.springframework.security.oauth2.common.OAuth2AccessToken; import org.springframework.security.oauth2.provider.OAuth2Authentication; import org.springframework.security.oauth2.provider.authentication.OAuth2AuthenticationDetails; import org.springframework.security.oauth2.provider.token.TokenStore; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.ResponseBody; @Controller public class UserController { @Autowired private TokenStore tokenStore; @PreAuthorize("#oauth2.hasScope('readScope')") @RequestMapping(method = RequestMethod.GET, value = "/users/extra") @ResponseBody public Map<String, Object> getExtraInfo(OAuth2Authentication auth) { final OAuth2AuthenticationDetails details = (OAuth2AuthenticationDetails) auth.getDetails(); final OAuth2AccessToken accessToken = tokenStore.readAccessToken(details.getTokenValue()); System.out.println(accessToken); return accessToken.getAdditionalInformation(); } } ```
/content/code_sandbox/oauth-legacy/oauth-microservices/2x/resource-server-rest-2/src/main/java/com/baeldung/web/controller/UserController.java
java
2016-03-02T09:04:07
2024-08-06T03:02:12
spring-security-oauth
Baeldung/spring-security-oauth
1,982
227
```java package com.baeldung.web.dto; import lombok.AllArgsConstructor; import lombok.Data; import lombok.NoArgsConstructor; @Data @AllArgsConstructor @NoArgsConstructor public class Foo { private long id; private String name; } ```
/content/code_sandbox/oauth-legacy/oauth-microservices/2x/resource-server-rest-2/src/main/java/com/baeldung/web/dto/Foo.java
java
2016-03-02T09:04:07
2024-08-06T03:02:12
spring-security-oauth
Baeldung/spring-security-oauth
1,982
42
```java package com.baeldung; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import org.springframework.test.context.web.WebAppConfiguration; import com.baeldung.ResourceServerApplication; @RunWith(SpringJUnit4ClassRunner.class) @SpringBootTest(classes = ResourceServerApplication.class) @WebAppConfiguration public class ResourceServerApplicationTests { @Test public void contextLoads() { } } ```
/content/code_sandbox/oauth-legacy/oauth-microservices/1x/resource-server-mvc-no-oauth-1/src/test/java/com/baeldung/ResourceServerApplicationTests.java
java
2016-03-02T09:04:07
2024-08-06T03:02:12
spring-security-oauth
Baeldung/spring-security-oauth
1,982
99
```yaml spring: application: name: resource-server-mvc-1 server: port: 8870 eureka: instance: hostname: localhost port: 8761 client: serviceUrl: defaultZone: path_to_url{eureka.instance.hostname}:${eureka.instance.port}/eureka/ security: basic: enabled: false oauth2: resource: jwt: keyValue: "abc" id: fooScope service-id: ${PREFIX:}resource ```
/content/code_sandbox/oauth-legacy/oauth-microservices/1x/resource-server-mvc-no-oauth-1/src/main/resources/application.yml
yaml
2016-03-02T09:04:07
2024-08-06T03:02:12
spring-security-oauth
Baeldung/spring-security-oauth
1,982
113
```java package com.baeldung; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.cloud.client.discovery.EnableDiscoveryClient; @SpringBootApplication @EnableDiscoveryClient class ResourceServerApplication { public static void main(String[] args) { SpringApplication.run(ResourceServerApplication.class, args); } } ```
/content/code_sandbox/oauth-legacy/oauth-microservices/1x/resource-server-mvc-no-oauth-1/src/main/java/com/baeldung/ResourceServerApplication.java
java
2016-03-02T09:04:07
2024-08-06T03:02:12
spring-security-oauth
Baeldung/spring-security-oauth
1,982
65
```java package com.baeldung; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import com.baeldung.ServiceRegistryApplication; @RunWith(SpringJUnit4ClassRunner.class) @SpringBootTest(classes = ServiceRegistryApplication.class) public class ServiceDiscoveryApplicationTests { @Test public void contextLoads() { } } ```
/content/code_sandbox/oauth-legacy/oauth-microservices/1x/service-registry-1/src/test/java/com/baeldung/ServiceDiscoveryApplicationTests.java
java
2016-03-02T09:04:07
2024-08-06T03:02:12
spring-security-oauth
Baeldung/spring-security-oauth
1,982
85
```yaml spring: application: name: service-registry-1 server: port: 8761 eureka: instance: hostname: localhost port: ${server.port} client: registerWithEureka: false fetchRegistry: false serviceUrl: defaultZone: path_to_url{eureka.instance.hostname}:${server.port}/eureka/ server: waitTimeInMsWhenSyncEmpty: 0 ```
/content/code_sandbox/oauth-legacy/oauth-microservices/1x/service-registry-1/src/main/resources/application.yml
yaml
2016-03-02T09:04:07
2024-08-06T03:02:12
spring-security-oauth
Baeldung/spring-security-oauth
1,982
97
```java package com.baeldung; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.boot.autoconfigure.web.ServerProperties; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import com.baeldung.ApiGatewayApplication; @RunWith(SpringJUnit4ClassRunner.class) @SpringBootTest(classes = ApiGatewayApplication.class) public class ApiGatewayApplicationTests { @Configuration public static class ByPassConfiguration { @Bean public ServerProperties serverProperties() { return new ServerProperties(); } } @Test public void contextLoads() { } } ```
/content/code_sandbox/oauth-legacy/oauth-microservices/1x/api-gateway-zuul-1/src/test/java/com/baeldung/ApiGatewayApplicationTests.java
java
2016-03-02T09:04:07
2024-08-06T03:02:12
spring-security-oauth
Baeldung/spring-security-oauth
1,982
142
```java package com.baeldung; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.cloud.client.discovery.EnableDiscoveryClient; import org.springframework.cloud.netflix.zuul.EnableZuulProxy; @SpringBootApplication @EnableZuulProxy @EnableDiscoveryClient public class ApiGatewayApplication { public static void main(String[] args) { SpringApplication.run(ApiGatewayApplication.class, args); } } ```
/content/code_sandbox/oauth-legacy/oauth-microservices/1x/api-gateway-zuul-1/src/main/java/com/baeldung/ApiGatewayApplication.java
java
2016-03-02T09:04:07
2024-08-06T03:02:12
spring-security-oauth
Baeldung/spring-security-oauth
1,982
86
```yaml spring: aop: proxyTargetClass: true application: name: api-gateway-zuul-1 server: port: 8765 eureka: instance: hostname: localhost port: 8761 client: serviceUrl: defaultZone: path_to_url{eureka.instance.hostname}:${eureka.instance.port}/eureka/ zuul: routes: resource-server-mvc-1: /resource-server-mvc-1/** authorization-server-1: sensitiveHeaders: Authorization path: /authorization-server-1/** stripPrefix: false add-proxy-headers: true security: basic: enabled: false oauth2: sso: loginPath: /login client: accessTokenUri: path_to_url userAuthorizationUri: /authorization-server-1/oauth/authorize clientId: fooClient clientSecret: fooSecret resource: jwt: keyValue: "abc" id: fooScope serviceId: ${PREFIX:}resource logging: level.org.springframework.security: DEBUG ```
/content/code_sandbox/oauth-legacy/oauth-microservices/1x/api-gateway-zuul-1/src/main/resources/application.yml
yaml
2016-03-02T09:04:07
2024-08-06T03:02:12
spring-security-oauth
Baeldung/spring-security-oauth
1,982
242
```java package com.baeldung.security; import java.io.IOException; import java.util.Map; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.springframework.security.oauth2.client.filter.OAuth2ClientContextFilter; import org.springframework.security.oauth2.client.resource.UserRedirectRequiredException; import org.springframework.security.web.DefaultRedirectStrategy; import org.springframework.security.web.RedirectStrategy; import org.springframework.web.util.UriComponentsBuilder; class Oauth2ClientContextFilterWithPath extends OAuth2ClientContextFilter { private RedirectStrategy redirectStrategy = new DefaultRedirectStrategy(); @Override protected void redirectUser(UserRedirectRequiredException e, HttpServletRequest request, HttpServletResponse response) throws IOException { final String redirectUri = e.getRedirectUri(); final UriComponentsBuilder builder = UriComponentsBuilder.fromUriString(redirectUri); final Map<String, String> requestParams = e.getRequestParams(); for (Map.Entry<String, String> param : requestParams.entrySet()) { builder.queryParam(param.getKey(), param.getValue()); } if (e.getStateKey() != null) { builder.queryParam("state", e.getStateKey()); } String url = getBaseUrl(request) + builder.build().encode().toUriString(); this.redirectStrategy.sendRedirect(request, response, url); } @Override public void setRedirectStrategy(RedirectStrategy redirectStrategy) { this.redirectStrategy = redirectStrategy; } private String getBaseUrl(HttpServletRequest request) { StringBuffer url = request.getRequestURL(); return url.substring(0, url.length() - request.getRequestURI().length() + request.getContextPath().length()); } } ```
/content/code_sandbox/oauth-legacy/oauth-microservices/1x/api-gateway-zuul-1/src/main/java/com/baeldung/security/Oauth2ClientContextFilterWithPath.java
java
2016-03-02T09:04:07
2024-08-06T03:02:12
spring-security-oauth
Baeldung/spring-security-oauth
1,982
332
```java package com.baeldung.security; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.autoconfigure.security.oauth2.client.EnableOAuth2Sso; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.Primary; import org.springframework.core.annotation.Order; import org.springframework.security.authentication.AuthenticationManager; import org.springframework.security.config.annotation.web.builders.HttpSecurity; import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter; import org.springframework.security.oauth2.client.filter.OAuth2ClientContextFilter; import org.springframework.security.oauth2.config.annotation.web.configuration.EnableResourceServer; import org.springframework.security.oauth2.provider.authentication.OAuth2AuthenticationManager; import org.springframework.security.oauth2.provider.authentication.OAuth2AuthenticationProcessingFilter; import org.springframework.security.oauth2.provider.token.ResourceServerTokenServices; import org.springframework.security.web.authentication.preauth.AbstractPreAuthenticatedProcessingFilter; @Configuration @EnableOAuth2Sso @EnableResourceServer @Order(value = 0) public class SecurityConfiguration extends WebSecurityConfigurerAdapter { @Autowired private ResourceServerTokenServices resourceServerTokenServices; @Bean @Primary public OAuth2ClientContextFilter oauth2ClientContextFilterWithPath() { return new Oauth2ClientContextFilterWithPath(); } @Override public void configure(HttpSecurity http) throws Exception { // @formatter:off http.csrf().disable() .authorizeRequests() .antMatchers("/authorization-server-1/**", "/login").permitAll() .anyRequest().authenticated() .and().addFilterAfter(oAuth2AuthenticationProcessingFilter(), AbstractPreAuthenticatedProcessingFilter.class) .logout().permitAll().logoutSuccessUrl("/"); } // @formatter:on private OAuth2AuthenticationProcessingFilter oAuth2AuthenticationProcessingFilter() { OAuth2AuthenticationProcessingFilter oAuth2AuthenticationProcessingFilter = new OAuth2AuthenticationProcessingFilter(); oAuth2AuthenticationProcessingFilter.setAuthenticationManager(oauthAuthenticationManager()); oAuth2AuthenticationProcessingFilter.setStateless(false); return oAuth2AuthenticationProcessingFilter; } private AuthenticationManager oauthAuthenticationManager() { OAuth2AuthenticationManager oAuth2AuthenticationManager = new OAuth2AuthenticationManager(); oAuth2AuthenticationManager.setResourceId("apigateway"); oAuth2AuthenticationManager.setTokenServices(resourceServerTokenServices); oAuth2AuthenticationManager.setClientDetailsService(null); return oAuth2AuthenticationManager; } } ```
/content/code_sandbox/oauth-legacy/oauth-microservices/1x/api-gateway-zuul-1/src/main/java/com/baeldung/security/SecurityConfiguration.java
java
2016-03-02T09:04:07
2024-08-06T03:02:12
spring-security-oauth
Baeldung/spring-security-oauth
1,982
498
```java package com.baeldung; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.cloud.client.discovery.EnableDiscoveryClient; import org.springframework.security.oauth2.config.annotation.web.configuration.EnableResourceServer; @SpringBootApplication @EnableResourceServer @EnableDiscoveryClient class ResourceServerApplication { public static void main(String[] args) { SpringApplication.run(ResourceServerApplication.class, args); } } ```
/content/code_sandbox/oauth-legacy/oauth-microservices/1x/resource-server-mvc-1/src/main/java/com/baeldung/ResourceServerApplication.java
java
2016-03-02T09:04:07
2024-08-06T03:02:12
spring-security-oauth
Baeldung/spring-security-oauth
1,982
83
```java package com.baeldung; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import com.baeldung.UaaServiceApplication; @RunWith(SpringJUnit4ClassRunner.class) @SpringBootTest(classes = UaaServiceApplication.class) public class UaaServiceApplicationTests { @Test public void contextLoads() { } } ```
/content/code_sandbox/oauth-legacy/oauth-microservices/1x/authorization-server-1/src/test/java/com/baeldung/UaaServiceApplicationTests.java
java
2016-03-02T09:04:07
2024-08-06T03:02:12
spring-security-oauth
Baeldung/spring-security-oauth
1,982
88
```yaml spring: application: name: authorization-server-1 server: port: 8769 context-path: /authorization-server-1 use-forward-headers: false eureka: instance: hostname: localhost port: 8761 client: serviceUrl: defaultZone: path_to_url{eureka.instance.hostname}:${eureka.instance.port}/eureka/ security: basic: enabled: false user: password: password ignored: /css/**,/js/**,/favicon.ico,/webjars/** logging: level.org.springframework.security: DEBUG ```
/content/code_sandbox/oauth-legacy/oauth-microservices/1x/authorization-server-1/src/main/resources/application.yml
yaml
2016-03-02T09:04:07
2024-08-06T03:02:12
spring-security-oauth
Baeldung/spring-security-oauth
1,982
132
```freemarker <html> <head> </head> <body> <div class="container"> <form role="form" action="login" method="post"> <div class="form-group"> <label for="username">Username:</label> <input type="text" class="form-control" id="username" name="username"/> </div> <div class="form-group"> <label for="password">Password:</label> <input type="password" class="form-control" id="password" name="password"/> </div> <button type="submit" class="btn btn-primary">Submit</button> </form> </div> </body> </html> ```
/content/code_sandbox/oauth-legacy/oauth-microservices/1x/authorization-server-1/src/main/resources/templates/login.ftl
freemarker
2016-03-02T09:04:07
2024-08-06T03:02:12
spring-security-oauth
Baeldung/spring-security-oauth
1,982
146
```freemarker <html> <head> </head> <body> <div class="container"> <h2>Please Confirm</h2> <p> Do you authorize "${authorizationRequest.clientId}" at "${authorizationRequest.redirectUri}" to access your protected resources with scope ${authorizationRequest.scope?join(", ")}. </p> <form id="confirmationForm" name="confirmationForm" action="../oauth/authorize" method="post"> <input name="user_oauth_approval" value="true" type="hidden"/> <button class="btn btn-primary" type="submit">Approve</button> </form> <form id="denyForm" name="confirmationForm" action="../oauth/authorize" method="post"> <input name="user_oauth_approval" value="false" type="hidden"/> <button class="btn btn-primary" type="submit">Deny</button> </form> </div> </body> </html> ```
/content/code_sandbox/oauth-legacy/oauth-microservices/1x/authorization-server-1/src/main/resources/templates/authorize.ftl
freemarker
2016-03-02T09:04:07
2024-08-06T03:02:12
spring-security-oauth
Baeldung/spring-security-oauth
1,982
206
```java package com.baeldung; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.cloud.client.discovery.EnableDiscoveryClient; @SpringBootApplication @EnableDiscoveryClient public class UaaServiceApplication { public static void main(String[] args) { SpringApplication.run(UaaServiceApplication.class, args); } } ```
/content/code_sandbox/oauth-legacy/oauth-microservices/1x/authorization-server-1/src/main/java/com/baeldung/UaaServiceApplication.java
java
2016-03-02T09:04:07
2024-08-06T03:02:12
spring-security-oauth
Baeldung/spring-security-oauth
1,982
68
```java package com.baeldung.config; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.actuate.autoconfigure.ManagementServerProperties; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.core.annotation.Order; import org.springframework.security.authentication.AuthenticationManager; import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder; import org.springframework.security.config.annotation.web.builders.HttpSecurity; import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter; @Order(ManagementServerProperties.ACCESS_OVERRIDE_ORDER) @Configuration public class WebSecurityConfig extends WebSecurityConfigurerAdapter { @Override protected void configure(HttpSecurity http) throws Exception { // @formatter:off http.csrf().disable() .authorizeRequests() .anyRequest().authenticated() .and().formLogin().loginPage("/login").permitAll(); }// @formatter:on @Autowired public void globalUserDetails(final AuthenticationManagerBuilder auth) throws Exception { // @formatter:off auth.inMemoryAuthentication() .withUser("user").password("password").roles("USER") .and().withUser("admin").password("admin").roles("ADMIN"); }// @formatter:on @Override @Bean public AuthenticationManager authenticationManagerBean() throws Exception { return super.authenticationManagerBean(); } } ```
/content/code_sandbox/oauth-legacy/oauth-microservices/1x/authorization-server-1/src/main/java/com/baeldung/config/WebSecurityConfig.java
java
2016-03-02T09:04:07
2024-08-06T03:02:12
spring-security-oauth
Baeldung/spring-security-oauth
1,982
274
```java package com.baeldung.config; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Qualifier; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.security.authentication.AuthenticationManager; import org.springframework.security.oauth2.config.annotation.configurers.ClientDetailsServiceConfigurer; import org.springframework.security.oauth2.config.annotation.web.configuration.AuthorizationServerConfigurerAdapter; import org.springframework.security.oauth2.config.annotation.web.configuration.EnableAuthorizationServer; import org.springframework.security.oauth2.config.annotation.web.configurers.AuthorizationServerEndpointsConfigurer; import org.springframework.security.oauth2.config.annotation.web.configurers.AuthorizationServerSecurityConfigurer; import org.springframework.security.oauth2.provider.token.TokenStore; import org.springframework.security.oauth2.provider.token.store.JwtAccessTokenConverter; import org.springframework.security.oauth2.provider.token.store.JwtTokenStore; @Configuration @EnableAuthorizationServer public class OAuth2AuthorizationServerConfig extends AuthorizationServerConfigurerAdapter { @Autowired @Qualifier("authenticationManagerBean") private AuthenticationManager authenticationManager; @Override public void configure(ClientDetailsServiceConfigurer clients) throws Exception { clients.inMemory().withClient("fooClient").secret("fooSecret").authorizedGrantTypes("authorization_code", "refresh_token").scopes("fooScope"); } @Override public void configure(AuthorizationServerSecurityConfigurer oauthServer) throws Exception { oauthServer.tokenKeyAccess("permitAll()").checkTokenAccess("isAuthenticated()"); } @Override public void configure(AuthorizationServerEndpointsConfigurer endpoints) throws Exception { endpoints.tokenStore(tokenStore()).authenticationManager(authenticationManager).accessTokenConverter(jwtAccessTokenConverter()); } @Bean public TokenStore tokenStore() { return new JwtTokenStore(jwtAccessTokenConverter()); } @Bean public JwtAccessTokenConverter jwtAccessTokenConverter() { JwtAccessTokenConverter converter = new JwtAccessTokenConverter(); converter.setSigningKey("abc"); return converter; } } ```
/content/code_sandbox/oauth-legacy/oauth-microservices/1x/authorization-server-1/src/main/java/com/baeldung/config/OAuth2AuthorizationServerConfig.java
java
2016-03-02T09:04:07
2024-08-06T03:02:12
spring-security-oauth
Baeldung/spring-security-oauth
1,982
395
```java package com.baeldung.config; import org.springframework.boot.web.servlet.FilterRegistrationBean; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.core.Ordered; import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity; import org.springframework.web.filter.ForwardedHeaderFilter; import org.springframework.web.servlet.config.annotation.EnableWebMvc; import org.springframework.web.servlet.config.annotation.ViewControllerRegistry; import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter; @Configuration @EnableWebSecurity @EnableWebMvc public class WebConfig extends WebMvcConfigurerAdapter { @Bean FilterRegistrationBean forwardedHeaderFilter() { FilterRegistrationBean filterRegBean = new FilterRegistrationBean(); filterRegBean.setFilter(new ForwardedHeaderFilter()); filterRegBean.setOrder(Ordered.HIGHEST_PRECEDENCE); return filterRegBean; } @Override public void addViewControllers(ViewControllerRegistry registry) { registry.addViewController("/login").setViewName("login"); registry.addViewController("/oauth/confirm_access").setViewName("authorize"); } } ```
/content/code_sandbox/oauth-legacy/oauth-microservices/1x/authorization-server-1/src/main/java/com/baeldung/config/WebConfig.java
java
2016-03-02T09:04:07
2024-08-06T03:02:12
spring-security-oauth
Baeldung/spring-security-oauth
1,982
225
```html <!doctype html> <html> <head> <meta charset="utf-8"> <title>OauthPassword</title> <base href="/"> <meta name="viewport" content="width=device-width, initial-scale=1"> <link rel="stylesheet" href="path_to_url"/> </head> <body> <app-root>Loading...</app-root> </body> </html> ```
/content/code_sandbox/oauth-legacy/oauth-ui-password-angular-legacy/src/main/resources/src/index.html
html
2016-03-02T09:04:07
2024-08-06T03:02:12
spring-security-oauth
Baeldung/spring-security-oauth
1,982
84
```yaml server: port: 8080 zuul: sensitiveHeaders: Cookie,Set-Cookie routes: spring-security-oauth-resource: path: /spring-security-oauth-resource/** url: path_to_url oauth: path: /oauth/** url: path_to_url security: oauth2: resource: jwt: key-value: 123 ```
/content/code_sandbox/oauth-legacy/oauth-zuul-gateway/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
85
```java package org.baeldung; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.cloud.netflix.zuul.EnableZuulProxy; import org.springframework.security.oauth2.config.annotation.web.configuration.EnableResourceServer; @EnableResourceServer @EnableZuulProxy @SpringBootApplication public class GatewayApplication { public static void main(String[] args) { SpringApplication.run(GatewayApplication.class, args); } } ```
/content/code_sandbox/oauth-legacy/oauth-zuul-gateway/src/main/java/org/baeldung/GatewayApplication.java
java
2016-03-02T09:04:07
2024-08-06T03:02:12
spring-security-oauth
Baeldung/spring-security-oauth
1,982
88