Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

first improvements #4

Open
wants to merge 3 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
@@ -1 +1,3 @@
oauth2

Full Article: <https://medium.com/@akourtim.ahmed/oauth-2-centralized-authorization-with-spring-boot-2-0-2-and-spring-security-5-and-jdbc-token-store-8dbc063bd5d4>
4 changes: 3 additions & 1 deletion authorization_server/.gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -15,11 +15,13 @@
*.iws
*.iml
*.ipr
.gradle
/out/

### NetBeans ###
/nbproject/private/
/build/
/nbbuild/
/dist/
/nbdist/
/.nb-gradle/
/.nb-gradle/
75 changes: 75 additions & 0 deletions authorization_server/build.gradle
Original file line number Diff line number Diff line change
@@ -0,0 +1,75 @@
apply plugin: 'java'
apply plugin: 'idea'
apply plugin: 'org.springframework.boot'
apply plugin: 'io.spring.dependency-management'

tasks.withType(JavaCompile) {
options.encoding = "UTF-8"
}

buildscript {
repositories {
mavenLocal()
mavenCentral()
}
dependencies {
classpath("org.springframework.boot:spring-boot-gradle-plugin:2.0.4.RELEASE")
}
}

group 'com.aak'
version '0.0.2-SNAPSHOT'

sourceCompatibility = 1.8
targetCompatibility = 1.8

jar {
baseName = 'authorization_server'
version = '0.0.2'
from "gradle.properties"
}

springBoot {
mainClassName = "com.aak.AuthorizationServerApplication"

}

idea {
project {
languageLevel = '1.8'
}
module {
downloadJavadoc = true
downloadSources = true
}
}

configurations {
compile.exclude module: 'spring-boot-starter-tomcat' // we exchange tomcat with jetty
}

repositories {
mavenLocal()
mavenCentral()
}

dependencies {
compile 'org.springframework.boot:spring-boot-devtools'
compile 'org.springframework.boot:spring-boot-starter-actuator'
compile 'org.springframework.boot:spring-boot-starter-jetty'
compile 'org.springframework.boot:spring-boot-starter-data-rest'
compile 'org.springframework.boot:spring-boot-starter-security'
compile 'org.springframework.boot:spring-boot-starter-thymeleaf'
compile 'org.springframework.boot:spring-boot-starter-web'
compile 'org.springframework.boot:spring-boot-starter-data-jpa'
compile 'org.springframework.boot:spring-boot-starter-jdbc'
compile 'com.h2database:h2'
compile 'org.springframework.cloud:spring-cloud-starter-oauth2:2.0.0.RELEASE'
compile 'org.webjars:bootstrap:4.1.3'

compile 'org.springframework.security.oauth.boot:spring-security-oauth2-autoconfigure:2.0.4.RELEASE'
compile 'org.springframework.security.oauth:spring-security-oauth2:2.3.3.RELEASE'

testCompile 'org.springframework.boot:spring-boot-starter-test'
testCompile 'org.springframework.security:spring-security-test'
}
Original file line number Diff line number Diff line change
@@ -1,19 +1,10 @@
package com.aak;

import com.zaxxer.hikari.HikariDataSource;
import org.apache.catalina.servlets.WebdavServlet;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.boot.jdbc.DataSourceBuilder;
import org.springframework.boot.web.servlet.ServletRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;

import javax.sql.DataSource;


@SpringBootApplication
Expand All @@ -22,13 +13,6 @@
@ComponentScan
public class AuthorizationServerApplication {

@Bean
@Primary
@ConfigurationProperties(prefix = "spring.datasource")
public DataSource mainDataSource() {
return DataSourceBuilder.create().type(HikariDataSource.class).build();
}

public static void main(String[] args) {
SpringApplication.run(AuthorizationServerApplication.class, args);
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,6 @@
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.oauth2.provider.ClientDetails;
import org.springframework.security.oauth2.provider.client.BaseClientDetails;
import org.springframework.security.oauth2.provider.client.JdbcClientDetailsService;
import org.springframework.stereotype.Controller;
Expand All @@ -14,6 +13,7 @@
import org.springframework.web.bind.annotation.*;

import java.util.Collection;
import java.util.Optional;
import java.util.Set;

/**
Expand All @@ -36,16 +36,9 @@ public void initBinder(WebDataBinder binder){
@RequestMapping(value="/form",method= RequestMethod.GET)
@PreAuthorize("hasRole('ROLE_OAUTH_ADMIN')")
public String showEditForm(@RequestParam(value="client",required=false)String clientId, Model model){

ClientDetails clientDetails;
if(clientId !=null){
clientDetails=clientsDetailsService.loadClientByClientId(clientId);
}
else{
clientDetails =new BaseClientDetails();
}

model.addAttribute("clientDetails",clientDetails);
model.addAttribute("clientDetails", Optional.ofNullable(clientId)
.map(clientsDetailsService::loadClientByClientId)
.orElse(new BaseClientDetails()));
return "form";
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,7 @@
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import static java.util.Arrays.asList;

/**
Expand Down Expand Up @@ -67,7 +68,6 @@ public String loginPage() {
}



@RequestMapping(value="/logout", method = RequestMethod.GET)
public String logoutPage (HttpServletRequest request, HttpServletResponse response) {
Authentication auth = SecurityContextHolder.getContext().getAuthentication();
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -58,7 +58,11 @@ public void configure(ClientDetailsServiceConfigurer clients) throws Exception {

@Override
public void configure(AuthorizationServerSecurityConfigurer oauthServer) throws Exception {

// grant access to token_key and check_token endpoints for authenticated user
// isAuthenticated() because all clients are trusted clients
// see: http://projects.spring.io/spring-security-oauth/docs/oauth2.html#resource-server-configuration
oauthServer.tokenKeyAccess("isAuthenticated()")
.checkTokenAccess("isAuthenticated()");
}

@Override
Expand Down
Original file line number Diff line number Diff line change
@@ -1,14 +1,13 @@
package com.aak.configuration;

import com.aak.domain.Credentials;
import com.aak.repository.CredentialRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.factory.PasswordEncoderFactories;
import org.springframework.security.crypto.password.PasswordEncoder;

import java.util.Optional;

/**
* Created by ahmed on 21.5.18.
Expand All @@ -20,18 +19,9 @@ public class JdbcUserDetails implements UserDetailsService{

@Override
public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
Credentials credentials = credentialRepository.findByName(username);


if(credentials==null){

throw new UsernameNotFoundException("User"+username+"can not be found");
}

User user = new User(credentials.getName(),credentials.getPassword(),credentials.isEnabled(),true,true,true,credentials.getAuthorities());

return user;


return Optional.ofNullable(username)
.map(credentialRepository::findByName)
.map(i -> new User(i.getName(),i.getPassword(),i.isEnabled(),true,true,true,i.getAuthorities()))
.orElseThrow(() -> new UsernameNotFoundException("User"+String.valueOf(username)+"can not be found"));
}
}
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
package com.aak.configuration;

import org.springframework.beans.propertyeditors.CustomCollectionEditor;
import org.springframework.util.StringUtils;

import java.util.Collection;

Expand All @@ -20,7 +21,7 @@ public SplitCollectionEditor(Class<? extends Collection> collectionType, String

@Override
public void setAsText(String text) throws IllegalArgumentException {
if (text == null || text.isEmpty()) {
if (StringUtils.isEmpty(text)) {
super.setValue(super.createCollection(this.collectionType, 0));
} else {
super.setValue(text.split(splitRegex));
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,6 @@
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.provisioning.JdbcUserDetailsManager;
import org.springframework.security.web.util.matcher.AntPathRequestMatcher;

/**
Expand All @@ -34,7 +33,9 @@ public UserDetailsService userDetailsServiceBean() throws Exception {

@Override
public void configure(WebSecurity web) throws Exception {
web.ignoring().antMatchers("/webjars/**","/resources/**");
web.ignoring().antMatchers("/webjars/**","/resources/**"
,"/h2-console/**","/actuator/**" // <-- remove this in production code
);

}

Expand Down
36 changes: 20 additions & 16 deletions authorization_server/src/main/resources/application.yml
Original file line number Diff line number Diff line change
@@ -1,20 +1,24 @@
spring:
datasource:
hikari:
connection-test-query: SELECT 1 FROM DUAL
minimum-idle: 1
maximum-pool-size: 5
driver-class-name: com.mysql.jdbc.Driver
jdbc-url: jdbc:mysql://localhost/oauth2
username: root
password:
initialization-mode: always
jpa:
hibernate:
ddl-auto: none
# --- server
server:
port: 8081

spring:
jackson:
serialization:
INDENT_OUTPUT: true
h2:
console:
enabled: true
datasource:
jdbc-url: jdbc:h2:mem:oauth;DB_CLOSE_DELAY=-1
driver-class-name: org.h2.Driver
username: root
password:
initialization-mode: always
jpa:
hibernate:
ddl-auto: none
database-platform: org.hibernate.dialect.H2Dialect


logging:
level:
org.springframework.security: DEBUG
17 changes: 8 additions & 9 deletions authorization_server/src/main/resources/data.sql
Original file line number Diff line number Diff line change
@@ -1,12 +1,11 @@
INSERT INTO authority VALUES(1,'ROLE_OAUTH_ADMIN');
INSERT INTO authority VALUES(1,'ROLE_OAUTH_ADMIN');
INSERT INTO authority VALUES(2,'ROLE_RESOURCE_ADMIN');
INSERT INTO authority VALUES(3,'ROLE_PRODUCT_ADMIN');
INSERT INTO credentials VALUES(1,b'1','oauth_admin','$2a$10$BurTWIy5NTF9GJJH4magz.9Bd4bBurWYG8tmXxeQh1vs7r/wnCFG2','0');
INSERT INTO credentials VALUES(2,b'1','resource_admin','$2a$10$BurTWIy5NTF9GJJH4magz.9Bd4bBurWYG8tmXxeQh1vs7r/wnCFG2','0');
INSERT INTO credentials VALUES(3,b'1','product_admin','$2a$10$BurTWIy5NTF9GJJH4magz.9Bd4bBurWYG8tmXxeQh1vs7r/wnCFG2','0');
INSERT INTO credentials_authorities VALUE (1,1);
INSERT INTO credentials_authorities VALUE (2,2);
INSERT INTO credentials_authorities VALUE (3,3);
INSERT INTO credentials VALUES(1,'1','oauth_admin','$2a$10$BurTWIy5NTF9GJJH4magz.9Bd4bBurWYG8tmXxeQh1vs7r/wnCFG2','0');
INSERT INTO credentials VALUES(2,'1','resource_admin','$2a$10$BurTWIy5NTF9GJJH4magz.9Bd4bBurWYG8tmXxeQh1vs7r/wnCFG2','0');
INSERT INTO credentials VALUES(3,'1','product_admin','$2a$10$BurTWIy5NTF9GJJH4magz.9Bd4bBurWYG8tmXxeQh1vs7r/wnCFG2','0');
INSERT INTO credentials_authorities VALUES (1,1);
INSERT INTO credentials_authorities VALUES (2,2);
INSERT INTO credentials_authorities VALUES (3,3);


INSERT INTO oauth_client_details VALUES('curl_client','product_api', '$2a$10$BurTWIy5NTF9GJJH4magz.9Bd4bBurWYG8tmXxeQh1vs7r/wnCFG2', 'read,write', 'client_credentials', 'http://127.0.0.1', 'ROLE_PRODUCT_ADMIN', 7200, 0, NULL, 'true');
INSERT INTO oauth_client_details VALUES('curl_client','product_api', '$2a$10$BurTWIy5NTF9GJJH4magz.9Bd4bBurWYG8tmXxeQh1vs7r/wnCFG2', 'read,write', 'password,client_credentials,authorization_code,refresh_token', 'http://127.0.0.1', 'ROLE_PRODUCT_ADMIN', 7200, 0, NULL, 'true');
1 change: 0 additions & 1 deletion authorization_server/src/main/resources/schema.sql
Original file line number Diff line number Diff line change
Expand Up @@ -43,7 +43,6 @@ CREATE TABLE authority (
primary key (id)
);
drop table if exists credentials;

CREATE TABLE credentials (
id integer,
enabled boolean not null,
Expand Down
Loading