spring oauth2 自定义granter

spring oauth2

支持用户名密码登录,但是难免要接入微信登录啊短信登录啊这些乱七八糟的登录方式。之前用那种filter的方式,不是那么好看!所以改用这种自定义granter的方式。

这样做

  1. 新建CaptchaTokenGranter 继承 AbstractTokenGranter

  2. 重写getOAuth2Authentication 方法

  3. 1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    //..。各种判断
    Authentication userAuth = new UsernamePasswordAuthenticationToken(username, password);
    ((AbstractAuthenticationToken) userAuth).setDetails(parameters);
    try {
    userAuth = authenticationManager.authenticate(userAuth);
    }
    catch (AccountStatusException | BadCredentialsException ase) {
    //covers expired, locked, disabled cases (mentioned in section 5.2, draft 31)
    throw new InvalidGrantException(ase.getMessage());
    }
    // If the username/password are wrong the spec says we should send 400/invalid grant

    if (userAuth == null || !userAuth.isAuthenticated()) {
    throw new InvalidGrantException("Could not authenticate user: " + username);
    }
    OAuth2Request storedOAuth2Request = getRequestFactory().createOAuth2Request(client, tokenRequest);
    return new OAuth2Authentication(storedOAuth2Request, userAuth);
  4. AuthorizationServerConfigurerAdapter 的配置中

    1
    2
    3
    4
    5
    6
    configure(AuthorizationServerEndpointsConfigurer endpoints) //这个配置方法

    List<TokenGranter> granters = new ArrayList<>(Collections.singletonList(endpoints.getTokenGranter()));
    granters.add(new CaptchaTokenGranter(...));
    //把granter添加进去
    endpoints.tokenGranter(new CompositeTokenGranter(granters));
  5. oauth_client_details别忘了加上你自定义的grant_type!

  6. 去登录,grant_type写成你自定义的,参数就是你自己定的那些

🐩这边没看懂的,到这里看