├── README.md ├── authserver ├── src │ └── main │ │ ├── java │ │ └── com │ │ │ └── talk2amareswaran │ │ │ └── projects │ │ │ └── authserver │ │ │ ├── dao │ │ │ ├── OAuthDAOService.java │ │ │ └── OAuthDAOServiceImpl.java │ │ │ ├── AuthserverApplication.java │ │ │ ├── model │ │ │ ├── CustomUser.java │ │ │ └── UserEntity.java │ │ │ ├── config │ │ │ ├── CustomTokenEnhancer.java │ │ │ ├── SecurityConfiguration.java │ │ │ └── OAuth2Config.java │ │ │ └── service │ │ │ └── CustomUserDetailsService.java │ │ └── resources │ │ └── application.yml └── build.gradle ├── resourceserver ├── src │ └── main │ │ ├── java │ │ └── com │ │ │ └── talk2amareswaran │ │ │ └── projects │ │ │ └── resourceserver │ │ │ ├── ResourceserverApplication.java │ │ │ ├── model │ │ │ └── AccessTokenMapper.java │ │ │ ├── config │ │ │ ├── SecurityConfiguration.java │ │ │ └── JwtConverter.java │ │ │ └── rest │ │ │ └── NoteServiceController.java │ │ └── resources │ │ └── application.yml └── build.gradle └── SQL-SCRIPTS.txt /README.md: -------------------------------------------------------------------------------- 1 | # Spring-Boot-2.1-OAuth2-Authorization-Server-and-Resource-Server-JWT-and-MySQL 2 | Spring Boot 2.1 OAuth2 Authorization Server and Resource Server JWT and MySQL 3 | 4 | 5 | Youtube video link - https://youtu.be/l9chhjL7Kuk 6 | -------------------------------------------------------------------------------- /authserver/src/main/java/com/talk2amareswaran/projects/authserver/dao/OAuthDAOService.java: -------------------------------------------------------------------------------- 1 | package com.talk2amareswaran.projects.authserver.dao; 2 | 3 | import com.talk2amareswaran.projects.authserver.model.UserEntity; 4 | 5 | public interface OAuthDAOService { 6 | 7 | public UserEntity getUserDetails(String emailId); 8 | } 9 | -------------------------------------------------------------------------------- /authserver/src/main/java/com/talk2amareswaran/projects/authserver/AuthserverApplication.java: -------------------------------------------------------------------------------- 1 | package com.talk2amareswaran.projects.authserver; 2 | 3 | import org.springframework.boot.SpringApplication; 4 | import org.springframework.boot.autoconfigure.SpringBootApplication; 5 | import org.springframework.security.oauth2.config.annotation.web.configuration.EnableAuthorizationServer; 6 | 7 | @SpringBootApplication 8 | @EnableAuthorizationServer 9 | public class AuthserverApplication { 10 | 11 | public static void main(String[] args) { 12 | SpringApplication.run(AuthserverApplication.class, args); 13 | } 14 | 15 | } 16 | -------------------------------------------------------------------------------- /resourceserver/src/main/java/com/talk2amareswaran/projects/resourceserver/ResourceserverApplication.java: -------------------------------------------------------------------------------- 1 | package com.talk2amareswaran.projects.resourceserver; 2 | 3 | import org.springframework.boot.SpringApplication; 4 | import org.springframework.boot.autoconfigure.SpringBootApplication; 5 | import org.springframework.security.oauth2.config.annotation.web.configuration.EnableResourceServer; 6 | 7 | @SpringBootApplication 8 | @EnableResourceServer 9 | public class ResourceserverApplication { 10 | 11 | public static void main(String[] args) { 12 | SpringApplication.run(ResourceserverApplication.class, args); 13 | } 14 | 15 | } 16 | -------------------------------------------------------------------------------- /resourceserver/src/main/resources/application.yml: -------------------------------------------------------------------------------- 1 | spring: 2 | application: 3 | name: resourceserver 4 | 5 | security: 6 | oauth2: 7 | resource: 8 | jwt: 9 | key-value: -----BEGIN PUBLIC KEY-----MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAsY9wY6rwdql0GCPFxu7eEypLC8TkDQHgaFlmP5QBf7Il4/8/ogTrT1cLF/fMrfhoJrPeZWjzP6NmaxttCUcki8JSbmaxdYNnIPHsPFvqr1DlpvikdKiG5lkKS27E9uUQ1XmeXh9Vhn9QwLQyXl5bbbjlDewiCzB/MuKlbuuxFsb7ZPpBD+rE69efUfTu8dZPa5QzTugqxqAe9q2soLPxYyh91BGjVGWMN9wwWnM+WaQ9IehuQko7drlvJRVhPow9zvzTanaJckn02+Ubj5+LFQ8yYNe/PQQSS+noaQtmCqRfVhL161F6yivj16EuYJhkUn3TQQTbDhSU3CcdMcX5lQIDAQAB-----END PUBLIC KEY----- 10 | 11 | server: 12 | port: 9090 -------------------------------------------------------------------------------- /resourceserver/build.gradle: -------------------------------------------------------------------------------- 1 | plugins { 2 | id 'org.springframework.boot' version '2.1.7.RELEASE' 3 | id 'io.spring.dependency-management' version '1.0.8.RELEASE' 4 | id 'java' 5 | } 6 | 7 | group = 'com.talk2amareswaran.projects' 8 | version = '0.0.1-SNAPSHOT' 9 | sourceCompatibility = '1.8' 10 | 11 | repositories { 12 | mavenCentral() 13 | } 14 | 15 | ext { 16 | set('springCloudVersion', "Greenwich.SR2") 17 | } 18 | 19 | dependencies { 20 | implementation 'org.springframework.boot:spring-boot-starter-web' 21 | implementation 'org.springframework.cloud:spring-cloud-starter-oauth2' 22 | testImplementation 'org.springframework.boot:spring-boot-starter-test' 23 | } 24 | 25 | dependencyManagement { 26 | imports { 27 | mavenBom "org.springframework.cloud:spring-cloud-dependencies:${springCloudVersion}" 28 | } 29 | } 30 | -------------------------------------------------------------------------------- /authserver/src/main/java/com/talk2amareswaran/projects/authserver/model/CustomUser.java: -------------------------------------------------------------------------------- 1 | package com.talk2amareswaran.projects.authserver.model; 2 | 3 | import org.springframework.security.core.userdetails.User; 4 | 5 | public class CustomUser extends User { 6 | 7 | private String id; 8 | private String name; 9 | 10 | public CustomUser(UserEntity userEntity) { 11 | super(userEntity.getEmailId(), userEntity.getPassword(), userEntity.getGrantedAuthoritiesList()); 12 | this.id = userEntity.getId(); 13 | this.name = userEntity.getName(); 14 | } 15 | 16 | public String getId() { 17 | return id; 18 | } 19 | 20 | public void setId(String id) { 21 | this.id = id; 22 | } 23 | 24 | public String getName() { 25 | return name; 26 | } 27 | 28 | public void setName(String name) { 29 | this.name = name; 30 | } 31 | } 32 | -------------------------------------------------------------------------------- /authserver/build.gradle: -------------------------------------------------------------------------------- 1 | plugins { 2 | id 'org.springframework.boot' version '2.1.7.RELEASE' 3 | id 'io.spring.dependency-management' version '1.0.8.RELEASE' 4 | id 'java' 5 | } 6 | 7 | group = 'com.talk2amareswaran.projects' 8 | version = '0.0.1-SNAPSHOT' 9 | sourceCompatibility = '1.8' 10 | 11 | repositories { 12 | mavenCentral() 13 | } 14 | 15 | ext { 16 | set('springCloudVersion', "Greenwich.SR2") 17 | } 18 | 19 | dependencies { 20 | implementation 'org.springframework.boot:spring-boot-starter-jdbc' 21 | implementation 'org.springframework.boot:spring-boot-starter-web' 22 | implementation 'org.springframework.cloud:spring-cloud-starter-oauth2' 23 | runtimeOnly 'mysql:mysql-connector-java' 24 | testImplementation 'org.springframework.boot:spring-boot-starter-test' 25 | } 26 | 27 | dependencyManagement { 28 | imports { 29 | mavenBom "org.springframework.cloud:spring-cloud-dependencies:${springCloudVersion}" 30 | } 31 | } 32 | -------------------------------------------------------------------------------- /resourceserver/src/main/java/com/talk2amareswaran/projects/resourceserver/model/AccessTokenMapper.java: -------------------------------------------------------------------------------- 1 | package com.talk2amareswaran.projects.resourceserver.model; 2 | 3 | public class AccessTokenMapper { 4 | 5 | private String access_token; 6 | private String id; 7 | private String userName; 8 | private String name; 9 | 10 | public String getAccess_token() { 11 | return access_token; 12 | } 13 | public void setAccess_token(String access_token) { 14 | this.access_token = access_token; 15 | } 16 | public String getId() { 17 | return id; 18 | } 19 | public void setId(String id) { 20 | this.id = id; 21 | } 22 | public String getUserName() { 23 | return userName; 24 | } 25 | public void setUserName(String userName) { 26 | this.userName = userName; 27 | } 28 | public String getName() { 29 | return name; 30 | } 31 | public void setName(String name) { 32 | this.name = name; 33 | } 34 | } 35 | -------------------------------------------------------------------------------- /resourceserver/src/main/java/com/talk2amareswaran/projects/resourceserver/config/SecurityConfiguration.java: -------------------------------------------------------------------------------- 1 | package com.talk2amareswaran.projects.resourceserver.config; 2 | 3 | import org.springframework.context.annotation.Configuration; 4 | import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity; 5 | import org.springframework.security.config.annotation.web.builders.HttpSecurity; 6 | import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity; 7 | import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter; 8 | import org.springframework.security.config.http.SessionCreationPolicy; 9 | 10 | @Configuration 11 | @EnableWebSecurity 12 | @EnableGlobalMethodSecurity(prePostEnabled = true) 13 | public class SecurityConfiguration extends WebSecurityConfigurerAdapter { 14 | 15 | @Override 16 | protected void configure(HttpSecurity http) throws Exception { 17 | http.authorizeRequests().anyRequest().authenticated().and().sessionManagement() 18 | .sessionCreationPolicy(SessionCreationPolicy.NEVER); 19 | } 20 | 21 | } 22 | -------------------------------------------------------------------------------- /authserver/src/main/java/com/talk2amareswaran/projects/authserver/model/UserEntity.java: -------------------------------------------------------------------------------- 1 | package com.talk2amareswaran.projects.authserver.model; 2 | 3 | import java.util.ArrayList; 4 | import java.util.Collection; 5 | 6 | import org.springframework.security.core.GrantedAuthority; 7 | 8 | public class UserEntity { 9 | 10 | private String id; 11 | private String name; 12 | private String emailId; 13 | private String password; 14 | private Collection grantedAuthoritiesList = new ArrayList<>(); 15 | 16 | public String getId() { 17 | return id; 18 | } 19 | public void setId(String id) { 20 | this.id = id; 21 | } 22 | public String getName() { 23 | return name; 24 | } 25 | public void setName(String name) { 26 | this.name = name; 27 | } 28 | public String getEmailId() { 29 | return emailId; 30 | } 31 | public void setEmailId(String emailId) { 32 | this.emailId = emailId; 33 | } 34 | public String getPassword() { 35 | return password; 36 | } 37 | public void setPassword(String password) { 38 | this.password = password; 39 | } 40 | public Collection getGrantedAuthoritiesList() { 41 | return grantedAuthoritiesList; 42 | } 43 | public void setGrantedAuthoritiesList(Collection grantedAuthoritiesList) { 44 | this.grantedAuthoritiesList = grantedAuthoritiesList; 45 | } 46 | } 47 | -------------------------------------------------------------------------------- /authserver/src/main/java/com/talk2amareswaran/projects/authserver/config/CustomTokenEnhancer.java: -------------------------------------------------------------------------------- 1 | package com.talk2amareswaran.projects.authserver.config; 2 | 3 | import java.util.LinkedHashMap; 4 | import java.util.Map; 5 | 6 | import org.springframework.security.oauth2.common.DefaultOAuth2AccessToken; 7 | import org.springframework.security.oauth2.common.OAuth2AccessToken; 8 | import org.springframework.security.oauth2.provider.OAuth2Authentication; 9 | import org.springframework.security.oauth2.provider.token.store.JwtAccessTokenConverter; 10 | 11 | import com.talk2amareswaran.projects.authserver.model.CustomUser; 12 | 13 | public class CustomTokenEnhancer extends JwtAccessTokenConverter { 14 | 15 | @Override 16 | public OAuth2AccessToken enhance(OAuth2AccessToken accessToken, OAuth2Authentication authentication) { 17 | CustomUser user = (CustomUser) authentication.getPrincipal(); 18 | Map info = new LinkedHashMap<>(accessToken.getAdditionalInformation()); 19 | if (user.getId() != null) 20 | info.put("id", user.getId()); 21 | if (user.getName() != null) 22 | info.put("name", user.getName()); 23 | if (user.getUsername() != null) 24 | info.put("userName", user.getUsername()); 25 | DefaultOAuth2AccessToken customAccessToken = new DefaultOAuth2AccessToken(accessToken); 26 | customAccessToken.setAdditionalInformation(info); 27 | return super.enhance(customAccessToken, authentication); 28 | } 29 | } 30 | -------------------------------------------------------------------------------- /resourceserver/src/main/java/com/talk2amareswaran/projects/resourceserver/config/JwtConverter.java: -------------------------------------------------------------------------------- 1 | package com.talk2amareswaran.projects.resourceserver.config; 2 | 3 | import java.util.Map; 4 | 5 | import org.springframework.boot.autoconfigure.security.oauth2.resource.JwtAccessTokenConverterConfigurer; 6 | import org.springframework.security.oauth2.provider.OAuth2Authentication; 7 | import org.springframework.security.oauth2.provider.token.DefaultAccessTokenConverter; 8 | import org.springframework.security.oauth2.provider.token.store.JwtAccessTokenConverter; 9 | import org.springframework.stereotype.Component; 10 | 11 | import com.talk2amareswaran.projects.resourceserver.model.AccessTokenMapper; 12 | 13 | @Component 14 | public class JwtConverter extends DefaultAccessTokenConverter implements JwtAccessTokenConverterConfigurer { 15 | 16 | @Override 17 | public void configure(JwtAccessTokenConverter converter) { 18 | converter.setAccessTokenConverter(this); 19 | } 20 | 21 | @Override 22 | public OAuth2Authentication extractAuthentication(Map map) { 23 | OAuth2Authentication auth = super.extractAuthentication(map); 24 | AccessTokenMapper details = new AccessTokenMapper(); 25 | 26 | if (map.get("id") != null) 27 | details.setId((String) map.get("id")); 28 | 29 | if (map.get("userName") != null) 30 | details.setUserName((String) map.get("userName")); 31 | 32 | if (map.get("name") != null) 33 | details.setName((String) map.get("name")); 34 | 35 | auth.setDetails(details); 36 | return auth; 37 | } 38 | 39 | } 40 | -------------------------------------------------------------------------------- /authserver/src/main/java/com/talk2amareswaran/projects/authserver/service/CustomUserDetailsService.java: -------------------------------------------------------------------------------- 1 | package com.talk2amareswaran.projects.authserver.service; 2 | 3 | import org.springframework.beans.factory.annotation.Autowired; 4 | import org.springframework.security.core.userdetails.UserDetails; 5 | import org.springframework.security.core.userdetails.UserDetailsService; 6 | import org.springframework.security.core.userdetails.UsernameNotFoundException; 7 | import org.springframework.stereotype.Service; 8 | 9 | import com.talk2amareswaran.projects.authserver.dao.OAuthDAOService; 10 | import com.talk2amareswaran.projects.authserver.model.CustomUser; 11 | import com.talk2amareswaran.projects.authserver.model.UserEntity; 12 | 13 | @Service 14 | public class CustomUserDetailsService implements UserDetailsService { 15 | 16 | @Autowired 17 | OAuthDAOService oauthDAOService; 18 | 19 | @Override 20 | public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException { 21 | 22 | UserEntity userEntity = null; 23 | 24 | try { 25 | userEntity = oauthDAOService.getUserDetails(username); 26 | 27 | if (userEntity != null && userEntity.getId() != null && !"".equalsIgnoreCase(userEntity.getId())) { 28 | CustomUser customUser = new CustomUser(userEntity); 29 | return customUser; 30 | } else { 31 | throw new UsernameNotFoundException("User " + username + " was not found in the database"); 32 | } 33 | } catch (Exception e) { 34 | throw new UsernameNotFoundException("User " + username + " was not found in the database"); 35 | } 36 | 37 | } 38 | 39 | } 40 | -------------------------------------------------------------------------------- /authserver/src/main/java/com/talk2amareswaran/projects/authserver/config/SecurityConfiguration.java: -------------------------------------------------------------------------------- 1 | package com.talk2amareswaran.projects.authserver.config; 2 | 3 | import org.springframework.beans.factory.annotation.Autowired; 4 | import org.springframework.context.annotation.Bean; 5 | import org.springframework.context.annotation.Configuration; 6 | import org.springframework.security.authentication.AuthenticationManager; 7 | import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder; 8 | import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity; 9 | import org.springframework.security.config.annotation.web.builders.HttpSecurity; 10 | import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity; 11 | import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter; 12 | import org.springframework.security.config.http.SessionCreationPolicy; 13 | import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder; 14 | import org.springframework.security.crypto.password.PasswordEncoder; 15 | 16 | import com.talk2amareswaran.projects.authserver.service.CustomUserDetailsService; 17 | 18 | @Configuration 19 | @EnableWebSecurity 20 | @EnableGlobalMethodSecurity(prePostEnabled = true) 21 | public class SecurityConfiguration extends WebSecurityConfigurerAdapter { 22 | 23 | @Autowired 24 | CustomUserDetailsService customUserDetailsService; 25 | 26 | @Override 27 | @Autowired 28 | protected void configure(AuthenticationManagerBuilder auth) throws Exception { 29 | auth.userDetailsService(customUserDetailsService).passwordEncoder(encoder()); 30 | } 31 | 32 | @Bean 33 | public PasswordEncoder encoder() { 34 | return new BCryptPasswordEncoder(); 35 | } 36 | 37 | @Override 38 | protected void configure(HttpSecurity http) throws Exception { 39 | http.authorizeRequests().anyRequest().authenticated().and().sessionManagement() 40 | .sessionCreationPolicy(SessionCreationPolicy.NEVER); 41 | } 42 | 43 | @Override 44 | @Bean 45 | public AuthenticationManager authenticationManagerBean() throws Exception { 46 | return super.authenticationManagerBean(); 47 | } 48 | 49 | } 50 | -------------------------------------------------------------------------------- /resourceserver/src/main/java/com/talk2amareswaran/projects/resourceserver/rest/NoteServiceController.java: -------------------------------------------------------------------------------- 1 | package com.talk2amareswaran.projects.resourceserver.rest; 2 | 3 | import org.springframework.security.access.prepost.PreAuthorize; 4 | import org.springframework.security.core.context.SecurityContextHolder; 5 | import org.springframework.web.bind.annotation.RequestMapping; 6 | import org.springframework.web.bind.annotation.RequestMethod; 7 | import org.springframework.web.bind.annotation.RestController; 8 | 9 | import com.talk2amareswaran.projects.resourceserver.model.AccessTokenMapper; 10 | 11 | import org.springframework.security.oauth2.provider.authentication.OAuth2AuthenticationDetails; 12 | 13 | @RestController 14 | public class NoteServiceController { 15 | 16 | 17 | @PreAuthorize("hasRole('CREATE_NOTE')") 18 | @RequestMapping(value="/note", method=RequestMethod.POST) 19 | public String createNote() { 20 | 21 | AccessTokenMapper accessTokenMapper = (AccessTokenMapper) 22 | ((OAuth2AuthenticationDetails) SecurityContextHolder.getContext().getAuthentication().getDetails()).getDecodedDetails(); 23 | 24 | System.out.println("ID:"+accessTokenMapper.getId()); 25 | System.out.println("Name:"+accessTokenMapper.getName()); 26 | System.out.println("Email ID:"+accessTokenMapper.getUserName()); 27 | 28 | return "Note has been created successfully"; 29 | } 30 | 31 | @PreAuthorize("hasRole('EDIT_NOTE')") 32 | @RequestMapping(value="/note", method=RequestMethod.PUT) 33 | public String updateNote() { 34 | return "Note has been updated successfully"; 35 | } 36 | 37 | @PreAuthorize("hasRole('DELETE_NOTE')") 38 | @RequestMapping(value="/note", method=RequestMethod.DELETE) 39 | public String deleteNote() { 40 | return "Note has been deleted successfully"; 41 | } 42 | 43 | @PreAuthorize("hasRole('VIEW_ALL_NOTE')") 44 | @RequestMapping(value="/note", method=RequestMethod.GET) 45 | public String viewAllNotes() { 46 | return "Notes ALL API response"; 47 | } 48 | 49 | @PreAuthorize("hasRole('VIEW_NOTE')") 50 | @RequestMapping(value="/noteById", method=RequestMethod.GET) 51 | public String viewNotesByID() { 52 | return "Notes By ID response"; 53 | } 54 | 55 | 56 | 57 | 58 | } 59 | -------------------------------------------------------------------------------- /SQL-SCRIPTS.txt: -------------------------------------------------------------------------------- 1 | CREATE DATABASE USERSERVICE; 2 | USE USERSERVICE; 3 | 4 | CREATE TABLE PERMISSION (ID INT PRIMARY KEY AUTO_INCREMENT, PERMISSION_NAME VARCHAR(20)); 5 | 6 | CREATE TABLE USER (ID INT PRIMARY KEY AUTO_INCREMENT, NAME VARCHAR(20), EMAIL_ID VARCHAR(255) UNIQUE KEY, PASSWORD VARCHAR(1000)); 7 | 8 | CREATE TABLE ROLE (ID INT PRIMARY KEY AUTO_INCREMENT, ROLE_NAME VARCHAR(20)); 9 | 10 | CREATE TABLE ASSIGN_PERMISSION_TO_ROLE (ID INT PRIMARY KEY AUTO_INCREMENT, PERMISSION_ID INT, FOREIGN KEY(PERMISSION_ID) REFERENCES 11 | PERMISSION (ID), ROLE_ID INT, FOREIGN KEY(ROLE_ID) REFERENCES ROLE(ID)); 12 | 13 | CREATE TABLE ASSIGN_USER_TO_ROLE (ID INT PRIMARY KEY AUTO_INCREMENT, USER_ID INT, FOREIGN KEY(USER_ID) REFERENCES USER(ID), 14 | ROLE_ID INT, FOREIGN KEY(ROLE_ID) REFERENCES ROLE(ID)); 15 | 16 | 17 | INSERT INTO PERMISSION (ID, PERMISSION_NAME) VALUES (1, 'CREATE_NOTE'), (2, 'EDIT_NOTE'), (3, 'DELETE_NOTE'), (4, 'VIEW_ALL_NOTE'), (5, 'VIEW_NOTE'); 18 | 19 | INSERT INTO ROLE (ID, ROLE_NAME) VALUES (1, 'ADMINISTRATOR'), (2, 'AUDITOR'); 20 | 21 | INSERT INTO USER (ID, NAME, EMAIL_ID, PASSWORD) VALUES (1, 'John', 'john@gmail.com','$2a$10$jbIi/RIYNm5xAW9M7IaE5.WPw6BZgD8wcpkZUg0jm8RHPtdfDcMgm'); 22 | INSERT INTO USER (ID, NAME, EMAIL_ID, PASSWORD) VALUES (2, 'Mike', 'mike@gmail.com','$2a$10$jbIi/RIYNm5xAW9M7IaE5.WPw6BZgD8wcpkZUg0jm8RHPtdfDcMgm'); 23 | 24 | INSERT INTO ASSIGN_PERMISSION_TO_ROLE (PERMISSION_ID, ROLE_ID) VALUES (1, 1); 25 | INSERT INTO ASSIGN_PERMISSION_TO_ROLE (PERMISSION_ID, ROLE_ID) VALUES (2, 1); 26 | INSERT INTO ASSIGN_PERMISSION_TO_ROLE (PERMISSION_ID, ROLE_ID) VALUES (3, 1); 27 | INSERT INTO ASSIGN_PERMISSION_TO_ROLE (PERMISSION_ID, ROLE_ID) VALUES (4, 1); 28 | INSERT INTO ASSIGN_PERMISSION_TO_ROLE (PERMISSION_ID, ROLE_ID) VALUES (5, 1); 29 | 30 | INSERT INTO ASSIGN_PERMISSION_TO_ROLE (PERMISSION_ID, ROLE_ID) VALUES (4, 2); 31 | INSERT INTO ASSIGN_PERMISSION_TO_ROLE (PERMISSION_ID, ROLE_ID) VALUES (5, 2); 32 | 33 | INSERT INTO ASSIGN_USER_TO_ROLE (USER_ID, ROLE_ID) VALUES (1, 1); 34 | INSERT INTO ASSIGN_USER_TO_ROLE (USER_ID, ROLE_ID) VALUES (2, 2); 35 | 36 | SELECT * FROM USER WHERE EMAIL_ID ='john@gmail.com'; 37 | 38 | SELECT DISTINCT P.PERMISSION_NAME FROM PERMISSION P 39 | INNER JOIN ASSIGN_PERMISSION_TO_ROLE P_R ON P.ID=P_R.PERMISSION_ID 40 | INNER JOIN ROLE R ON R.ID=P_R.ROLE_ID 41 | INNER JOIN ASSIGN_USER_TO_ROLE U_R ON U_R.ROLE_ID=R.ID 42 | INNER JOIN USER U ON U.ID=U_R.USER_ID 43 | WHERE U.EMAIL_ID='john@gmail.com'; 44 | 45 | -------------------------------------------------------------------------------- /authserver/src/main/resources/application.yml: -------------------------------------------------------------------------------- 1 | spring: 2 | application: 3 | name: authserver 4 | 5 | datasource: 6 | driverClassName: com.mysql.cj.jdbc.Driver 7 | url: "jdbc:mysql://35.226.143.212/USERSERVICE?autoreconnect=true" 8 | password: "root" 9 | username: "root" 10 | 11 | config: 12 | oauth2: 13 | clientid: talk2amareswaran 14 | clientSecret: talk2amareswaran@123 15 | privateKey: -----BEGIN RSA PRIVATE KEY-----MIIEpAIBAAKCAQEAsY9wY6rwdql0GCPFxu7eEypLC8TkDQHgaFlmP5QBf7Il4/8/ogTrT1cLF/fMrfhoJrPeZWjzP6NmaxttCUcki8JSbmaxdYNnIPHsPFvqr1DlpvikdKiG5lkKS27E9uUQ1XmeXh9Vhn9QwLQyXl5bbbjlDewiCzB/MuKlbuuxFsb7ZPpBD+rE69efUfTu8dZPa5QzTugqxqAe9q2soLPxYyh91BGjVGWMN9wwWnM+WaQ9IehuQko7drlvJRVhPow9zvzTanaJckn02+Ubj5+LFQ8yYNe/PQQSS+noaQtmCqRfVhL161F6yivj16EuYJhkUn3TQQTbDhSU3CcdMcX5lQIDAQABAoIBABXGVm0SmHyk2UTgli+IOZm2FQ/zbFggA8ooNH7Vgr2LNlRYiBAxdD39mbGtxN8M2JDue/aJwVLrkfLOoTeDDvtIsF0zoM2deLc0k9jvGL+5NwCb+2cHB8wV3UpU4ji47LCRQpeeVhmxYVDQiGDER4gUJZroe2BN6TtvSgRpSQVW2z6Fd26e3ywHchDZBm/Uj5piXbbUaNVngy/SehiGD9ETCkeFkHyjCETOS1ot4hpN6j7ovyZQdDJVc4ERmmd9V28d4m1Av9yoLSiNYnECpkhH4KuteHQ/keO3bq8mOgeKNtReTadHPVAjkq4sF4ZlsTUru7JNGmFv1yLsUWh4Ex0CgYEA4J972qFv+i//wjg3Q2YdvmCx7zT3SA4Fs+1vlcbW35iEQ96SQS5ToPl47+yev2j+rXswsyjKdW1t9PbgfmKSmxtbnbNyzX6u2RlbxwazMGIwGg8Z7ITWr9Y65PtKea3fsNBKiwR3jT97KB5wl/wJK5GvFYFt1M3cSKv5qQbsgu8CgYEAylz+i4Fbzk3uii290f8fkHiNudKWRoWAHu3sdBV0dFbkt4Ec5QZkUyb9aeLZbI4YDdNHo6+aAQCcOp4qU+7vgkLUSMIoTCK/I8N5iA9Ws3lvnLaVJJ8j64M+HV7A+zaRtKbPVDRBt4oWuzjMhBgCs0NPVa9BgpYmwqfltgN++7sCgYBWBl49pfQnofhWXoczpckgXxHmJafKjaw7c2R3vRYPve5xu6zRj7dxf/mEEV/euIxIzlQhWS7oeAdTeLUTUhcJlhmpNM9zyd+Wv3J5r6QylHgNktj/zwQVhXs6tM6Z+TAhHDRgN0695qD5BWdjnZ+5curV1qLEjC6gGlTcGg28OwKBgQDGr4uUuUvEQSwGK2cGOfFpzZOJcUPutcDXnU7dovsWBwLFUVVnYGE8aznAruQ++zyOxnS+N/mDJnA99XElu6EZSjhXv5oFNtBoctJuTnEYAhEd0v6YWE/SOqfP+mqLvEZPEsDZsf0cEc7Dv769qz1reJj6TfqKFpaz5Flb3g7dZQKBgQCfD4iTDLsCtdmZ7qENAQ26UYES/C+/cYbuPBnme3B7C14YeDXE1bVFk0GPxIwCisyiM0aayuM4o7kQFsF0ChV7XP5leTdGusZWACDnyP1vibAAnPde7fAqHiX4PZOYaKVBS0cCjZQfZHV/ilcD0EvYt6e61n+qozJfYDOVyimqIQ==-----END RSA PRIVATE KEY----- 16 | publicKey: -----BEGIN PUBLIC KEY-----MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAsY9wY6rwdql0GCPFxu7eEypLC8TkDQHgaFlmP5QBf7Il4/8/ogTrT1cLF/fMrfhoJrPeZWjzP6NmaxttCUcki8JSbmaxdYNnIPHsPFvqr1DlpvikdKiG5lkKS27E9uUQ1XmeXh9Vhn9QwLQyXl5bbbjlDewiCzB/MuKlbuuxFsb7ZPpBD+rE69efUfTu8dZPa5QzTugqxqAe9q2soLPxYyh91BGjVGWMN9wwWnM+WaQ9IehuQko7drlvJRVhPow9zvzTanaJckn02+Ubj5+LFQ8yYNe/PQQSS+noaQtmCqRfVhL161F6yivj16EuYJhkUn3TQQTbDhSU3CcdMcX5lQIDAQAB-----END PUBLIC KEY----- 17 | -------------------------------------------------------------------------------- /authserver/src/main/java/com/talk2amareswaran/projects/authserver/dao/OAuthDAOServiceImpl.java: -------------------------------------------------------------------------------- 1 | package com.talk2amareswaran.projects.authserver.dao; 2 | 3 | import java.sql.ResultSet; 4 | import java.util.ArrayList; 5 | import java.util.Collection; 6 | import java.util.List; 7 | 8 | import org.springframework.beans.factory.annotation.Autowired; 9 | import org.springframework.jdbc.core.JdbcTemplate; 10 | import org.springframework.security.core.GrantedAuthority; 11 | import org.springframework.security.core.authority.SimpleGrantedAuthority; 12 | import org.springframework.stereotype.Repository; 13 | 14 | import com.talk2amareswaran.projects.authserver.model.UserEntity; 15 | 16 | @Repository 17 | public class OAuthDAOServiceImpl implements OAuthDAOService { 18 | 19 | 20 | @Autowired 21 | JdbcTemplate jdbcTemplate; 22 | 23 | @Override 24 | public UserEntity getUserDetails(String emailId) { 25 | 26 | Collection grantedAuthoritiesList = new ArrayList<>(); 27 | 28 | List list = jdbcTemplate.query("SELECT * FROM USER WHERE EMAIL_ID=?", new String[] { emailId }, 29 | (ResultSet rs, int rowNum) -> { 30 | UserEntity user = new UserEntity(); 31 | user.setEmailId(emailId); 32 | user.setId(rs.getString("ID")); 33 | user.setName(rs.getString("NAME")); 34 | user.setPassword(rs.getString("PASSWORD")); 35 | return user; 36 | }); 37 | 38 | if(!list.isEmpty()) { 39 | 40 | UserEntity userEntity = list.get(0); 41 | 42 | List permissionList = jdbcTemplate.query("SELECT DISTINCT P.PERMISSION_NAME FROM PERMISSION P \r\n" + 43 | "INNER JOIN ASSIGN_PERMISSION_TO_ROLE P_R ON P.ID=P_R.PERMISSION_ID\r\n" + 44 | "INNER JOIN ROLE R ON R.ID=P_R.ROLE_ID \r\n" + 45 | "INNER JOIN ASSIGN_USER_TO_ROLE U_R ON U_R.ROLE_ID=R.ID\r\n" + 46 | "INNER JOIN USER U ON U.ID=U_R.USER_ID\r\n" + 47 | "WHERE U.EMAIL_ID=?", new String[] { userEntity.getEmailId() }, 48 | (ResultSet rs, int rowNum) -> { 49 | return "ROLE_" + rs.getString("PERMISSION_NAME"); 50 | }); 51 | 52 | if (permissionList != null && !permissionList.isEmpty()) { 53 | for (String permission : permissionList) { 54 | GrantedAuthority grantedAuthority = new SimpleGrantedAuthority(permission); 55 | grantedAuthoritiesList.add(grantedAuthority); 56 | } 57 | userEntity.setGrantedAuthoritiesList(grantedAuthoritiesList); 58 | } 59 | return userEntity; 60 | } 61 | 62 | return null; 63 | 64 | 65 | 66 | } 67 | 68 | } 69 | -------------------------------------------------------------------------------- /authserver/src/main/java/com/talk2amareswaran/projects/authserver/config/OAuth2Config.java: -------------------------------------------------------------------------------- 1 | package com.talk2amareswaran.projects.authserver.config; 2 | 3 | import org.springframework.beans.factory.annotation.Autowired; 4 | import org.springframework.beans.factory.annotation.Qualifier; 5 | import org.springframework.beans.factory.annotation.Value; 6 | import org.springframework.context.annotation.Bean; 7 | import org.springframework.context.annotation.Configuration; 8 | import org.springframework.security.authentication.AuthenticationManager; 9 | import org.springframework.security.crypto.password.PasswordEncoder; 10 | import org.springframework.security.oauth2.config.annotation.configurers.ClientDetailsServiceConfigurer; 11 | import org.springframework.security.oauth2.config.annotation.web.configuration.AuthorizationServerConfigurerAdapter; 12 | import org.springframework.security.oauth2.config.annotation.web.configurers.AuthorizationServerEndpointsConfigurer; 13 | import org.springframework.security.oauth2.config.annotation.web.configurers.AuthorizationServerSecurityConfigurer; 14 | import org.springframework.security.oauth2.provider.token.store.JwtAccessTokenConverter; 15 | import org.springframework.security.oauth2.provider.token.store.JwtTokenStore; 16 | 17 | @Configuration 18 | public class OAuth2Config extends AuthorizationServerConfigurerAdapter { 19 | 20 | @Value("${config.oauth2.clientid}") 21 | private String clientid; 22 | 23 | @Value("${config.oauth2.clientSecret}") 24 | private String clientSecret; 25 | 26 | @Value("${config.oauth2.privateKey}") 27 | private String privateKey; 28 | 29 | @Value("${config.oauth2.publicKey}") 30 | private String publicKey; 31 | 32 | @Autowired 33 | PasswordEncoder passwordEncoder; 34 | 35 | @Autowired 36 | @Qualifier("authenticationManagerBean") 37 | private AuthenticationManager authenticationManager; 38 | 39 | @Override 40 | public void configure(AuthorizationServerSecurityConfigurer security) throws Exception { 41 | security.tokenKeyAccess("permitAll()").checkTokenAccess("isAuthenticated()"); 42 | } 43 | 44 | @Override 45 | public void configure(ClientDetailsServiceConfigurer clients) throws Exception { 46 | clients.inMemory().withClient(clientid).secret(passwordEncoder.encode(clientSecret)).scopes("read", "write") 47 | .authorizedGrantTypes("password", "refresh_token").accessTokenValiditySeconds(3600) 48 | .refreshTokenValiditySeconds(18000); 49 | } 50 | 51 | @Override 52 | public void configure(AuthorizationServerEndpointsConfigurer endpoints) throws Exception { 53 | endpoints.authenticationManager(authenticationManager).tokenStore(tokenStore()) 54 | .accessTokenConverter(tokenEnhancer()); 55 | } 56 | 57 | @Bean 58 | public JwtTokenStore tokenStore() { 59 | return new JwtTokenStore(tokenEnhancer()); 60 | } 61 | 62 | @Bean 63 | public JwtAccessTokenConverter tokenEnhancer() { 64 | JwtAccessTokenConverter converter = new CustomTokenEnhancer(); 65 | converter.setSigningKey(privateKey); 66 | converter.setVerifierKey(publicKey); 67 | return converter; 68 | } 69 | 70 | } 71 | --------------------------------------------------------------------------------