SpringBoot實戰電商項目mall(20k+star)地址: https://github.com/macrozheng/mall
Spring Cloud Security 爲構建安全的SpringBoot應用提供了一系列解決方案,結合Oauth2能夠實現單點登陸、令牌中繼、令牌交換等功能,本文將對其結合Oauth2入門使用進行詳細介紹。java
OAuth 2.0是用於受權的行業標準協議。OAuth 2.0爲簡化客戶端開發提供了特定的受權流,包括Web應用、桌面應用、移動端應用等。git
這裏咱們建立一個oauth2-server模塊做爲認證服務器來使用。
<dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-starter-oauth2</artifactId> </dependency> <dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-starter-security</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency>
server: port: 9401 spring: application: name: oauth2-service
/** * Created by macro on 2019/9/30. */ @Service public class UserService implements UserDetailsService { private List<User> userList; @Autowired private PasswordEncoder passwordEncoder; @PostConstruct public void initData() { String password = passwordEncoder.encode("123456"); userList = new ArrayList<>(); userList.add(new User("macro", password, AuthorityUtils.commaSeparatedStringToAuthorityList("admin"))); userList.add(new User("andy", password, AuthorityUtils.commaSeparatedStringToAuthorityList("client"))); userList.add(new User("mark", password, AuthorityUtils.commaSeparatedStringToAuthorityList("client"))); } @Override public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException { List<User> findUserList = userList.stream().filter(user -> user.getUsername().equals(username)).collect(Collectors.toList()); if (!CollectionUtils.isEmpty(findUserList)) { return findUserList.get(0); } else { throw new UsernameNotFoundException("用戶名或密碼錯誤"); } } }
/** * 認證服務器配置 * Created by macro on 2019/9/30. */ @Configuration @EnableAuthorizationServer public class AuthorizationServerConfig extends AuthorizationServerConfigurerAdapter { @Autowired private PasswordEncoder passwordEncoder; @Autowired private AuthenticationManager authenticationManager; @Autowired private UserService userService; /** * 使用密碼模式須要配置 */ @Override public void configure(AuthorizationServerEndpointsConfigurer endpoints) { endpoints.authenticationManager(authenticationManager) .userDetailsService(userService); } @Override public void configure(ClientDetailsServiceConfigurer clients) throws Exception { clients.inMemory() .withClient("admin")//配置client_id .secret(passwordEncoder.encode("admin123456"))//配置client_secret .accessTokenValiditySeconds(3600)//配置訪問token的有效期 .refreshTokenValiditySeconds(864000)//配置刷新token的有效期 .redirectUris("http://www.baidu.com")//配置redirect_uri,用於受權成功後跳轉 .scopes("all")//配置申請的權限範圍 .authorizedGrantTypes("authorization_code","password");//配置grant_type,表示受權類型 } }
/** * 資源服務器配置 * Created by macro on 2019/9/30. */ @Configuration @EnableResourceServer public class ResourceServerConfig extends ResourceServerConfigurerAdapter { @Override public void configure(HttpSecurity http) throws Exception { http.authorizeRequests() .anyRequest() .authenticated() .and() .requestMatchers() .antMatchers("/user/**");//配置須要保護的資源路徑 } }
/** * SpringSecurity配置 * Created by macro on 2019/10/8. */ @Configuration @EnableWebSecurity public class SecurityConfig extends WebSecurityConfigurerAdapter { @Bean public PasswordEncoder passwordEncoder() { return new BCryptPasswordEncoder(); } @Bean @Override public AuthenticationManager authenticationManagerBean() throws Exception { return super.authenticationManagerBean(); } @Override public void configure(HttpSecurity http) throws Exception { http.csrf() .disable() .authorizeRequests() .antMatchers("/oauth/**", "/login/**", "/logout/**") .permitAll() .anyRequest() .authenticated() .and() .formLogin() .permitAll(); } }
/** * Created by macro on 2019/9/30. */ @RestController @RequestMapping("/user") public class UserController { @GetMapping("/getCurrentUser") public Object getCurrentUser(Authentication authentication) { return authentication.getPrincipal(); } }
https://www.baidu.com/?code=eTsADY&state=normal
springcloud-learning └── oauth2-server -- oauth2認證測試服務
https://github.com/macrozheng/springcloud-learninggithub
mall項目全套學習教程連載中,關注公衆號第一時間獲取。web