欧美一级特黄大片做受成人-亚洲成人一区二区电影-激情熟女一区二区三区-日韩专区欧美专区国产专区

SpringBoot中怎么通過整合oauth2實現(xiàn)token認(rèn)證

SpringBoot中怎么通過整合oauth2實現(xiàn)token認(rèn)證,針對這個問題,這篇文章詳細(xì)介紹了相對應(yīng)的分析和解答,希望可以幫助更多想解決這個問題的小伙伴找到更簡單易行的方法。

目前成都創(chuàng)新互聯(lián)已為成百上千家的企業(yè)提供了網(wǎng)站建設(shè)、域名、雅安服務(wù)器托管、網(wǎng)站托管、企業(yè)網(wǎng)站設(shè)計、永定網(wǎng)站維護(hù)等服務(wù),公司將堅持客戶導(dǎo)向、應(yīng)用為本的策略,正道將秉承"和諧、參與、激情"的文化,與客戶和合作伙伴齊心協(xié)力一起成長,共同發(fā)展。

session和token的區(qū)別:

session是空間換時間,而token是時間換空間。session占用空間,但是可以管理過期時間,token管理部了過期時間,但是不占用空間.sessionId失效問題和token內(nèi)包含。session基于cookie,app請求并沒有cookie 。token更加安全(每次請求都需要帶上)

Oauth3 密碼授權(quán)流程

在oauth3協(xié)議里,每一個應(yīng)用都有自己的一個clientId和clientSecret(需要去認(rèn)證方申請),所以一旦想通過認(rèn)證,必須要有認(rèn)證方下發(fā)的clientId和secret。

1. pom

<!--security-->    <dependency>      <groupId>org.springframework.boot</groupId>      <artifactId>spring-boot-starter-security</artifactId>    </dependency>    <dependency>      <groupId>org.springframework.security.oauth</groupId>      <artifactId>spring-security-oauth3</artifactId>    </dependency>

2. UserDetail實現(xiàn)認(rèn)證第一步

MyUserDetailsService.java

@Autowired  private PasswordEncoder passwordEncoder;  /**   * 根據(jù)進(jìn)行登錄   * @param username   * @return   * @throws UsernameNotFoundException   */  @Override  public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {    log.info("登錄用戶名:"+username);    String password = passwordEncoder.encode("123456");    //User三個參數(shù)  (用戶名+密碼+權(quán)限)    //根據(jù)查找到的用戶信息判斷用戶是否被凍結(jié)    log.info("數(shù)據(jù)庫密碼:"+password);    return new User(username,password, AuthorityUtils.commaSeparatedStringToAuthorityList("admin"));  }

3. 獲取token的控制器

@RestControllerpublic class OauthController {  @Autowired  private ClientDetailsService clientDetailsService;  @Autowired  private AuthorizationServerTokenServices authorizationServerTokenServices;  @Autowired  private AuthenticationManager authenticationManager;  @PostMapping("/oauth/getToken")  public Object getToken(@RequestParam String username, @RequestParam String password, HttpServletRequest request) throws IOException {    Map<String,Object>map = new HashMap<>(8);    //進(jìn)行驗證    String header = request.getHeader("Authorization");    if (header == null && !header.startsWith("Basic")) {      map.put("code",500);      map.put("message","請求投中無client信息");      return map;    }    String[] tokens = this.extractAndDecodeHeader(header, request);    assert tokens.length == 2;    //獲取clientId 和 clientSecret    String clientId = tokens[0];    String clientSecret = tokens[1];    //獲取 ClientDetails    ClientDetails clientDetails = clientDetailsService.loadClientByClientId(clientId);    if (clientDetails == null){      map.put("code",500);      map.put("message","clientId 不存在"+clientId);      return map;      //判斷 方言 是否一致    }else if (!StringUtils.equals(clientDetails.getClientSecret(),clientSecret)){      map.put("code",500);      map.put("message","clientSecret 不匹配"+clientId);      return map;    }    //使用username、密碼進(jìn)行登錄    UsernamePasswordAuthenticationToken authentication = new UsernamePasswordAuthenticationToken(username, password);    //調(diào)用指定的UserDetailsService,進(jìn)行用戶名密碼驗證    Authentication authenticate = authenticationManager.authenticate(authentication);    HrUtils.setCurrentUser(authenticate);    //放到session中    //密碼授權(quán) 模式, 組建 authentication    TokenRequest tokenRequest = new TokenRequest(new HashMap<>(),clientId,clientDetails.getScope(),"password");    OAuth3Request oAuth3Request = tokenRequest.createOAuth3Request(clientDetails);    OAuth3Authentication oAuth3Authentication = new OAuth3Authentication(oAuth3Request,authentication);    OAuth3AccessToken token = authorizationServerTokenServices.createAccessToken(oAuth3Authentication);    map.put("code",200);    map.put("token",token.getValue());    map.put("refreshToken",token.getRefreshToken());    return map;  }  /**   * 解碼請求頭   */  private String[] extractAndDecodeHeader(String header, HttpServletRequest request) throws IOException {    byte[] base64Token = header.substring(6).getBytes("UTF-8");    byte[] decoded;    try {      decoded = Base64.decode(base64Token);    } catch (IllegalArgumentException var7) {      throw new BadCredentialsException("Failed to decode basic authentication token");    }    String token = new String(decoded, "UTF-8");    int delim = token.indexOf(":");    if (delim == -1) {      throw new BadCredentialsException("Invalid basic authentication token");    } else {      return new String[]{token.substring(0, delim), token.substring(delim + 1)};    }  }}

4. 核心配置

(1)、Security 配置類 說明登錄方式、登錄頁面、哪個url需要認(rèn)證、注入登錄失敗/成功過濾器

@Configurationpublic class BrowserSecurityConfig extends WebSecurityConfigurerAdapter {  /**   * 注入 自定義的 登錄成功處理類   */  @Autowired  private MyAuthenticationSuccessHandler mySuccessHandler;  /**   * 注入 自定義的 登錄失敗處理類   */  @Autowired  private MyAuthenticationFailHandler myFailHandler;  @Autowired  private ValidateCodeFilter validateCodeFilter;  /**   * 重寫PasswordEncoder 接口中的方法,實例化加密策略   * @return 返回 BCrypt 加密策略   */  @Bean  public PasswordEncoder passwordEncoder(){    return new BCryptPasswordEncoder();  }  @Override  protected void configure(HttpSecurity http) throws Exception {    //在UsernamePasswordAuthenticationFilter 過濾器前 加一個過濾器 來搞驗證碼    http.addFilterBefore(validateCodeFilter, UsernamePasswordAuthenticationFilter.class)        //表單登錄 方式        .formLogin()        .loginPage("/authentication/require")        //登錄需要經(jīng)過的url請求        .loginProcessingUrl("/authentication/form")        .passwordParameter("pwd")        .usernameParameter("user")        .successHandler(mySuccessHandler)        .failureHandler(myFailHandler)        .and()        //請求授權(quán)        .authorizeRequests()        //不需要權(quán)限認(rèn)證的url        .antMatchers("/oauth/*","/authentication/*","/code/image").permitAll()        //任何請求        .anyRequest()        //需要身份認(rèn)證        .authenticated()        .and()        //關(guān)閉跨站請求防護(hù)        .csrf().disable();    //默認(rèn)注銷地址:/logout    http.logout().        //注銷之后 跳轉(zhuǎn)的頁面        logoutSuccessUrl("/authentication/require");  }  /**   * 認(rèn)證管理   *   * @return 認(rèn)證管理對象   * @throws Exception 認(rèn)證異常信息   */  @Override  @Bean  public AuthenticationManager authenticationManagerBean() throws Exception {    return super.authenticationManagerBean();  }}

(2)、認(rèn)證服務(wù)器

@Configuration@EnableAuthorizationServerpublic class MyAuthorizationServerConfig extends AuthorizationServerConfigurerAdapter {  @Autowired  private AuthenticationManager authenticationManager;  @Autowired  private MyUserDetailsService userDetailsService;  @Override  public void configure(AuthorizationServerSecurityConfigurer security) throws Exception {    super.configure(security);  }  /**   * 客戶端配置(給誰發(fā)令牌)   * @param clients   * @throws Exception   */  @Override  public void configure(ClientDetailsServiceConfigurer clients) throws Exception {    clients.inMemory().withClient("internet_plus")        .secret("internet_plus")        //有效時間 2小時        .accessTokenValiditySeconds(72000)        //密碼授權(quán)模式和刷新令牌        .authorizedGrantTypes("refresh_token","password")        .scopes( "all");  }  @Override  public void configure(AuthorizationServerEndpointsConfigurer endpoints) throws Exception {    endpoints        .authenticationManager(authenticationManager)        .userDetailsService(userDetailsService);  }}

@EnableResourceServer這個注解就決定了這是個資源服務(wù)器。它決定了哪些資源需要什么樣的權(quán)限。

關(guān)于SpringBoot中怎么通過整合oauth2實現(xiàn)token認(rèn)證問題的解答就分享到這里了,希望以上內(nèi)容可以對大家有一定的幫助,如果你還有很多疑惑沒有解開,可以關(guān)注創(chuàng)新互聯(lián)行業(yè)資訊頻道了解更多相關(guān)知識。

新聞名稱:SpringBoot中怎么通過整合oauth2實現(xiàn)token認(rèn)證
URL標(biāo)題:http://aaarwkj.com/article32/igjepc.html

成都網(wǎng)站建設(shè)公司_創(chuàng)新互聯(lián),為您提供商城網(wǎng)站、網(wǎng)站設(shè)計公司ChatGPT、外貿(mào)建站、網(wǎng)站維護(hù)、App設(shè)計

廣告

聲明:本網(wǎng)站發(fā)布的內(nèi)容(圖片、視頻和文字)以用戶投稿、用戶轉(zhuǎn)載內(nèi)容為主,如果涉及侵權(quán)請盡快告知,我們將會在第一時間刪除。文章觀點不代表本網(wǎng)站立場,如需處理請聯(lián)系客服。電話:028-86922220;郵箱:631063699@qq.com。內(nèi)容未經(jīng)允許不得轉(zhuǎn)載,或轉(zhuǎn)載時需注明來源: 創(chuàng)新互聯(lián)

成都seo排名網(wǎng)站優(yōu)化
精品人妻日韩中文字幕| 国产成人亚洲精品午夜国产馆| 三级日本午夜在线观看| av中文字幕一二三区| 国产精品一区二区激情视频| 免费观看日本成人午夜大片 | 日本一区二区三区免费精品| 最近免费欧美一级黄片| 偷拍视频一区二区三区| 成人亚洲理论片在线观看| 国产成人大片一区二区三区 | 亚洲精品伦理视频在线| 久久精品噜噜噜成人av农村| 中文字幕日韩手机在线| 亚洲av成人在线观看| 亚洲视频在线的视频在| 九九在线视频免费观看精彩| 国产91在线一区精品| 精品爆白浆一区二区三区| 国产又粗又长又大又长| 深夜毛片一区二区三区| 亚洲日本在线观看一区| 欧美日韩国产91在线| 夜夜草视频在线免费观看| 黄色日韩欧美在线观看| 另类视频网站在线观看| 亚洲精品成人午夜av| 传媒视频在线免费观看| 中文字幕国产精品专区| 这里只有精品国产999| 日韩在线不卡视频一区 | 天天干天天干夜夜操| 91精品国产综合久久麻豆| 亚洲国产精品中文字幕久久| 国产日韩亚洲欧美精品专区| 精品国产av一区二区三广区| 亚洲国产精品青青草| av黄色资源在线观看| 亚洲中文字幕av天堂久久| 国产免费av剧情演绎| 亚洲中文无码亚洲人vr在线|