最新国产好看的视频,伊人天堂AV在线,国产Aaaaaa视频,蜜臀视频在线观看一区,人妻av色图,密臀久久久精品影片,青青视频免费观看毛片,久草在线观看视,国产三级精品色情在线

SpringSecurity OAtu2+JWT實現(xiàn)微服務版本的單點登錄的示例

 更新時間:2022年05月24日 08:45:54   作者:梵高的豬v  
本文主要介紹了SpringSecurity OAtu2+JWT實現(xiàn)微服務版本的單點登錄的示例,文中通過示例代碼介紹的非常詳細,具有一定的參考價值,感興趣的小伙伴們可以參考一下

何為單點登錄

單點登錄通俗的話來講在微服務當中,在一個服務登錄后就能免去另一個服務的登錄操作,所謂單點登錄.

就好像你在微博總網(wǎng)站里登錄后,然后在微博里面的某一個模塊點進去后,就發(fā)現(xiàn)這個模塊竟然不用登錄了,不是因為這個模塊與主網(wǎng)站是一體的用一個SpringSecurity就可以搞定了,這里面的水深著呢!
感興趣更深這個SpringSecurity建議去看看圖靈課堂的SpringSecurity,建議不要看尚硅谷的,那個版本說實話感覺有點老式了,教你手寫,其實我覺得,你既然學到了這個層次了,就應該能建立起快速打通一個新技術(shù)的能力,這個"打通"的意思不是要你深入,而是會用!別想著深入,因為沒有什么實際意義,現(xiàn)在不是我們小白應該做的事,我們小白只要打好基礎(chǔ)就可以了,比如java,jvm,spring,mysql這些!
沒有SpringSecurity基礎(chǔ)就別看這篇文章了,你可能看得懂,但是你肯定實現(xiàn)不出來,不信我你就看

認證中心

新建一個微服務模塊,可以另外建項目,也可以直接在你微服務項目里建立模塊就可以了.

maven配置

? <dependencies>
? ? ? ? <dependency>
? ? ? ? ? ? <groupId>org.springframework.boot</groupId>
? ? ? ? ? ? <artifactId>spring-boot-starter-thymeleaf</artifactId>
? ? ? ? </dependency>
? ? ? ? <dependency>
? ? ? ? ? ? <groupId>org.springframework.boot</groupId>
? ? ? ? ? ? <artifactId>spring-boot-starter-web</artifactId>
? ? ? ? </dependency>
? ? ? ? <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-test</artifactId>
? ? ? ? ? ? <scope>test</scope>
? ? ? ? ? ? <exclusions>
? ? ? ? ? ? ? ? <exclusion>
? ? ? ? ? ? ? ? ? ? <groupId>org.junit.vintage</groupId>
? ? ? ? ? ? ? ? ? ? <artifactId>junit-vintage-engine</artifactId>
? ? ? ? ? ? ? ? </exclusion>
? ? ? ? ? ? </exclusions>
? ? ? ? </dependency>
? ? </dependencies>

用戶登錄邏輯

@Component
public class SheepUserDetailsService implements UserDetailsService {

? ? @Autowired
? ? private PasswordEncoder passwordEncoder;

? ? @Override
? ? public UserDetails loadUserByUsername(String s) throws UsernameNotFoundException {

? ? ? ? if( !"admin".equals(s) )
? ? ? ? ? ? throw new UsernameNotFoundException("用戶" + s + "不存在" );

? ? ? ? return new User( s, passwordEncoder.encode("123456"), AuthorityUtils.commaSeparatedStringToAuthorityList("ROLE_NORMAL,ROLE_MEDIUM"));
? ? }
}

OAtuh2配置

配置服務中心

@Configuration
@EnableAuthorizationServer
public class AuthorizationServerConfig extends AuthorizationServerConfigurerAdapter {

? ? @Autowired
? ? AuthenticationManager authenticationManager;

? ? @Autowired
? ? SheepUserDetailsService sheepUserDetailsService;

? ? @Override
? ? public void configure(ClientDetailsServiceConfigurer clients) throws Exception {

? ? ? ? // 定義了兩個客戶端應用的通行證
? ? ? ? clients.inMemory()
? ? ? ? ? ? ? ? .withClient("admin")
? ? ? ? ? ? ? ? .secret(new BCryptPasswordEncoder().encode("123456"))
? ? ? ? ? ? ? ? .authorizedGrantTypes("authorization_code", "refresh_token","password")
? ? ? ? ? ? ? ? .scopes("all")
? ? ? ? ? ? ? ? .autoApprove(true)
? ? ? ? ? ? ? ? .redirectUris("http://192.168.216.1:8001/login","http://192.168.216.1:8004/login");

? ? }

? ? @Override
? ? public void configure(AuthorizationServerEndpointsConfigurer endpoints) throws Exception {

? ? ? ? endpoints.tokenStore(jwtTokenStore()).accessTokenConverter(jwtAccessTokenConverter());
? ? ? ? DefaultTokenServices tokenServices = (DefaultTokenServices) endpoints.getDefaultAuthorizationServerTokenServices();
? ? ? ? tokenServices.setTokenStore(endpoints.getTokenStore());
? ? ? ? tokenServices.setSupportRefreshToken(true);
? ? ? ? tokenServices.setClientDetailsService(endpoints.getClientDetailsService());
? ? ? ? tokenServices.setTokenEnhancer(endpoints.getTokenEnhancer());
? ? ? ? tokenServices.setAccessTokenValiditySeconds((int) TimeUnit.DAYS.toSeconds(1)); // 一天有效期
? ? ? ? endpoints.tokenServices(tokenServices);

? ? ? ? //密碼模式配置
? ? ? ? endpoints.authenticationManager(authenticationManager).userDetailsService(sheepUserDetailsService);
? ? }

? ? @Override
? ? public void configure(AuthorizationServerSecurityConfigurer security) throws Exception {
? ? ? ? security
? ? ? ? ? ? ? ? .tokenKeyAccess("isAuthenticated()")
? ? ? ? ? ? ? ? .checkTokenAccess("permitAll()")
? ? ? ? ? ? ? ? .allowFormAuthenticationForClients();
? ? }

? ? @Bean
? ? public TokenStore jwtTokenStore() {
? ? ? ? return new JwtTokenStore(jwtAccessTokenConverter());
? ? }

? ? @Bean
? ? public JwtAccessTokenConverter jwtAccessTokenConverter(){
? ? ? ? JwtAccessTokenConverter converter = new JwtAccessTokenConverter();
? ? ? ? converter.setSigningKey("testKey");
? ? ? ? return converter;
? ? }

}

配置規(guī)則中心

Configuration

public class SpringSecurityConfig extends WebSecurityConfigurerAdapter {


? ? @Override
? ? @Bean
? ? public AuthenticationManager authenticationManager() throws Exception {
? ? ? ? return super.authenticationManager();
? ? }

? ? @Autowired
? ? private UserDetailsService userDetailsService;

? ? @Bean
? ? public PasswordEncoder passwordEncoder() {
? ? ? ? return new BCryptPasswordEncoder();
? ? }


? ? @Autowired
? ? private CustomLogoutSuccessHandler customLogoutSuccessHandler;


? ? @Bean
? ? public DaoAuthenticationProvider authenticationProvider() {
? ? ? ? DaoAuthenticationProvider authenticationProvider = new DaoAuthenticationProvider();
? ? ? ? authenticationProvider.setUserDetailsService(userDetailsService);
? ? ? ? authenticationProvider.setPasswordEncoder(passwordEncoder());
? ? ? ? authenticationProvider.setHideUserNotFoundExceptions(false);
? ? ? ? return authenticationProvider;
? ? }

? ? @Override
? ? protected void configure(HttpSecurity http) throws Exception {
? ? ? ? http.requestMatchers().antMatchers("/oauth/**","/login/**","/logout/**","/uac/oauth/token","/remove")
? ? ? ? ? ? ? ? .and()
? ? ? ? ? ? ? ? .authorizeRequests()
? ? ? ? ? ? ? ? .antMatchers("/oauth/**").authenticated()
? ? ? ? ? ? ? ? .and()
? ? ? ? ? ? ? ? .formLogin().permitAll()
? ? ? ? ? ? ? ? .and()
? ? ? ? ? ? ? ? .logout()
? ? ? ? ? ? ? ? .logoutSuccessHandler(customLogoutSuccessHandler)
? ? ? ? ? ? ? ? // 無效會話
? ? ? ? ? ? ? ? .invalidateHttpSession(true)
? ? ? ? ? ? ? ? // 清除身份驗證
? ? ? ? ? ? ? ? .clearAuthentication(true)
? ? ? ? ? ? ? ? .permitAll();
? ? }


? ? @Override
? ? protected void configure(AuthenticationManagerBuilder auth) throws Exception {
? ? ? ? auth.authenticationProvider(authenticationProvider());
? ? }

}
@Component
public class CustomLogoutSuccessHandler extends AbstractAuthenticationTargetUrlRequestHandler implements LogoutSuccessHandler {
? ? @Override
? ? public void onLogoutSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException, ServletException {
? ? ? ? // 將子系統(tǒng)的cookie刪掉
? ? ? ? //建議將token也刪除,直接寫個controller接口就可以了,可以在前端調(diào)用/logout的同時調(diào)用刪除token接口
? ? ? ? Cookie[] cookies = request.getCookies();
? ? ? ? if(cookies != null && cookies.length>0){
? ? ? ? ? ? for (Cookie cookie : cookies){
? ? ? ? ? ? ? ? cookie.setMaxAge(0);
? ? ? ? ? ? ? ? cookie.setPath("/");
? ? ? ? ? ? ? ? response.addCookie(cookie);
? ? ? ? ? ? }
? ? ? ? }
? ? ? ? super.handle(request, response, authentication);
? ? }
}

請求模塊

下面這個是請求模塊,也就是獨立出一個微服務,假如這個微服務是做業(yè)務的,會給認證中心發(fā)出請求,然后去熱證,這個模塊也算登錄了.
那么有道友會問:其他模塊在該模塊登錄后還要登錄嗎?答案:不用!
至于要以什么為基礎(chǔ),接著往下看:

請求模塊這個依賴很關(guān)鍵

? ? ? ? <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>

這個yml也很重要

auth-server: http://localhost:8085/uac
security:
  oauth2:
    client:
      client-id: admin
      client-secret: 123456
      user-authorization-uri: ${auth-server}/oauth/authorize #認證
      access-token-uri: ${auth-server}/oauth/token #獲取token
    resource:
      jwt:
        key-uri: ${auth-server}/oauth/token_key #忘了,反正要寫上

上面的認證和獲取token這兩個配置很重要,還有一個/oauth/check_token,這個是用來檢查token是否合法的,這些都怎么用,是什么,后面會說

下面這個也很重要

@Configuration
@EnableWebSecurity
@EnableGlobalMethodSecurity(prePostEnabled = true)
@EnableOAuth2Sso
public class ClientWebsecurityConfigurer extends WebSecurityConfigurerAdapter {

? ? @Override
? ? public void configure(HttpSecurity http) throws Exception {
? ? //下面表示該模塊所有請求都要攔截
? ? //因為在yml配置了認證中心的各個路徑,所以會自動跳轉(zhuǎn)到認證中心去認證
? ? //如果你想在當前模塊排除哪些攔截,可以在下面去排除
? ? ? ? http.antMatcher("/**").authorizeRequests()
? ? ? ? ? ? ? ? .anyRequest().authenticated();
? ? }
}

真實請求

下面就可以正式去請求了,這里很多網(wǎng)友都會有疑問,就是前面我在認證中心授予了權(quán)限之后,在其他模塊該如何去權(quán)限的規(guī)定呢?其實很簡單,有很多博主都沒有說,直接加上注解就可以了.

? ? @GetMapping("/get")
? ? @PreAuthorize("hasAuthority('ROLE_NORMAL')")
? ? public String get(HttpServletRequest request){
? ? ? ? System.out.println("函數(shù)進來了");
? ? ? ? return "uusb1j";
? ? }
}

這個時候,如果該微服務的get請求過來,就會跳轉(zhuǎn)到認證中心去認證.

一些小問題

這個時候只要有相同配置的模塊都不用自行登錄了.如果有一個模塊進行登出請求,所有服務都會進行登出.

注意認證中心有項配置redirectUris(“http://192.168.216.1:8001/login”,“http://192.168.216.1:8004/login”),這個配置代表認證成功后重定向去哪個地址,但并不會真的重定向去對應模塊的login頁,而是重定向去你請求前被攔截的地址,但是這個有講究就是必須配置請求前所在模塊的地址,每個模塊對應一個重定向地址,最好是重定向到對應模塊的/login頁,其他頁也行.如果你從網(wǎng)關(guān)過來,然后你這里重定向回網(wǎng)關(guān)是不行的,除非你網(wǎng)關(guān)有相關(guān)操作,不然你網(wǎng)關(guān)只是一個轉(zhuǎn)發(fā)功能,是先轉(zhuǎn)發(fā)到對應模塊,然后發(fā)現(xiàn)該模塊的某個地址不可訪問,才去認證中心請求權(quán)限的,所以這里的重定向地址還是具體到對應模塊才對,其他不行,有多個用","隔開就行.

到此這篇關(guān)于SpringSecurity OAtu2+JWT實現(xiàn)微服務版本的單點登錄的示例的文章就介紹到這了,更多相關(guān)SpringSecurity OAtu2 JWT單點登錄內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!

相關(guān)文章

  • JAVA mongodb 聚合幾種查詢方式詳解

    JAVA mongodb 聚合幾種查詢方式詳解

    這篇文章主要介紹了JAVA mongodb 聚合幾種查詢方式詳解,小編覺得挺不錯的,現(xiàn)在分享給大家,也給大家做個參考。一起跟隨小編過來看看吧
    2018-03-03
  • GitLab+Jenkins+Maven+Tomcat?實現(xiàn)自動集成、打包、部署

    GitLab+Jenkins+Maven+Tomcat?實現(xiàn)自動集成、打包、部署

    本文主要介紹了GitLab?+?Jenkins?+?Maven?+?Tomcat?實現(xiàn)自動集成、打包、部署,文中通過示例代碼介紹的非常詳細,具有一定的參考價值,感興趣的小伙伴們可以參考一下
    2022-01-01
  • JAVA基礎(chǔ)--如何通過異常處理錯誤

    JAVA基礎(chǔ)--如何通過異常處理錯誤

    這篇文章主要介紹了JAVA中如何通過異常處理錯誤,文中講解非常細致,代碼幫助大家更好的理解,感興趣的朋友可以了解下
    2020-06-06
  • 詳解Java編程的Observer觀察者設計模式

    詳解Java編程的Observer觀察者設計模式

    這篇文章主要介紹了Java編程的Observer觀察者設計模式,觀察者模式定義了一個一對多的依賴關(guān)系,讓一個或多個觀察者對象監(jiān)察一個主題對象,需要的朋友可以參考下
    2016-01-01
  • java實現(xiàn)voctor按指定方式排序示例分享

    java實現(xiàn)voctor按指定方式排序示例分享

    這篇文章主要介紹了java實現(xiàn)voctor按指定方式排序示例,需要的朋友可以參考下
    2014-03-03
  • SpringCloud Config分布式配置中心使用教程介紹

    SpringCloud Config分布式配置中心使用教程介紹

    springcloud config是一個解決分布式系統(tǒng)的配置管理方案。它包含了 client和server兩個部分,server端提供配置文件的存儲、以接口的形式將配置文件的內(nèi)容提供出去,client端通過接口獲取數(shù)據(jù)、并依據(jù)此數(shù)據(jù)初始化自己的應用
    2022-12-12
  • 解決Springboot @Autowired 無法注入問題

    解決Springboot @Autowired 無法注入問題

    WebappApplication 一定要在包的最外層,否則Spring無法對所有的類進行托管,會造成@Autowired 無法注入。接下來給大家介紹解決Springboot @Autowired 無法注入問題,感興趣的朋友一起看看吧
    2018-08-08
  • feign的ribbon超時配置和hystrix的超時配置說明

    feign的ribbon超時配置和hystrix的超時配置說明

    這篇文章主要介紹了feign的ribbon超時配置和hystrix的超時配置說明,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧
    2020-09-09
  • Spring Boot開啟的2種方式詳解

    Spring Boot開啟的2種方式詳解

    這篇文章主要介紹了Spring Boot開啟的2種方式詳解,小編覺得挺不錯的,現(xiàn)在分享給大家,也給大家做個參考。一起跟隨小編過來看看吧
    2019-05-05
  • Spring?Boot整合Log4j2.xml的問題及解決方法

    Spring?Boot整合Log4j2.xml的問題及解決方法

    這篇文章主要介紹了Spring?Boot整合Log4j2.xml的問題,本文給大家分享解決方案,需要的朋友可以參考下
    2023-09-09

最新評論

抚州市| 墨脱县| 霸州市| 武川县| 夹江县| 襄樊市| 湖口县| 祥云县| 石河子市| 安塞县| 洞口县| 同仁县| 东明县| 股票| 勐海县| 洪江市| 华宁县| 张家川| 固镇县| 遂宁市| 柳江县| 海南省| 丰顺县| 渝北区| 南木林县| 绵阳市| 那曲县| 新和县| 裕民县| 延津县| 陈巴尔虎旗| 清水河县| 巴里| 东源县| 灵宝市| 衡东县| 阿荣旗| 太康县| 渭源县| 肇东市| 望谟县|