├── README.md ├── pom.xml ├── springboot2-oauth2.sql └── src ├── main ├── java │ └── com │ │ └── talk2amareswaran │ │ └── projects │ │ └── springboot2authserver │ │ ├── Springboot2AuthserverApplication.java │ │ ├── config │ │ ├── CustomOauth2RequestFactory.java │ │ ├── CustomTokenEnhancer.java │ │ ├── OAuth2Configuration.java │ │ └── WebSecurityConfiguration.java │ │ ├── entity │ │ ├── BaseIdEntity.java │ │ ├── Permission.java │ │ ├── Role.java │ │ └── User.java │ │ ├── repository │ │ └── UserRepository.java │ │ └── service │ │ └── CustomUserDetailsService.java └── resources │ ├── application.yml │ └── jwt.jks └── test └── java └── com └── talk2amareswaran └── projects └── springboot2authserver └── Springboot2AuthserverApplicationTests.java /README.md: -------------------------------------------------------------------------------- 1 | # spring-boot2-oauth2-auth-server-jwt-mysql 2 | 3 | Hello Everyone, 4 | 5 | Here is the video of Spring Boot 2.0 Authorization Server | OAuth2 | JWT and MySQL 6 | 7 | https://youtu.be/wxebTn_a930 8 | 9 | Please subscribe my YouTube channel - https://www.youtube.com/c/Talk2Amareswaran 10 | 11 | Please like my Facebook page - https://www.facebook.com/talk2amareswaran/ 12 | 13 | Please join Facebook group - https://www.facebook.com/groups/271796230307847/ 14 | -------------------------------------------------------------------------------- /pom.xml: -------------------------------------------------------------------------------- 1 | 2 | 4 | 4.0.0 5 | 6 | com.talk2amareswaran.projects 7 | springboot2-authserver 8 | 0.0.1-SNAPSHOT 9 | jar 10 | 11 | springboot2-authserver 12 | Demo project for Spring Boot 13 | 14 | 15 | org.springframework.boot 16 | spring-boot-starter-parent 17 | 2.0.1.RELEASE 18 | 19 | 20 | 21 | 22 | UTF-8 23 | UTF-8 24 | 1.8 25 | Finchley.RC1 26 | 27 | 28 | 29 | 30 | org.springframework.boot 31 | spring-boot-starter-data-jpa 32 | 33 | 34 | org.springframework.boot 35 | spring-boot-starter-web 36 | 37 | 38 | org.springframework.cloud 39 | spring-cloud-starter-oauth2 40 | 41 | 42 | org.springframework.cloud 43 | spring-cloud-starter-security 44 | 45 | 46 | 47 | mysql 48 | mysql-connector-java 49 | runtime 50 | 51 | 52 | org.springframework.boot 53 | spring-boot-starter-test 54 | test 55 | 56 | 57 | 58 | 59 | 60 | 61 | org.springframework.cloud 62 | spring-cloud-dependencies 63 | ${spring-cloud.version} 64 | pom 65 | import 66 | 67 | 68 | 69 | 70 | 71 | 72 | 73 | org.springframework.boot 74 | spring-boot-maven-plugin 75 | 76 | 77 | 78 | 79 | 80 | 81 | spring-milestones 82 | Spring Milestones 83 | https://repo.spring.io/milestone 84 | 85 | false 86 | 87 | 88 | 89 | 90 | 91 | 92 | -------------------------------------------------------------------------------- /springboot2-oauth2.sql: -------------------------------------------------------------------------------- 1 | CREATE TABLE OAUTH_CLIENT_DETAILS ( 2 | CLIENT_ID VARCHAR(255) NOT NULL PRIMARY KEY, 3 | CLIENT_SECRET VARCHAR(255) NOT NULL, 4 | RESOURCE_IDS VARCHAR(255) DEFAULT NULL, 5 | SCOPE VARCHAR(255) DEFAULT NULL, 6 | AUTHORIZED_GRANT_TYPES VARCHAR(255) DEFAULT NULL, 7 | WEB_SERVER_REDIRECT_URI VARCHAR(255) DEFAULT NULL, 8 | AUTHORITIES VARCHAR(255) DEFAULT NULL, 9 | ACCESS_TOKEN_VALIDITY INT(11) DEFAULT NULL, 10 | REFRESH_TOKEN_VALIDITY INT(11) DEFAULT NULL, 11 | ADDITIONAL_INFORMATION VARCHAR(4096) DEFAULT NULL, 12 | AUTOAPPROVE VARCHAR(255) DEFAULT NULL); 13 | 14 | INSERT INTO OAUTH_CLIENT_DETAILS ( 15 | CLIENT_ID,CLIENT_SECRET, 16 | RESOURCE_IDS, 17 | SCOPE, 18 | AUTHORIZED_GRANT_TYPES, 19 | WEB_SERVER_REDIRECT_URI,AUTHORITIES, 20 | ACCESS_TOKEN_VALIDITY,REFRESH_TOKEN_VALIDITY, 21 | ADDITIONAL_INFORMATION,AUTOAPPROVE) 22 | VALUES( 23 | 'USER_CLIENT_APP','{bcrypt}$2a$10$EOs8VROb14e7ZnydvXECA.4LoIhPOoFHKvVF/iBZ/ker17Eocz4Vi', 24 | 'USER_CLIENT_RESOURCE,USER_ADMIN_RESOURCE', 25 | 'role_admin,role_user', 26 | 'authorization_code,password,refresh_token,implicit', 27 | NULL,NULL, 28 | 900,3600, 29 | '{}',NULL); 30 | 31 | 32 | 33 | CREATE TABLE PERMISSION ( 34 | ID INT PRIMARY KEY AUTO_INCREMENT, 35 | NAME VARCHAR(60) UNIQUE KEY); 36 | 37 | INSERT INTO PERMISSION (NAME) VALUES 38 | ('can_create_user'), 39 | ('can_update_user'), 40 | ('can_read_user'), 41 | ('can_delete_user'); 42 | 43 | 44 | 45 | CREATE TABLE ROLE 46 | (ID INT PRIMARY KEY AUTO_INCREMENT, 47 | NAME VARCHAR(60) UNIQUE KEY); 48 | 49 | 50 | INSERT INTO ROLE (NAME) VALUES 51 | ('role_admin'),('role_user'); 52 | 53 | 54 | 55 | 56 | CREATE TABLE PERMISSION_ROLE( 57 | PERMISSION_ID INT, 58 | FOREIGN KEY(PERMISSION_ID) REFERENCES PERMISSION(ID), 59 | ROLE_ID INT, 60 | FOREIGN KEY(ROLE_ID) REFERENCES ROLE(ID)); 61 | 62 | INSERT INTO PERMISSION_ROLE (PERMISSION_ID, ROLE_ID) VALUES 63 | (1,1), /* can_create_user assigned to role_admin */ 64 | (2,1), /* can_update_user assigned to role_admin */ 65 | (3,1), /* can_read_user assigned to role_admin */ 66 | (4,1), /* can_delete_user assigned to role_admin */ 67 | 68 | (3,2); /* can_read_user assigned to role_user */ 69 | 70 | 71 | 72 | 73 | 74 | CREATE TABLE USER ( 75 | ID INT PRIMARY KEY AUTO_INCREMENT, 76 | USERNAME VARCHAR(24) UNIQUE KEY NOT NULL, 77 | PASSWORD VARCHAR(255) NOT NULL, 78 | EMAIL VARCHAR(255) NOT NULL, 79 | ENABLED BIT(1) NOT NULL, 80 | ACCOUNT_EXPIRED BIT(1) NOT NULL, 81 | CREDENTIALS_EXPIRED BIT(1) NOT NULL, 82 | ACCOUNT_LOCKED BIT(1) NOT NULL); 83 | 84 | 85 | 86 | 87 | 88 | INSERT INTO USER ( 89 | USERNAME,PASSWORD, 90 | EMAIL,ENABLED,ACCOUNT_EXPIRED,CREDENTIALS_EXPIRED,ACCOUNT_LOCKED) VALUES ( 91 | 'admin','{bcrypt}$2a$10$EOs8VROb14e7ZnydvXECA.4LoIhPOoFHKvVF/iBZ/ker17Eocz4Vi', 92 | 'william@gmail.com',1,0,0,0), 93 | ('user','{bcrypt}$2a$10$EOs8VROb14e7ZnydvXECA.4LoIhPOoFHKvVF/iBZ/ker17Eocz4Vi', 94 | 'john@gmail.com',1,0,0,0); 95 | 96 | 97 | 98 | CREATE TABLE ROLE_USER (ROLE_ID INT,FOREIGN KEY(ROLE_ID) REFERENCES ROLE(ID), 99 | USER_ID INT, FOREIGN KEY(USER_ID) REFERENCES USER(ID)); 100 | 101 | 102 | INSERT INTO ROLE_USER (ROLE_ID, USER_ID) 103 | VALUES 104 | (1, 1) /* role_admin assigned to admin user */, 105 | (2, 2) /* role_user assigned to user user */ ; 106 | 107 | -------------------------------------------------------------------------------- /src/main/java/com/talk2amareswaran/projects/springboot2authserver/Springboot2AuthserverApplication.java: -------------------------------------------------------------------------------- 1 | package com.talk2amareswaran.projects.springboot2authserver; 2 | 3 | import org.springframework.boot.SpringApplication; 4 | import org.springframework.boot.autoconfigure.SpringBootApplication; 5 | 6 | @SpringBootApplication 7 | public class Springboot2AuthserverApplication { 8 | 9 | public static void main(String[] args) { 10 | SpringApplication.run(Springboot2AuthserverApplication.class, args); 11 | } 12 | } 13 | -------------------------------------------------------------------------------- /src/main/java/com/talk2amareswaran/projects/springboot2authserver/config/CustomOauth2RequestFactory.java: -------------------------------------------------------------------------------- 1 | package com.talk2amareswaran.projects.springboot2authserver.config; 2 | 3 | import java.util.Map; 4 | 5 | import org.springframework.beans.factory.annotation.Autowired; 6 | import org.springframework.security.authentication.UsernamePasswordAuthenticationToken; 7 | import org.springframework.security.core.context.SecurityContextHolder; 8 | import org.springframework.security.core.userdetails.UserDetailsService; 9 | import org.springframework.security.oauth2.provider.ClientDetails; 10 | import org.springframework.security.oauth2.provider.ClientDetailsService; 11 | import org.springframework.security.oauth2.provider.OAuth2Authentication; 12 | import org.springframework.security.oauth2.provider.TokenRequest; 13 | import org.springframework.security.oauth2.provider.request.DefaultOAuth2RequestFactory; 14 | import org.springframework.security.oauth2.provider.token.TokenStore; 15 | 16 | public class CustomOauth2RequestFactory extends DefaultOAuth2RequestFactory { 17 | 18 | @Autowired 19 | private TokenStore tokenStore; 20 | 21 | @Autowired 22 | private UserDetailsService userDetailsService; 23 | 24 | public CustomOauth2RequestFactory(ClientDetailsService clientDetailsService) { 25 | super(clientDetailsService); 26 | } 27 | 28 | 29 | @Override 30 | public TokenRequest createTokenRequest(Map requestParameters, 31 | ClientDetails authenticatedClient) { 32 | if (requestParameters.get("grant_type").equals("refresh_token")) { 33 | OAuth2Authentication authentication = tokenStore.readAuthenticationForRefreshToken( 34 | tokenStore.readRefreshToken(requestParameters.get("refresh_token"))); 35 | SecurityContextHolder.getContext() 36 | .setAuthentication(new UsernamePasswordAuthenticationToken(authentication.getName(), null, 37 | userDetailsService.loadUserByUsername(authentication.getName()).getAuthorities())); 38 | } 39 | return super.createTokenRequest(requestParameters, authenticatedClient); 40 | } 41 | } 42 | -------------------------------------------------------------------------------- /src/main/java/com/talk2amareswaran/projects/springboot2authserver/config/CustomTokenEnhancer.java: -------------------------------------------------------------------------------- 1 | package com.talk2amareswaran.projects.springboot2authserver.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.springboot2authserver.entity.User; 12 | 13 | public class CustomTokenEnhancer extends JwtAccessTokenConverter { 14 | @Override 15 | public OAuth2AccessToken enhance(OAuth2AccessToken accessToken, OAuth2Authentication authentication) { 16 | User user = (User) authentication.getPrincipal(); 17 | 18 | Map info = new LinkedHashMap(accessToken.getAdditionalInformation()); 19 | 20 | info.put("email", user.getEmail()); 21 | 22 | DefaultOAuth2AccessToken customAccessToken = new DefaultOAuth2AccessToken(accessToken); 23 | customAccessToken.setAdditionalInformation(info); 24 | 25 | return super.enhance(customAccessToken, authentication); 26 | } 27 | } -------------------------------------------------------------------------------- /src/main/java/com/talk2amareswaran/projects/springboot2authserver/config/OAuth2Configuration.java: -------------------------------------------------------------------------------- 1 | package com.talk2amareswaran.projects.springboot2authserver.config; 2 | 3 | import javax.sql.DataSource; 4 | 5 | import org.springframework.beans.factory.annotation.Autowired; 6 | import org.springframework.beans.factory.annotation.Qualifier; 7 | import org.springframework.beans.factory.annotation.Value; 8 | import org.springframework.context.annotation.Bean; 9 | import org.springframework.context.annotation.Configuration; 10 | import org.springframework.core.io.ClassPathResource; 11 | import org.springframework.security.authentication.AuthenticationManager; 12 | import org.springframework.security.core.userdetails.UserDetailsService; 13 | import org.springframework.security.crypto.password.PasswordEncoder; 14 | import org.springframework.security.oauth2.config.annotation.configurers.ClientDetailsServiceConfigurer; 15 | import org.springframework.security.oauth2.config.annotation.web.configuration.AuthorizationServerConfigurerAdapter; 16 | import org.springframework.security.oauth2.config.annotation.web.configuration.EnableAuthorizationServer; 17 | import org.springframework.security.oauth2.config.annotation.web.configurers.AuthorizationServerEndpointsConfigurer; 18 | import org.springframework.security.oauth2.config.annotation.web.configurers.AuthorizationServerSecurityConfigurer; 19 | import org.springframework.security.oauth2.provider.ClientDetailsService; 20 | import org.springframework.security.oauth2.provider.OAuth2RequestFactory; 21 | import org.springframework.security.oauth2.provider.endpoint.TokenEndpointAuthenticationFilter; 22 | import org.springframework.security.oauth2.provider.token.TokenStore; 23 | import org.springframework.security.oauth2.provider.token.store.JwtAccessTokenConverter; 24 | import org.springframework.security.oauth2.provider.token.store.JwtTokenStore; 25 | import org.springframework.security.oauth2.provider.token.store.KeyStoreKeyFactory; 26 | 27 | @Configuration 28 | @EnableAuthorizationServer 29 | public class OAuth2Configuration extends AuthorizationServerConfigurerAdapter { 30 | 31 | @Value("${check-user-scopes}") 32 | private Boolean checkUserScopes; 33 | 34 | @Autowired 35 | private DataSource dataSource; 36 | 37 | @Autowired 38 | private PasswordEncoder passwordEncoder; 39 | 40 | @Autowired 41 | private UserDetailsService userDetailsService; 42 | 43 | @Autowired 44 | private ClientDetailsService clientDetailsService; 45 | 46 | @Autowired 47 | @Qualifier("authenticationManagerBean") 48 | private AuthenticationManager authenticationManager; 49 | 50 | @Bean 51 | public OAuth2RequestFactory requestFactory() { 52 | CustomOauth2RequestFactory requestFactory = new CustomOauth2RequestFactory(clientDetailsService); 53 | requestFactory.setCheckUserScopes(true); 54 | return requestFactory; 55 | } 56 | 57 | @Bean 58 | public TokenStore tokenStore() { 59 | return new JwtTokenStore(jwtAccessTokenConverter()); 60 | } 61 | 62 | @Bean 63 | public JwtAccessTokenConverter jwtAccessTokenConverter() { 64 | JwtAccessTokenConverter converter = new CustomTokenEnhancer(); 65 | converter.setKeyPair(new KeyStoreKeyFactory(new ClassPathResource("jwt.jks"), "password".toCharArray()).getKeyPair("jwt")); 66 | return converter; 67 | } 68 | 69 | @Override 70 | public void configure(ClientDetailsServiceConfigurer clients) throws Exception { 71 | clients.jdbc(dataSource).passwordEncoder(passwordEncoder); 72 | } 73 | 74 | 75 | @Bean 76 | public TokenEndpointAuthenticationFilter tokenEndpointAuthenticationFilter() { 77 | return new TokenEndpointAuthenticationFilter(authenticationManager, requestFactory()); 78 | } 79 | 80 | 81 | @Override 82 | public void configure(AuthorizationServerSecurityConfigurer oauthServer) throws Exception { 83 | oauthServer.tokenKeyAccess("permitAll()").checkTokenAccess("isAuthenticated()"); 84 | } 85 | 86 | @Override 87 | public void configure(AuthorizationServerEndpointsConfigurer endpoints) throws Exception { 88 | endpoints.tokenStore(tokenStore()).tokenEnhancer(jwtAccessTokenConverter()) 89 | .authenticationManager(authenticationManager).userDetailsService(userDetailsService); 90 | if (checkUserScopes) 91 | endpoints.requestFactory(requestFactory()); 92 | } 93 | 94 | 95 | 96 | 97 | 98 | 99 | 100 | 101 | 102 | 103 | 104 | 105 | 106 | 107 | 108 | 109 | 110 | 111 | 112 | 113 | 114 | 115 | 116 | 117 | 118 | 119 | 120 | 121 | 122 | 123 | } -------------------------------------------------------------------------------- /src/main/java/com/talk2amareswaran/projects/springboot2authserver/config/WebSecurityConfiguration.java: -------------------------------------------------------------------------------- 1 | package com.talk2amareswaran.projects.springboot2authserver.config; 2 | 3 | import javax.servlet.http.HttpServletResponse; 4 | 5 | import org.springframework.beans.factory.annotation.Autowired; 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.config.annotation.authentication.builders.AuthenticationManagerBuilder; 10 | import org.springframework.security.config.annotation.web.builders.HttpSecurity; 11 | import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter; 12 | import org.springframework.security.core.userdetails.UserDetailsService; 13 | import org.springframework.security.crypto.factory.PasswordEncoderFactories; 14 | import org.springframework.security.crypto.password.PasswordEncoder; 15 | 16 | @Configuration 17 | public class WebSecurityConfiguration extends WebSecurityConfigurerAdapter { 18 | 19 | @Autowired 20 | private UserDetailsService userDetailsService; 21 | 22 | @Bean 23 | public PasswordEncoder passwordEncoder() { 24 | return PasswordEncoderFactories.createDelegatingPasswordEncoder(); 25 | } 26 | 27 | @Bean 28 | @Override 29 | public AuthenticationManager authenticationManagerBean() throws Exception { 30 | return super.authenticationManagerBean(); 31 | } 32 | 33 | @Override 34 | public void configure(HttpSecurity http) throws Exception { 35 | http.csrf().disable().exceptionHandling() 36 | .authenticationEntryPoint( 37 | (request, response, authException) -> response.sendError(HttpServletResponse.SC_UNAUTHORIZED)) 38 | .and().authorizeRequests().antMatchers("/**").authenticated().and().httpBasic(); 39 | } 40 | 41 | @Override 42 | public void configure(AuthenticationManagerBuilder auth) throws Exception { 43 | auth.userDetailsService(userDetailsService).passwordEncoder(passwordEncoder()); 44 | } 45 | 46 | } 47 | -------------------------------------------------------------------------------- /src/main/java/com/talk2amareswaran/projects/springboot2authserver/entity/BaseIdEntity.java: -------------------------------------------------------------------------------- 1 | package com.talk2amareswaran.projects.springboot2authserver.entity; 2 | 3 | import javax.persistence.GeneratedValue; 4 | import javax.persistence.GenerationType; 5 | import javax.persistence.Id; 6 | import javax.persistence.MappedSuperclass; 7 | 8 | @MappedSuperclass 9 | public class BaseIdEntity { 10 | 11 | @Id 12 | @GeneratedValue(strategy = GenerationType.IDENTITY) 13 | protected int id; 14 | 15 | } -------------------------------------------------------------------------------- /src/main/java/com/talk2amareswaran/projects/springboot2authserver/entity/Permission.java: -------------------------------------------------------------------------------- 1 | package com.talk2amareswaran.projects.springboot2authserver.entity; 2 | 3 | import javax.persistence.Entity; 4 | 5 | @Entity 6 | public class Permission extends BaseIdEntity { 7 | 8 | private String name; 9 | 10 | public String getName() { 11 | return name; 12 | } 13 | 14 | public void setName(String name) { 15 | this.name = name; 16 | } 17 | } 18 | -------------------------------------------------------------------------------- /src/main/java/com/talk2amareswaran/projects/springboot2authserver/entity/Role.java: -------------------------------------------------------------------------------- 1 | package com.talk2amareswaran.projects.springboot2authserver.entity; 2 | 3 | import java.util.List; 4 | 5 | import javax.persistence.Entity; 6 | import javax.persistence.FetchType; 7 | import javax.persistence.JoinTable; 8 | import javax.persistence.ManyToMany; 9 | import javax.persistence.JoinColumn; 10 | 11 | @Entity 12 | public class Role extends BaseIdEntity { 13 | 14 | private String name; 15 | 16 | @ManyToMany(fetch = FetchType.EAGER) 17 | @JoinTable(name = "permission_role", joinColumns = { 18 | @JoinColumn(name = "role_id", referencedColumnName = "id") }, inverseJoinColumns = { 19 | @JoinColumn(name = "permission_id", referencedColumnName = "id") }) 20 | private List permissions; 21 | 22 | public String getName() { 23 | return name; 24 | } 25 | 26 | public void setName(String name) { 27 | this.name = name; 28 | } 29 | 30 | public List getPermissions() { 31 | return permissions; 32 | } 33 | 34 | public void setPermissions(List permissions) { 35 | this.permissions = permissions; 36 | } 37 | 38 | } -------------------------------------------------------------------------------- /src/main/java/com/talk2amareswaran/projects/springboot2authserver/entity/User.java: -------------------------------------------------------------------------------- 1 | package com.talk2amareswaran.projects.springboot2authserver.entity; 2 | 3 | import java.util.Collection; 4 | import java.util.HashSet; 5 | import java.util.List; 6 | import java.util.Set; 7 | 8 | import javax.persistence.Column; 9 | import javax.persistence.Entity; 10 | import javax.persistence.FetchType; 11 | import javax.persistence.JoinTable; 12 | import javax.persistence.JoinColumn; 13 | import javax.persistence.ManyToMany; 14 | 15 | import org.springframework.security.core.GrantedAuthority; 16 | import org.springframework.security.core.authority.SimpleGrantedAuthority; 17 | import org.springframework.security.core.userdetails.UserDetails; 18 | 19 | @Entity 20 | public class User extends BaseIdEntity implements UserDetails { 21 | 22 | private static final long serialVersionUID = 1L; 23 | private String email; 24 | private String username; 25 | private String password; 26 | private boolean enabled; 27 | 28 | @Column(name = "account_locked") 29 | private boolean accountNonLocked; 30 | 31 | @Column(name = "account_expired") 32 | private boolean accountNonExpired; 33 | 34 | @Column(name = "credentials_expired") 35 | private boolean credentialsNonExpired; 36 | 37 | @ManyToMany(fetch = FetchType.EAGER) 38 | @JoinTable(name = "role_user", joinColumns = { 39 | @JoinColumn(name = "user_id", referencedColumnName = "id") }, inverseJoinColumns = { 40 | @JoinColumn(name = "role_id", referencedColumnName = "id") }) 41 | private List roles; 42 | 43 | @Override 44 | public boolean isEnabled() { 45 | return enabled; 46 | } 47 | 48 | @Override 49 | public boolean isAccountNonExpired() { 50 | return !accountNonExpired; 51 | } 52 | 53 | @Override 54 | public boolean isCredentialsNonExpired() { 55 | return !credentialsNonExpired; 56 | } 57 | 58 | @Override 59 | public boolean isAccountNonLocked() { 60 | return !accountNonLocked; 61 | } 62 | 63 | /* 64 | * Get roles and permissions and add them as a Set of GrantedAuthority 65 | */ 66 | @Override 67 | public Collection getAuthorities() { 68 | Set authorities = new HashSet(); 69 | 70 | roles.forEach(r -> { 71 | authorities.add(new SimpleGrantedAuthority(r.getName())); 72 | r.getPermissions().forEach(p -> { 73 | authorities.add(new SimpleGrantedAuthority(p.getName())); 74 | }); 75 | }); 76 | 77 | return authorities; 78 | } 79 | 80 | @Override 81 | public String getPassword() { 82 | return password; 83 | } 84 | 85 | @Override 86 | public String getUsername() { 87 | return username; 88 | } 89 | 90 | public String getEmail() { 91 | return email; 92 | } 93 | 94 | public void setEmail(String email) { 95 | this.email = email; 96 | } 97 | 98 | } 99 | -------------------------------------------------------------------------------- /src/main/java/com/talk2amareswaran/projects/springboot2authserver/repository/UserRepository.java: -------------------------------------------------------------------------------- 1 | package com.talk2amareswaran.projects.springboot2authserver.repository; 2 | 3 | import javax.transaction.Transactional; 4 | 5 | import org.springframework.data.jpa.repository.JpaRepository; 6 | import org.springframework.stereotype.Repository; 7 | 8 | import com.talk2amareswaran.projects.springboot2authserver.entity.User; 9 | 10 | @Repository 11 | @Transactional 12 | public interface UserRepository extends JpaRepository { 13 | 14 | User findByUsername(String username); 15 | 16 | } 17 | 18 | 19 | -------------------------------------------------------------------------------- /src/main/java/com/talk2amareswaran/projects/springboot2authserver/service/CustomUserDetailsService.java: -------------------------------------------------------------------------------- 1 | package com.talk2amareswaran.projects.springboot2authserver.service; 2 | 3 | import org.springframework.beans.factory.annotation.Autowired; 4 | import org.springframework.security.authentication.AccountStatusUserDetailsChecker; 5 | import org.springframework.security.authentication.BadCredentialsException; 6 | import org.springframework.security.core.userdetails.UserDetails; 7 | import org.springframework.security.core.userdetails.UserDetailsService; 8 | import org.springframework.stereotype.Service; 9 | 10 | import com.talk2amareswaran.projects.springboot2authserver.entity.User; 11 | import com.talk2amareswaran.projects.springboot2authserver.repository.UserRepository; 12 | 13 | @Service(value = "userDetailsService") 14 | public class CustomUserDetailsService implements UserDetailsService { 15 | 16 | @Autowired 17 | private UserRepository userRepository; 18 | 19 | @Override 20 | public UserDetails loadUserByUsername(String input) { 21 | User user = userRepository.findByUsername(input); 22 | 23 | if (user == null) 24 | throw new BadCredentialsException("Bad credentials"); 25 | 26 | new AccountStatusUserDetailsChecker().check(user); 27 | 28 | return user; 29 | } 30 | } 31 | -------------------------------------------------------------------------------- /src/main/resources/application.yml: -------------------------------------------------------------------------------- 1 | server: 2 | port: 9001 3 | spring: 4 | datasource: 5 | url: jdbc:mysql://localhost:3306/oauth2_database?useSSL=false 6 | username: root 7 | password: root 8 | driver-class-name: com.mysql.jdbc.Driver 9 | tomcat: 10 | test-while-idle: true 11 | validation-query: SELECT 1 12 | initialization-mode: never 13 | platform: mysql 14 | jpa: 15 | properties: 16 | hibernate: 17 | dialect: org.hibernate.dialect.MySQL5Dialect 18 | hibernate: 19 | naming: 20 | physical-strategy: org.springframework.boot.orm.jpa.hibernate.SpringPhysicalNamingStrategy 21 | ddl-auto: validate 22 | 23 | check-user-scopes: true -------------------------------------------------------------------------------- /src/main/resources/jwt.jks: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/talk2amareswaran/spring-boot2-oauth2-auth-server-jwt-mysql/a056fb7bca818bda44dc24c76ad77a0e180f534e/src/main/resources/jwt.jks -------------------------------------------------------------------------------- /src/test/java/com/talk2amareswaran/projects/springboot2authserver/Springboot2AuthserverApplicationTests.java: -------------------------------------------------------------------------------- 1 | package com.talk2amareswaran.projects.springboot2authserver; 2 | 3 | import org.junit.Test; 4 | import org.junit.runner.RunWith; 5 | import org.springframework.boot.test.context.SpringBootTest; 6 | import org.springframework.test.context.junit4.SpringRunner; 7 | 8 | @RunWith(SpringRunner.class) 9 | @SpringBootTest 10 | public class Springboot2AuthserverApplicationTests { 11 | 12 | @Test 13 | public void contextLoads() { 14 | } 15 | 16 | } 17 | --------------------------------------------------------------------------------