Skip to content

Commit

Permalink
SecurityConfig and README.md are updated. OpenAPIConfiguration is added
Browse files Browse the repository at this point in the history
  • Loading branch information
musab.bozkurt committed Jul 6, 2024
1 parent 872d416 commit dab8f5f
Show file tree
Hide file tree
Showing 4 changed files with 51 additions and 18 deletions.
12 changes: 10 additions & 2 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -2,20 +2,28 @@

#### Prerequisites

- Java 21+ should be installed
- Java 21 should be installed --> `export JAVA_HOME=$(/usr/libexec/java_home -v 21)`
- Maven should be installed
- Docker should be installed
- Postman can be installed
- Swagger: http://localhost:9000/swagger-ui/index.html

#### How to Run and Test

- Run `mvn test` or `mvn clean install` or `mvn clean package` command to run all the tests
- `mvn spring-boot:run`
- Swagger: http://localhost:9000/swagger-ui/index.html
- Click `Authorize` and enter the following credentials
- `client_id`: `client`
- `client_secret`: `secret`
- Import [OAuth2 Authorization Server.postman_collection.json](OAuth2%20Authorization%20Server.postman_collection.json)
- Use one of the following default values
- username: `Developer` password: `password`
- username: `Admin` password: `password`
- username: `User` password: `password`
- Database credentials
- `url`: `jdbc:mariadb://localhost:3306/oauth2_authorization_server`
- `username`: `mb_test`
- `password`: `test`

### References

Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
package mb.oauth2authorizationserver.config;

import io.swagger.v3.oas.annotations.OpenAPIDefinition;
import io.swagger.v3.oas.annotations.enums.SecuritySchemeType;
import io.swagger.v3.oas.annotations.info.Info;
import io.swagger.v3.oas.annotations.security.OAuthFlow;
import io.swagger.v3.oas.annotations.security.OAuthFlows;
import io.swagger.v3.oas.annotations.security.OAuthScope;
import io.swagger.v3.oas.annotations.security.SecurityScheme;
import io.swagger.v3.oas.annotations.servers.Server;

@OpenAPIDefinition(servers = {@Server(url = "${openapi.url}")}, info = @Info(title = "${openapi.title}", description = "${openapi.description}", version = "${openapi.version}"))
@SecurityScheme(name = "security_auth", type = SecuritySchemeType.OAUTH2,
flows = @OAuthFlows(clientCredentials = @OAuthFlow(tokenUrl = "${openapi.oauth-flow.token-url}", scopes = {@OAuthScope(name = "openid", description = "openid scope")})))
public class OpenAPIConfiguration {
}
Original file line number Diff line number Diff line change
Expand Up @@ -22,10 +22,10 @@
import org.springframework.context.annotation.Configuration;
import org.springframework.core.annotation.Order;
import org.springframework.security.authentication.AuthenticationProvider;
import org.springframework.security.config.Customizer;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configurers.AbstractHttpConfigurer;
import org.springframework.security.config.annotation.web.configurers.oauth2.server.resource.OAuth2ResourceServerConfigurer;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.userdetails.UserDetailsService;
Expand All @@ -49,8 +49,6 @@
import java.util.function.Consumer;
import java.util.stream.Collectors;

import static org.springframework.security.config.Customizer.withDefaults;

@Slf4j
@Configuration
@EnableWebSecurity
Expand All @@ -66,26 +64,29 @@ public class SecurityConfig {

@Bean
@Order(1)
SecurityFilterChain asSecurityFilterChain(HttpSecurity httpSecurity) throws Exception {
public SecurityFilterChain asSecurityFilterChain(HttpSecurity httpSecurity) throws Exception {
OAuth2AuthorizationServerConfiguration.applyDefaultSecurity(httpSecurity);
OAuth2AuthorizationService oAuth2AuthorizationService = new OAuth2AuthorizationServiceImpl(authorizationRepository, authorizationBuilderService);

return httpSecurity
httpSecurity
.getConfigurer(OAuth2AuthorizationServerConfigurer.class)
.oidc(Customizer.withDefaults()); // Enable OpenID Connect 1.0

httpSecurity
.cors(AbstractHttpConfigurer::disable)
.csrf(AbstractHttpConfigurer::disable)
.oauth2ResourceServer(httpSecurityOAuth2ResourceServerConfigurer -> httpSecurityOAuth2ResourceServerConfigurer.jwt(Customizer.withDefaults()))
.exceptionHandling(e -> e.authenticationEntryPoint(new LoginUrlAuthenticationEntryPoint("/login")))
.getConfigurer(OAuth2AuthorizationServerConfigurer.class)
.tokenEndpoint(tokenEndpoint -> tokenEndpoint
.accessTokenRequestConverter(new CustomPasswordAuthenticationConverter())
.authenticationProvider(new CustomPasswordAuthenticationProvider(oAuth2AuthorizationService, tokenGenerator(), userDetailsService(), passwordEncoder()))
.accessTokenRequestConverter(new JwtBearerGrantAuthenticationConverter())
.authenticationProvider(new JwtBearerGrantAuthenticationProvider(oAuth2AuthorizationService, tokenGenerator()))
.accessTokenRequestConverters(getConverters())
.authenticationProviders(getProviders()))
.oidc(withDefaults())
.and()
.exceptionHandling(e -> e.authenticationEntryPoint(new LoginUrlAuthenticationEntryPoint("/login")))
.oauth2ResourceServer(OAuth2ResourceServerConfigurer::jwt)
.build();
.authenticationProviders(getProviders()));

return httpSecurity.build();
}

@Bean
Expand Down Expand Up @@ -113,9 +114,9 @@ private Consumer<List<AuthenticationConverter>> getConverters() {

@Bean
@Order(2)
SecurityFilterChain appSecurityFilterChain(HttpSecurity http) throws Exception {
public SecurityFilterChain appSecurityFilterChain(HttpSecurity http) throws Exception {
return http
.formLogin(withDefaults())
.formLogin(Customizer.withDefaults())
.authorizeHttpRequests(authorizationManagerRequestMatcherRegistry -> authorizationManagerRequestMatcherRegistry
.requestMatchers(
"%s/**".formatted(apiDocsPath),
Expand Down
14 changes: 11 additions & 3 deletions src/main/resources/application.yml
Original file line number Diff line number Diff line change
Expand Up @@ -3,9 +3,9 @@ server:

spring:
datasource:
url: 'jdbc:mariadb://localhost:3306/oauth2_authorization_server'
username: mb_test
password: 'test'
url: ${DB_URL:jdbc:mariadb://localhost:3306/oauth2_authorization_server}
username: ${DB_USERNAME:mb_test}
password: ${DB_PASSWORD:test}
driver-class-name: org.mariadb.jdbc.Driver

flyway:
Expand Down Expand Up @@ -44,3 +44,11 @@ springdoc:
path: /swagger-ui.html # http://localhost:9000/swagger-ui/index.html
csrf:
enabled: true

openapi:
url: ${OPENAPI_URL:http://localhost:9000}
title: ${OPENAPI_TITLE:OAuth2 Authorization Server}
description: ${OPENAPI_DESCRIPTION:This lists all the OAuth2 Authorization Server API Calls. The Calls are OAuth2 secured, so please use your Client ID and Secret to test them out.}
version: ${OPENAPI_VERSION:v1.0}
oauth-flow:
token-url: ${OPENAPI_OAUTH_FLOW_TOKEN_URL:http://localhost:9000/oauth2/token}

0 comments on commit dab8f5f

Please sign in to comment.