├── src ├── main │ ├── resources │ │ └── application.properties │ └── java │ │ └── com │ │ └── lxg │ │ └── springboot │ │ ├── service │ │ ├── UserRoleService.java │ │ ├── UserService.java │ │ └── impl │ │ │ ├── UserRoleServiceImpl.java │ │ │ └── UserServiceImpl.java │ │ ├── mapper │ │ ├── RoleRepository.java │ │ ├── UserRepository.java │ │ └── UserRoleRepository.java │ │ ├── Application.java │ │ ├── entity │ │ ├── Role.java │ │ ├── UserRole.java │ │ └── User.java │ │ ├── security │ │ ├── ResourceServerConfiguration.java │ │ ├── AuthorizationServerConfiguration.java │ │ └── OAuth2SecurityConfiguration.java │ │ ├── config │ │ └── MyUserDetailsService.java │ │ └── controller │ │ └── HelloWorldRestController.java └── test │ └── java │ └── com │ └── lxg │ └── springboot │ └── test │ └── ApplicationTests.java ├── Readme.md └── pom.xml /src/main/resources/application.properties: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/li5454yong/springboot-security-oauth2/HEAD/src/main/resources/application.properties -------------------------------------------------------------------------------- /Readme.md: -------------------------------------------------------------------------------- 1 | # springboot-security-oauth2 2 | ### Spring集成Spring Security、OAuth2实现资源访问授权认证。 3 | ### 后端主要做的是认证服务器和资源服务。 4 | ### 用户登录使用自定义UserDetailService从MySQL中加载数据。 5 | ### 用户认证的token使用RedisTokenStore保存在redis中。 -------------------------------------------------------------------------------- /src/main/java/com/lxg/springboot/service/UserRoleService.java: -------------------------------------------------------------------------------- 1 | package com.lxg.springboot.service; 2 | 3 | import java.util.List; 4 | 5 | /** 6 | * Created by lxg 7 | * on 2017/2/21. 8 | */ 9 | public interface UserRoleService { 10 | 11 | List findRoles(int uid); 12 | } 13 | -------------------------------------------------------------------------------- /src/main/java/com/lxg/springboot/service/UserService.java: -------------------------------------------------------------------------------- 1 | package com.lxg.springboot.service; 2 | 3 | import com.lxg.springboot.entity.User; 4 | 5 | import java.util.List; 6 | 7 | /** 8 | * Created by lxg 9 | * on 2017/2/21. 10 | */ 11 | public interface UserService { 12 | 13 | User findByUsername(String name); 14 | 15 | List findAll(); 16 | 17 | } 18 | -------------------------------------------------------------------------------- /src/main/java/com/lxg/springboot/mapper/RoleRepository.java: -------------------------------------------------------------------------------- 1 | package com.lxg.springboot.mapper; 2 | 3 | import com.lxg.springboot.entity.Role; 4 | import org.springframework.data.jpa.repository.JpaRepository; 5 | import org.springframework.stereotype.Repository; 6 | 7 | /** 8 | * Created by lxg 9 | * on 2017/2/20. 10 | */ 11 | @Repository 12 | public interface RoleRepository extends JpaRepository { 13 | } 14 | -------------------------------------------------------------------------------- /src/main/java/com/lxg/springboot/Application.java: -------------------------------------------------------------------------------- 1 | package com.lxg.springboot; 2 | 3 | import org.springframework.boot.SpringApplication; 4 | 5 | /** 6 | * Created by lxg 7 | * on 2017/2/18. 8 | */ 9 | @org.springframework.boot.autoconfigure.SpringBootApplication 10 | public class Application { 11 | 12 | public static void main(String[] args){ 13 | new SpringApplication(Application.class).run(args); 14 | } 15 | } 16 | -------------------------------------------------------------------------------- /src/main/java/com/lxg/springboot/mapper/UserRepository.java: -------------------------------------------------------------------------------- 1 | package com.lxg.springboot.mapper; 2 | 3 | import com.lxg.springboot.entity.User; 4 | import org.springframework.data.jpa.repository.JpaRepository; 5 | import org.springframework.stereotype.Repository; 6 | 7 | /** 8 | * Created by lxg 9 | * on 2017/2/20. 10 | */ 11 | @Repository 12 | public interface UserRepository extends JpaRepository { 13 | 14 | User findByUsername(String name); 15 | 16 | } 17 | -------------------------------------------------------------------------------- /src/main/java/com/lxg/springboot/mapper/UserRoleRepository.java: -------------------------------------------------------------------------------- 1 | package com.lxg.springboot.mapper; 2 | 3 | import com.lxg.springboot.entity.UserRole; 4 | import org.springframework.data.jpa.repository.JpaRepository; 5 | import org.springframework.data.jpa.repository.Query; 6 | import org.springframework.data.repository.query.Param; 7 | import org.springframework.stereotype.Repository; 8 | 9 | import java.util.List; 10 | 11 | /** 12 | * Created by lxg 13 | * on 2017/2/20. 14 | */ 15 | @Repository 16 | public interface UserRoleRepository extends JpaRepository { 17 | 18 | List findByuid(int uid); 19 | 20 | @Query(value = "select r.role_name from user_role ur left join role r on ur.rid=r.id where ur.uid = ?1",nativeQuery = true) 21 | List findRoleName(int uid); 22 | } 23 | -------------------------------------------------------------------------------- /src/main/java/com/lxg/springboot/service/impl/UserRoleServiceImpl.java: -------------------------------------------------------------------------------- 1 | package com.lxg.springboot.service.impl; 2 | 3 | import com.lxg.springboot.entity.UserRole; 4 | import com.lxg.springboot.mapper.UserRoleRepository; 5 | import com.lxg.springboot.service.UserRoleService; 6 | import org.springframework.beans.factory.annotation.Autowired; 7 | import org.springframework.stereotype.Service; 8 | 9 | import java.util.List; 10 | 11 | /** 12 | * Created by lxg 13 | * on 2017/2/21. 14 | */ 15 | @Service 16 | public class UserRoleServiceImpl implements UserRoleService { 17 | 18 | @Autowired 19 | private UserRoleRepository userRoleRepository; 20 | @Override 21 | public List findRoles(int uid) { 22 | 23 | List list = userRoleRepository.findRoleName(uid); 24 | 25 | return list; 26 | } 27 | } 28 | -------------------------------------------------------------------------------- /src/main/java/com/lxg/springboot/service/impl/UserServiceImpl.java: -------------------------------------------------------------------------------- 1 | package com.lxg.springboot.service.impl; 2 | 3 | import com.lxg.springboot.entity.User; 4 | import com.lxg.springboot.mapper.UserRepository; 5 | import com.lxg.springboot.service.UserService; 6 | import org.springframework.beans.factory.annotation.Autowired; 7 | import org.springframework.stereotype.Service; 8 | 9 | import java.util.List; 10 | 11 | /** 12 | * Created by lxg 13 | * on 2017/2/21. 14 | */ 15 | @Service 16 | public class UserServiceImpl implements UserService { 17 | 18 | @Autowired 19 | private UserRepository userRepository; 20 | 21 | @Override 22 | public User findByUsername(String name) { 23 | return userRepository.findByUsername(name); 24 | } 25 | 26 | @Override 27 | public List findAll() { 28 | return userRepository.findAll(); 29 | } 30 | 31 | } 32 | -------------------------------------------------------------------------------- /src/main/java/com/lxg/springboot/entity/Role.java: -------------------------------------------------------------------------------- 1 | package com.lxg.springboot.entity; 2 | 3 | import javax.persistence.*; 4 | import java.io.Serializable; 5 | import java.util.HashSet; 6 | import java.util.Set; 7 | 8 | import static javax.persistence.GenerationType.IDENTITY; 9 | 10 | /** 11 | * Created by lxg 12 | * on 2017/2/20. 13 | */ 14 | @Entity 15 | @Table(name = "role") 16 | public class Role implements Serializable{ 17 | private int id; 18 | private String role_name; 19 | 20 | 21 | @Id 22 | @GeneratedValue(strategy = IDENTITY) 23 | public int getId() { 24 | return id; 25 | } 26 | 27 | public void setId(int id) { 28 | this.id = id; 29 | } 30 | 31 | public String getRole_name() { 32 | return role_name; 33 | } 34 | 35 | public void setRole_name(String role_name) { 36 | this.role_name = role_name; 37 | } 38 | } 39 | -------------------------------------------------------------------------------- /src/main/java/com/lxg/springboot/entity/UserRole.java: -------------------------------------------------------------------------------- 1 | package com.lxg.springboot.entity; 2 | 3 | import javax.persistence.*; 4 | import java.io.Serializable; 5 | 6 | import static javax.persistence.GenerationType.IDENTITY; 7 | 8 | /** 9 | * Created by lxg 10 | * on 2017/2/20. 11 | */ 12 | @Entity 13 | @Table(name = "user_role") 14 | public class UserRole implements Serializable{ 15 | private int id; 16 | private int uid; 17 | private int rid; 18 | 19 | @Id 20 | @GeneratedValue(strategy = IDENTITY) 21 | public int getId() { 22 | return id; 23 | } 24 | 25 | public void setId(int id) { 26 | this.id = id; 27 | } 28 | 29 | 30 | public int getUid() { 31 | return uid; 32 | } 33 | 34 | public void setUid(int uid) { 35 | this.uid = uid; 36 | } 37 | 38 | public int getRid() { 39 | return rid; 40 | } 41 | 42 | public void setRid(int rid) { 43 | this.rid = rid; 44 | } 45 | } 46 | -------------------------------------------------------------------------------- /src/test/java/com/lxg/springboot/test/ApplicationTests.java: -------------------------------------------------------------------------------- 1 | package com.lxg.springboot.test; 2 | 3 | import com.lxg.springboot.Application; 4 | import com.lxg.springboot.entity.User; 5 | import com.lxg.springboot.entity.UserRole; 6 | import com.lxg.springboot.mapper.UserRepository; 7 | import com.lxg.springboot.mapper.UserRoleRepository; 8 | import org.junit.Test; 9 | import org.junit.runner.RunWith; 10 | import org.springframework.beans.factory.annotation.Autowired; 11 | import org.springframework.boot.test.SpringApplicationConfiguration; 12 | import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; 13 | 14 | import java.util.List; 15 | 16 | /** 17 | * Created by lxg 18 | * on 2017/2/20. 19 | */ 20 | @RunWith(SpringJUnit4ClassRunner.class) 21 | @SpringApplicationConfiguration(Application.class) 22 | public class ApplicationTests { 23 | 24 | @Autowired 25 | private UserRepository userRepository; 26 | 27 | @Autowired 28 | private UserRoleRepository userRoleRepository; 29 | 30 | @Test 31 | public void test() throws Exception { 32 | //User user = userRepository.findByUsername("123"); 33 | //List userRole = userRoleRepository.findByuid(1); 34 | 35 | 36 | List list = userRoleRepository.findRoleName(1); 37 | System.out.println(list.get(0)); 38 | } 39 | } 40 | -------------------------------------------------------------------------------- /src/main/java/com/lxg/springboot/security/ResourceServerConfiguration.java: -------------------------------------------------------------------------------- 1 | package com.lxg.springboot.security; 2 | 3 | import org.springframework.context.annotation.Configuration; 4 | import org.springframework.security.config.annotation.web.builders.HttpSecurity; 5 | import org.springframework.security.oauth2.config.annotation.web.configuration.EnableResourceServer; 6 | import org.springframework.security.oauth2.config.annotation.web.configuration.ResourceServerConfigurerAdapter; 7 | import org.springframework.security.oauth2.config.annotation.web.configurers.ResourceServerSecurityConfigurer; 8 | import org.springframework.security.oauth2.provider.error.OAuth2AccessDeniedHandler; 9 | 10 | /** 11 | * 资源服务器 12 | */ 13 | @Configuration 14 | @EnableResourceServer 15 | public class ResourceServerConfiguration extends ResourceServerConfigurerAdapter { 16 | 17 | private static final String RESOURCE_ID = "my_rest_api"; 18 | 19 | @Override 20 | public void configure(ResourceServerSecurityConfigurer resources) { 21 | resources.resourceId(RESOURCE_ID).stateless(false); 22 | } 23 | 24 | @Override 25 | public void configure(HttpSecurity http) throws Exception { 26 | http. 27 | anonymous().disable() 28 | .requestMatchers().antMatchers("/user*/**") 29 | .and().authorizeRequests() 30 | .antMatchers("/user*/**").permitAll() 31 | .and().exceptionHandling().accessDeniedHandler(new OAuth2AccessDeniedHandler()); 32 | } 33 | 34 | } -------------------------------------------------------------------------------- /src/main/java/com/lxg/springboot/entity/User.java: -------------------------------------------------------------------------------- 1 | package com.lxg.springboot.entity; 2 | 3 | import javax.persistence.*; 4 | import java.io.Serializable; 5 | import java.util.ArrayList; 6 | import java.util.List; 7 | 8 | import static javax.persistence.GenerationType.IDENTITY; 9 | 10 | /** 11 | * Created by lxg 12 | * on 2017/2/20. 13 | */ 14 | @Entity 15 | @Table(name = "user") 16 | public class User implements Serializable { 17 | private int id; 18 | private String username; 19 | private String password; 20 | private List list = new ArrayList(); 21 | 22 | @OneToMany(cascade = { CascadeType.ALL }, fetch = FetchType.EAGER) 23 | @JoinTable(name="user_role", 24 | joinColumns={ @JoinColumn(name="uid",referencedColumnName="id")}, 25 | inverseJoinColumns={@JoinColumn(name="rid",referencedColumnName="id")}) 26 | public List getList() { 27 | return list; 28 | } 29 | 30 | public void setList(List list) { 31 | this.list = list; 32 | } 33 | 34 | @Id 35 | @GeneratedValue(strategy = IDENTITY) 36 | public int getId() { 37 | return id; 38 | } 39 | 40 | public void setId(int id) { 41 | this.id = id; 42 | } 43 | 44 | public String getUsername() { 45 | return username; 46 | } 47 | 48 | public void setUsername(String username) { 49 | this.username = username; 50 | } 51 | 52 | public String getPassword() { 53 | return password; 54 | } 55 | 56 | public void setPassword(String password) { 57 | this.password = password; 58 | } 59 | } 60 | -------------------------------------------------------------------------------- /src/main/java/com/lxg/springboot/config/MyUserDetailsService.java: -------------------------------------------------------------------------------- 1 | package com.lxg.springboot.config; 2 | 3 | import com.lxg.springboot.entity.Role; 4 | import com.lxg.springboot.entity.User; 5 | import com.lxg.springboot.entity.UserRole; 6 | import com.lxg.springboot.service.UserRoleService; 7 | import com.lxg.springboot.service.UserService; 8 | import org.springframework.beans.factory.annotation.Autowired; 9 | import org.springframework.security.core.authority.SimpleGrantedAuthority; 10 | import org.springframework.security.core.userdetails.UserDetails; 11 | import org.springframework.security.core.userdetails.UserDetailsService; 12 | import org.springframework.security.core.userdetails.UsernameNotFoundException; 13 | import org.springframework.stereotype.Component; 14 | 15 | import java.util.Collection; 16 | import java.util.HashSet; 17 | import java.util.Iterator; 18 | 19 | /** 20 | * Created by lxg 21 | * on 2017/2/20. 22 | */ 23 | public class MyUserDetailsService implements UserDetailsService { 24 | 25 | @Autowired 26 | private UserService userService; 27 | 28 | @Autowired 29 | private UserRoleService userRoleService; 30 | /** 31 | * 根据用户名获取登录用户信息 32 | * @param username 33 | * @return 34 | * @throws UsernameNotFoundException 35 | */ 36 | @Override 37 | public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException { 38 | User user = userService.findByUsername(username); 39 | 40 | if(user == null){ 41 | throw new UsernameNotFoundException("用户名:"+ username + "不存在!"); 42 | } 43 | Collection collection = new HashSet(); 44 | Iterator iterator = user.getList().iterator(); 45 | while (iterator.hasNext()){ 46 | collection.add(new SimpleGrantedAuthority(iterator.next().getRole_name())); 47 | } 48 | 49 | return new org.springframework.security.core.userdetails.User(username,user.getPassword(),collection); 50 | } 51 | } 52 | -------------------------------------------------------------------------------- /src/main/java/com/lxg/springboot/security/AuthorizationServerConfiguration.java: -------------------------------------------------------------------------------- 1 | package com.lxg.springboot.security; 2 | 3 | import org.springframework.beans.factory.annotation.Autowired; 4 | import org.springframework.beans.factory.annotation.Qualifier; 5 | import org.springframework.context.annotation.Configuration; 6 | import org.springframework.security.authentication.AuthenticationManager; 7 | import org.springframework.security.oauth2.config.annotation.configurers.ClientDetailsServiceConfigurer; 8 | import org.springframework.security.oauth2.config.annotation.web.configuration.AuthorizationServerConfigurerAdapter; 9 | import org.springframework.security.oauth2.config.annotation.web.configuration.EnableAuthorizationServer; 10 | import org.springframework.security.oauth2.config.annotation.web.configurers.AuthorizationServerEndpointsConfigurer; 11 | import org.springframework.security.oauth2.config.annotation.web.configurers.AuthorizationServerSecurityConfigurer; 12 | import org.springframework.security.oauth2.provider.approval.UserApprovalHandler; 13 | import org.springframework.security.oauth2.provider.token.DefaultTokenServices; 14 | import org.springframework.security.oauth2.provider.token.TokenStore; 15 | /** 16 | * 认证服务器配置 17 | * @author lxg 18 | * 19 | * 2017年2月17日上午10:50:04 20 | */ 21 | @Configuration 22 | @EnableAuthorizationServer 23 | public class AuthorizationServerConfiguration extends AuthorizationServerConfigurerAdapter { 24 | 25 | private static String REALM="MY_OAUTH_REALM"; 26 | 27 | @Autowired 28 | private TokenStore tokenStore; 29 | 30 | @Autowired 31 | private UserApprovalHandler userApprovalHandler; 32 | 33 | @Autowired 34 | @Qualifier("authenticationManagerBean") 35 | private AuthenticationManager authenticationManager; 36 | 37 | @Override 38 | public void configure(ClientDetailsServiceConfigurer clients) throws Exception { 39 | 40 | clients.inMemory() 41 | .withClient("my-trusted-client")//客户端ID 42 | .authorizedGrantTypes("password", "authorization_code", "refresh_token", "implicit") 43 | .authorities("ROLE_CLIENT", "ROLE_TRUSTED_CLIENT") 44 | .scopes("read", "write", "trust")//授权用户的操作权限 45 | .secret("secret")//密码 46 | .accessTokenValiditySeconds(120).//token有效期为120秒 47 | refreshTokenValiditySeconds(600);//刷新token有效期为600秒 48 | } 49 | 50 | @Override 51 | public void configure(AuthorizationServerEndpointsConfigurer endpoints) throws Exception { 52 | endpoints.tokenStore(tokenStore).userApprovalHandler(userApprovalHandler) 53 | .authenticationManager(authenticationManager); 54 | } 55 | 56 | @Override 57 | public void configure(AuthorizationServerSecurityConfigurer oauthServer) throws Exception { 58 | oauthServer.realm(REALM+"/client"); 59 | } 60 | 61 | } -------------------------------------------------------------------------------- /pom.xml: -------------------------------------------------------------------------------- 1 | 2 | 5 | 4.0.0 6 | 7 | com.lxg.springboot 8 | springboot-security-oauth2 9 | 1.0-SNAPSHOT 10 | 11 | 12 | org.springframework.boot 13 | spring-boot-starter-parent 14 | 1.4.4.RELEASE 15 | 16 | 17 | 18 | 19 | 20 | aliyunRepository 21 | myRepository 22 | http://maven.aliyun.com/nexus/content/groups/public/ 23 | 24 | false 25 | 26 | 27 | 28 | 29 | 30 | UTF-8 31 | 1.7 32 | 2.0.3.RELEASE 33 | 34 | 35 | 36 | 37 | org.springframework.boot 38 | spring-boot-starter-jdbc 39 | 40 | 41 | org.springframework.boot 42 | spring-boot-starter-web 43 | 44 | 45 | org.springframework.boot 46 | spring-boot-starter-redis 47 | 48 | 49 | org.springframework.boot 50 | spring-boot-starter-data-jpa 51 | 52 | 53 | org.springframework.boot 54 | spring-boot-starter-security 55 | 56 | 57 | org.springframework.security.oauth 58 | spring-security-oauth2 59 | 60 | 61 | mysql 62 | mysql-connector-java 63 | runtime 64 | 65 | 66 | org.springframework.boot 67 | spring-boot-starter-test 68 | test 69 | 70 | 71 | 72 | 73 | 74 | -------------------------------------------------------------------------------- /src/main/java/com/lxg/springboot/security/OAuth2SecurityConfiguration.java: -------------------------------------------------------------------------------- 1 | package com.lxg.springboot.security; 2 | 3 | import com.lxg.springboot.config.MyUserDetailsService; 4 | import org.springframework.beans.factory.annotation.Autowired; 5 | import org.springframework.context.annotation.Bean; 6 | import org.springframework.context.annotation.Configuration; 7 | import org.springframework.data.redis.connection.RedisConnection; 8 | import org.springframework.data.redis.connection.RedisConnectionFactory; 9 | import org.springframework.security.authentication.AuthenticationManager; 10 | import org.springframework.security.authentication.encoding.Md5PasswordEncoder; 11 | import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder; 12 | import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity; 13 | import org.springframework.security.config.annotation.web.builders.HttpSecurity; 14 | import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity; 15 | import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter; 16 | import org.springframework.security.oauth2.provider.ClientDetailsService; 17 | import org.springframework.security.oauth2.provider.approval.ApprovalStore; 18 | import org.springframework.security.oauth2.provider.approval.TokenApprovalStore; 19 | import org.springframework.security.oauth2.provider.approval.TokenStoreUserApprovalHandler; 20 | import org.springframework.security.oauth2.provider.request.DefaultOAuth2RequestFactory; 21 | import org.springframework.security.oauth2.provider.token.TokenStore; 22 | import org.springframework.security.oauth2.provider.token.store.InMemoryTokenStore; 23 | import org.springframework.security.oauth2.provider.token.store.redis.RedisTokenStore; 24 | 25 | /** 26 | * security配置 27 | * 28 | * @author lxg 29 | * 30 | * 2017年2月17日上午11:13:55 31 | */ 32 | @Configuration 33 | @EnableWebSecurity 34 | @EnableGlobalMethodSecurity(prePostEnabled = true) 35 | public class OAuth2SecurityConfiguration extends WebSecurityConfigurerAdapter { 36 | 37 | @Autowired 38 | private ClientDetailsService clientDetailsService; 39 | 40 | @Autowired 41 | private RedisConnectionFactory redisConnection; 42 | 43 | @Bean 44 | public MyUserDetailsService myUserDetailsService(){ 45 | return new MyUserDetailsService(); 46 | } 47 | @Autowired 48 | public void globalUserDetails(AuthenticationManagerBuilder auth) throws Exception { 49 | auth 50 | .userDetailsService(myUserDetailsService()) 51 | .passwordEncoder(new Md5PasswordEncoder()); 52 | } 53 | 54 | 55 | @Override 56 | protected void configure(HttpSecurity http) throws Exception { 57 | http 58 | .anonymous().disable() 59 | .authorizeRequests() 60 | .antMatchers("/oauth/token").permitAll(); 61 | } 62 | 63 | @Override 64 | @Bean 65 | public AuthenticationManager authenticationManagerBean() throws Exception { 66 | return super.authenticationManagerBean(); 67 | } 68 | 69 | 70 | @Bean 71 | public TokenStore tokenStore() { 72 | return new RedisTokenStore(redisConnection); 73 | } 74 | 75 | @Bean 76 | @Autowired 77 | public TokenStoreUserApprovalHandler userApprovalHandler(TokenStore tokenStore){ 78 | TokenStoreUserApprovalHandler handler = new TokenStoreUserApprovalHandler(); 79 | handler.setTokenStore(tokenStore); 80 | handler.setRequestFactory(new DefaultOAuth2RequestFactory(clientDetailsService)); 81 | handler.setClientDetailsService(clientDetailsService); 82 | return handler; 83 | } 84 | 85 | @Bean 86 | @Autowired 87 | public ApprovalStore approvalStore(TokenStore tokenStore) throws Exception { 88 | TokenApprovalStore store = new TokenApprovalStore(); 89 | store.setTokenStore(tokenStore); 90 | return store; 91 | } 92 | 93 | } 94 | -------------------------------------------------------------------------------- /src/main/java/com/lxg/springboot/controller/HelloWorldRestController.java: -------------------------------------------------------------------------------- 1 | package com.lxg.springboot.controller; 2 | 3 | import java.util.List; 4 | 5 | import com.lxg.springboot.entity.User; 6 | import com.lxg.springboot.service.UserService; 7 | import org.springframework.beans.factory.annotation.Autowired; 8 | import org.springframework.http.HttpHeaders; 9 | import org.springframework.http.HttpStatus; 10 | import org.springframework.http.MediaType; 11 | import org.springframework.http.ResponseEntity; 12 | import org.springframework.security.access.prepost.PreAuthorize; 13 | import org.springframework.stereotype.Controller; 14 | import org.springframework.web.bind.annotation.*; 15 | import org.springframework.web.util.UriComponentsBuilder; 16 | 17 | @Controller 18 | public class HelloWorldRestController { 19 | 20 | @Autowired 21 | UserService userService; //Service which will do all data retrieval/manipulation work 22 | 23 | 24 | //-------------------Retrieve All Users-------------------------------------------------------- 25 | 26 | @PreAuthorize("hasRole('admin')") 27 | @RequestMapping(value = "/user/", method = RequestMethod.GET) 28 | @ResponseBody 29 | public List listAllUsers() { 30 | List users = userService.findAll(); 31 | if(users.isEmpty()){ 32 | return null; 33 | } 34 | return users; 35 | } 36 | 37 | 38 | //-------------------Retrieve Single User-------------------------------------------------------- 39 | 40 | /*@RequestMapping(value = "/user/{id}", method = RequestMethod.GET, produces = {MediaType.APPLICATION_JSON_VALUE,MediaType.APPLICATION_XML_VALUE}) 41 | public ResponseEntity getUser(@PathVariable("id") long id) { 42 | System.out.println("Fetching User with id " + id); 43 | User user = userService.findById(id); 44 | if (user == null) { 45 | System.out.println("User with id " + id + " not found"); 46 | return new ResponseEntity(HttpStatus.NOT_FOUND); 47 | } 48 | return new ResponseEntity(user, HttpStatus.OK); 49 | }*/ 50 | 51 | 52 | 53 | //-------------------Create a User-------------------------------------------------------- 54 | 55 | /*@RequestMapping(value = "/user/", method = RequestMethod.POST) 56 | public ResponseEntity createUser(@RequestBody User user, UriComponentsBuilder ucBuilder) { 57 | System.out.println("Creating User " + user.getName()); 58 | 59 | if (userService.isUserExist(user)) { 60 | System.out.println("A User with name " + user.getName() + " already exist"); 61 | return new ResponseEntity(HttpStatus.CONFLICT); 62 | } 63 | 64 | userService.saveUser(user); 65 | 66 | HttpHeaders headers = new HttpHeaders(); 67 | headers.setLocation(ucBuilder.path("/user/{id}").buildAndExpand(user.getId()).toUri()); 68 | return new ResponseEntity(headers, HttpStatus.CREATED); 69 | }*/ 70 | 71 | 72 | //------------------- Update a User -------------------------------------------------------- 73 | 74 | /*@RequestMapping(value = "/user/{id}", method = RequestMethod.PUT) 75 | public ResponseEntity updateUser(@PathVariable("id") long id, @RequestBody User user) { 76 | System.out.println("Updating User " + id); 77 | 78 | User currentUser = userService.findById(id); 79 | 80 | if (currentUser==null) { 81 | System.out.println("User with id " + id + " not found"); 82 | return new ResponseEntity(HttpStatus.NOT_FOUND); 83 | } 84 | 85 | currentUser.setName(user.getName()); 86 | currentUser.setAge(user.getAge()); 87 | currentUser.setSalary(user.getSalary()); 88 | 89 | userService.updateUser(currentUser); 90 | return new ResponseEntity(currentUser, HttpStatus.OK); 91 | }*/ 92 | 93 | //------------------- Delete a User -------------------------------------------------------- 94 | 95 | /*@RequestMapping(value = "/user/{id}", method = RequestMethod.DELETE) 96 | public ResponseEntity deleteUser(@PathVariable("id") long id) { 97 | System.out.println("Fetching & Deleting User with id " + id); 98 | 99 | User user = userService.findById(id); 100 | if (user == null) { 101 | System.out.println("Unable to delete. User with id " + id + " not found"); 102 | return new ResponseEntity(HttpStatus.NOT_FOUND); 103 | } 104 | 105 | userService.deleteUserById(id); 106 | return new ResponseEntity(HttpStatus.NO_CONTENT); 107 | }*/ 108 | 109 | 110 | //------------------- Delete All Users -------------------------------------------------------- 111 | 112 | /*@RequestMapping(value = "/user/", method = RequestMethod.DELETE) 113 | public ResponseEntity deleteAllUsers() { 114 | System.out.println("Deleting All Users"); 115 | 116 | userService.deleteAllUsers(); 117 | return new ResponseEntity(HttpStatus.NO_CONTENT); 118 | }*/ 119 | 120 | } --------------------------------------------------------------------------------