您好,登錄后才能下訂單哦!
本篇內容主要講解“spring oauth2 +springboot sso的案例分析”,感興趣的朋友不妨來看看。本文介紹的方法操作簡單快捷,實用性強。下面就讓小編來帶大家學習“spring oauth2 +springboot sso的案例分析”吧!
<dependency> <groupId>org.springframework.security.oauth.boot</groupId> <artifactId>spring-security-oauth3-autoconfigure</artifactId> <version>2.1.6.RELEASE</version> </dependency>
1.服務端需要的是授權與身份驗證,通過配置@EnableAuthorizationServer、@EnableWebSecurity、@EnableResourceServer來完成配置。
2.先來配置WebSecurity的配置
package com.example.oauth; import org.springframework.boot.autoconfigure.security.SecurityProperties; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.core.annotation.Order; import org.springframework.security.authentication.AuthenticationManager; import org.springframework.security.config.BeanIds; import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder; import org.springframework.security.config.annotation.web.builders.HttpSecurity; import org.springframework.security.config.annotation.web.builders.WebSecurity; import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity; import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter; import org.springframework.security.core.userdetails.User; import org.springframework.security.core.userdetails.UserDetailsService; import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder; import org.springframework.security.provisioning.InMemoryUserDetailsManager; /** * @author sorata * @date 2019-07-23 09:19 */ @Configuration @EnableWebSecurity @Order(SecurityProperties.BASIC_AUTH_ORDER) public class WebSecurityConfig extends WebSecurityConfigurerAdapter { @Bean public UserDetailsService myUserDetailsService(){ return new InMemoryUserDetailsManager(User.builder().username("admin").password(passwordEncoder().encode("admin")).roles("ADMIN").build()); } @Bean public BCryptPasswordEncoder passwordEncoder(){ return new BCryptPasswordEncoder(); } @Override protected void configure(AuthenticationManagerBuilder auth) throws Exception { auth.userDetailsService(myUserDetailsService()).passwordEncoder(passwordEncoder()); } @Bean(BeanIds.AUTHENTICATION_MANAGER) @Override public AuthenticationManager authenticationManagerBean() throws Exception { return super.authenticationManagerBean(); } @Override public void configure(WebSecurity web) throws Exception { super.configure(web); } @Override protected void configure(HttpSecurity http) throws Exception { http.csrf().disable().antMatcher("/**") .authorizeRequests() .antMatchers("/","/login","/oauth/**").permitAll() .anyRequest().authenticated() .and().httpBasic().and().formLogin() .and().logout(); } }
note:首先是配置用戶UserDetailsService,然后配置密碼策略。主要的部分是 configure(HttpSecurity http) 方法,這里當我在formLogin()后配置了驗證完成轉發(fā),即successForwardUrl(“/main”)后,sso客戶端請求驗證完成時,不會跳轉到客戶端的請求地址,而是跳轉到驗證成功的服務端地址 /main。
3.編寫一個用戶信息的controller
package com.example.oauth; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; import java.security.Principal; /** * @author sorata * @date 2019-07-23 09:17 */ @RestController public class UserController { @RequestMapping("/user") public Principal principal(Principal principal){ return principal; } @RequestMapping("/user2") public Principal principal2(Principal principal){ return principal; } }
note: 作用就是測試和之后客戶端填寫的服務器用戶信息的url
4.資源服務器
package com.example.oauth; import org.springframework.context.annotation.Configuration; import org.springframework.security.config.annotation.web.builders.HttpSecurity; import org.springframework.security.oauth3.config.annotation.web.configuration.EnableResourceServer; import org.springframework.security.oauth3.config.annotation.web.configuration.ResourceServerConfigurerAdapter; /** * @author sorata * @date 2019-07-23 09:50 */ @Configuration @EnableResourceServer public class ResourceConfig extends ResourceServerConfigurerAdapter { @Override public void configure(HttpSecurity http) throws Exception { http.csrf().disable().antMatcher("/user") .authorizeRequests().anyRequest().authenticated(); } }
5.完成后的效果
6. 重要的認證服務端
package com.example.oauth; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.security.authentication.AuthenticationManager; import org.springframework.security.core.userdetails.UserDetailsService; import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder; import org.springframework.security.oauth3.config.annotation.configurers.ClientDetailsServiceConfigurer; import org.springframework.security.oauth3.config.annotation.web.configuration.AuthorizationServerConfigurerAdapter; import org.springframework.security.oauth3.config.annotation.web.configuration.EnableAuthorizationServer; import org.springframework.security.oauth3.config.annotation.web.configurers.AuthorizationServerEndpointsConfigurer; import org.springframework.security.oauth3.config.annotation.web.configurers.AuthorizationServerSecurityConfigurer; import org.springframework.security.oauth3.provider.token.TokenStore; import org.springframework.security.oauth3.provider.token.store.InMemoryTokenStore; /** * @author sorata * @date 2019-07-23 10:06 */ @Configuration @EnableAuthorizationServer public class SsoServerConfig extends AuthorizationServerConfigurerAdapter { @Autowired private AuthenticationManager authenticationManager; @Autowired private BCryptPasswordEncoder passwordEncoder; /** * 如果出現錯誤 在主類上去掉默認配置 * {@link SsoServerApplication} */ @Autowired private UserDetailsService detailsService; @Override public void configure(AuthorizationServerSecurityConfigurer security) throws Exception { security.allowFormAuthenticationForClients() .tokenKeyAccess("permitAll()") .checkTokenAccess("isAuthenticated()") .passwordEncoder(passwordEncoder); } @Override public void configure(ClientDetailsServiceConfigurer clients) throws Exception { clients.inMemory().withClient("cocos") .secret(passwordEncoder.encode("cocos")) .autoApprove(true) .redirectUris("http://localhost:9090/client/login") .scopes("all") .authorities("ADMIN") .authorizedGrantTypes("authorization_code","password","refresh_token") .accessTokenValiditySeconds(10000) .refreshTokenValiditySeconds(10000); } @Override public void configure(AuthorizationServerEndpointsConfigurer endpoints) throws Exception { endpoints.authenticationManager(authenticationManager) .userDetailsService(detailsService).tokenStore(tokenStore()); } @Bean public TokenStore tokenStore(){ return new InMemoryTokenStore(); } }
1.客戶端實現比較簡單,如果想針對行的修改,自定義那么可以根據后面參考地址研讀。
2.application.properties
security.oauth3.client.authentication-scheme=form security.oauth3.client.user-authorization-uri=http://localhost:8080/server/oauth/authorize security.oauth3.client.access-token-uri=http://localhost:8080/server/oauth/token security.oauth3.client.client-id=cocos security.oauth3.client.client-secret=cocos security.oauth3.resource.user-info-uri=http://localhost:8080/server/user server.servlet.context-path=/client server.port=9090
3.主類添加注解
package com.example.oauth; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.boot.autoconfigure.security.oauth3.client.EnableOAuth3Sso; @SpringBootApplication @EnableOAuth3Sso public class SsoClientApplication { public static void main(String[] args) { SpringApplication.run(SsoClientApplication.class, args); } }
4.用戶的接口
package com.example.oauth; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; import java.security.Principal; /** * @author sorata * @date 2019-07-23 10:30 */ @RestController public class UserController { @RequestMapping("/user") public Principal principal(Principal principal){ return principal; } }
note: 如果想看到
到此,相信大家對“spring oauth2 +springboot sso的案例分析”有了更深的了解,不妨來實際操作一番吧!這里是億速云網站,更多相關內容可以進入相關頻道進行查詢,關注我們,繼續(xù)學習!
免責聲明:本站發(fā)布的內容(圖片、視頻和文字)以原創(chuàng)、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。