溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點擊 登錄注冊 即表示同意《億速云用戶服務條款》

基于SpringBoot整合oauth2實現(xiàn)token認證

發(fā)布時間:2020-09-14 10:56:06 來源:腳本之家 閱讀:193 作者:炫舞風中 欄目:編程語言

這篇文章主要介紹了基于SpringBoot整合oauth3實現(xiàn)token 認證,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友可以參考下

session和token的區(qū)別:

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

Oauth3 密碼授權流程

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

基于SpringBoot整合oauth2實現(xiàn)token認證

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)認證第一步

MyUserDetailsService.java

@Autowired
  private PasswordEncoder passwordEncoder;

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

3. 獲取token的控制器

@RestController
public 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);
    //進行驗證
    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、密碼進行登錄
    UsernamePasswordAuthenticationToken authentication = new UsernamePasswordAuthenticationToken(username, password);
    //調(diào)用指定的UserDetailsService,進行用戶名密碼驗證
    Authentication authenticate = authenticationManager.authenticate(authentication);
    HrUtils.setCurrentUser(authenticate);
    //放到session中
    //密碼授權 模式, 組建 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需要認證、注入登錄失敗/成功過濾器

@Configuration
public 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()
        //請求授權
        .authorizeRequests()
        //不需要權限認證的url
        .antMatchers("/oauth/*","/authentication/*","/code/image").permitAll()
        //任何請求
        .anyRequest()
        //需要身份認證
        .authenticated()
        .and()
        //關閉跨站請求防護
        .csrf().disable();
    //默認注銷地址:/logout
    http.logout().
        //注銷之后 跳轉的頁面
        logoutSuccessUrl("/authentication/require");
  }

  /**
   * 認證管理
   *
   * @return 認證管理對象
   * @throws Exception 認證異常信息
   */
  @Override
  @Bean
  public AuthenticationManager authenticationManagerBean() throws Exception {
    return super.authenticationManagerBean();
  }
}

(2)、認證服務器

@Configuration
@EnableAuthorizationServer
public 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)
        //密碼授權模式和刷新令牌
        .authorizedGrantTypes("refresh_token","password")
        .scopes( "all");
  }

  @Override
  public void configure(AuthorizationServerEndpointsConfigurer endpoints) throws Exception {
    endpoints
        .authenticationManager(authenticationManager)
        .userDetailsService(userDetailsService);
  }
}

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

5、測試

基于SpringBoot整合oauth2實現(xiàn)token認證

以上就是本文的全部內(nèi)容,希望對大家的學習有所幫助,也希望大家多多支持億速云。

向AI問一下細節(jié)

免責聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉載和分享為主,文章觀點不代表本網(wǎng)站立場,如果涉及侵權請聯(lián)系站長郵箱:is@yisu.com進行舉報,并提供相關證據(jù),一經(jīng)查實,將立刻刪除涉嫌侵權內(nèi)容。

AI