spring-security實現的token受權

在個人用戶密碼受權文章裏介紹了spring-security的工做過程,不瞭解的同窗,能夠先看看用戶密碼受權這篇文章,在
用戶密碼受權模式裏,主要是經過一個登錄頁進行受權,而後把受權對象寫到session裏,它主要用在mvc框架裏,而對於webapi來講,通常不會採用這種方式,對於webapi
來講,通常會用jwt受權方式,就是token受權碼的方式,每訪問api接口時,在http頭上帶着你的token碼,而大叔本身也寫了一個簡單的jwt受權模式,下面介紹一下。web

WebSecurityConfig受權配置

@Configuration
@EnableWebSecurity
@EnableGlobalMethodSecurity(prePostEnabled = true)
public class TokenWebSecurityConfig extends WebSecurityConfigurerAdapter {
  /**
   * token過濾器.
   */
  @Autowired
  LindTokenAuthenticationFilter lindTokenAuthenticationFilter;

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

  @Override
  protected void configure(HttpSecurity httpSecurity) throws Exception {
    httpSecurity
        .csrf().disable()
        // 基於token,因此不須要session
        .sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS).and()
        .authorizeRequests()
        // 對於獲取token的rest api要容許匿名訪問
        .antMatchers("/lind-auth/**").permitAll()
        // 除上面外的全部請求所有須要鑑權認證
        .anyRequest().authenticated();
    httpSecurity
        .addFilterBefore(lindTokenAuthenticationFilter, UsernamePasswordAuthenticationFilter.class);
    // 禁用緩存
    httpSecurity.headers().cacheControl();
  }

  /**
   * 密碼生成策略.
   *
   * @return
   */
  @Bean
  public PasswordEncoder passwordEncoder() {
    return new BCryptPasswordEncoder();
  }
}

受權接口login

對外開放的,須要提供用戶名和密碼爲參數進行登錄,而後返回token碼,固然也可使用手機號和驗證碼登錄,受權邏輯是同樣的,獲取用戶信息都是使用UserDetailsService,
而後開發人員根據本身的業務去重寫loadUserByUsername來獲取用戶實體。redis

用戶登錄成功後,爲它受權及認證,這一步咱們會在redis裏創建token與用戶名的關係。spring

@GetMapping(LOGIN)
  public ResponseEntity<?> refreshAndGetAuthenticationToken(
      @RequestParam String username,
      @RequestParam String password) throws AuthenticationException {
    return ResponseEntity.ok(generateToken(username, password));
  }

  /**
   * 登錄與受權.
   *
   * @param username .
   * @param password .
   * @return
   */
  private String generateToken(String username, String password) {
    UsernamePasswordAuthenticationToken upToken = new UsernamePasswordAuthenticationToken(username, password);
    // Perform the security
    final Authentication authentication = authenticationManager.authenticate(upToken);
    SecurityContextHolder.getContext().setAuthentication(authentication);
    // Reload password post-security so we can generate token
    final UserDetails userDetails = userDetailsService.loadUserByUsername(username);
    // 持久化的redis
    String token = CommonUtils.encrypt(userDetails.getUsername());
    redisTemplate.opsForValue().set(token, userDetails.getUsername());
    return token;
  }

LindTokenAuthenticationFilter代碼

主要實現了對請求的攔截,獲取http頭上的Authorization元素,token碼就在這個鍵裏,咱們的token都是採用通用的Bearer開頭,當你的token沒有過時時,會
存儲在redis裏,key就是用戶名的md5碼,而value就是用戶名,當拿到token以後去數據庫或者緩存裏拿用戶信息進行受權便可。數據庫

/**
 * token filter bean.
 */
@Component
public class LindTokenAuthenticationFilter extends OncePerRequestFilter {

  @Autowired
  RedisTemplate<String, String> redisTemplate;
  String tokenHead = "Bearer ";
  String tokenHeader = "Authorization";
  @Autowired
  private UserDetailsService userDetailsService;

  /**
   * token filter.
   *
   * @param request     .
   * @param response    .
   * @param filterChain .
   */
  @Override
  protected void doFilterInternal(
      HttpServletRequest request,
      HttpServletResponse response,
      FilterChain filterChain) throws ServletException, IOException {

    String authHeader = request.getHeader(this.tokenHeader);
    if (authHeader != null && authHeader.startsWith(tokenHead)) {
      final String authToken = authHeader.substring(tokenHead.length()); // The part after "Bearer "
      if (authToken != null && redisTemplate.hasKey(authToken)) {
        String username = redisTemplate.opsForValue().get(authToken);
        if (username != null && SecurityContextHolder.getContext().getAuthentication() == null) {
          UserDetails userDetails = this.userDetailsService.loadUserByUsername(username);
          //能夠校驗token和username是否有效,目前因爲token對應username存在redis,都以默認都是有效的
          UsernamePasswordAuthenticationToken authentication = new UsernamePasswordAuthenticationToken(
              userDetails, null, userDetails.getAuthorities());
          authentication.setDetails(new WebAuthenticationDetailsSource().buildDetails(
              request));
          logger.info("authenticated user " + username + ", setting security context");
          SecurityContextHolder.getContext().setAuthentication(authentication);
        }
      }
    }

    filterChain.doFilter(request, response);

  }

測試token受權

get:http://localhost:8080/lind-demo/login?username=admin&password=123

post:http://localhost:8080/lind-demo/user/add
Content-Type:application/json
Authorization:Bearer 21232F297A57A5A743894A0E4A801FC3
相關文章
相關標籤/搜索