spring boot oauth2 支持不同登录类型 自定义token信息返回

近期在项目需求上需要用到不同的用户类型,并且不同的用户,check_token 返回的信息也需要不一样

在这里例子发上来,希望能够帮到别人,同时也给自己留个记录

首先,先添加依赖

    <dependencyManagement>
        <dependencies>
            <dependency>
                <groupId>org.springframework.cloud</groupId>
                <artifactId>spring-cloud-dependencies</artifactId>
                <version>${spring-cloud.version}</version>
                <type>pom</type>
                <scope>import</scope>
            </dependency>
        </dependencies>
    </dependencyManagement>
        <properties>
            <java.version>1.8</java.version>
            <spring-cloud.version>Hoxton.SR8</spring-cloud.version>
        </properties>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-security</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-oauth2</artifactId>
        </dependency>
        <dependency>
            <groupId>org.apache.tomcat.embed</groupId>
            <artifactId>tomcat-embed-core</artifactId>
            <version>9.0.45</version>
            <scope>provided</scope>
        </dependency>

使用mysql来保存客户端信息,加入mysql依赖

        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-jdbc</artifactId>
        </dependency>
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>druid-spring-boot-starter</artifactId>
            <version>1.1.13</version>
        </dependency>
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
        </dependency>

application.properties

server.port=8080

#datasource config
spring.datasource.url=jdbc:mysql://localhost:3306/oauth_test?useUnicode=true&characterEncoding=utf8
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
spring.datasource.username=root
spring.datasource.password=

step1.新建一个CustomUser,在User的基础上添加用户类型信息

这里主要是为了让后续流程可以获取到userType的值

public class CustomUser extends User {

    private String userType;

    public CustomUser(String username, String password, String userType, Collection<? extends GrantedAuthority> authorities) {
        super(username, password, authorities);
        this.userType = userType;
    }

    public String getUserType() {
        return userType;
    }

    public CustomUser withUserType(String userType) {
        this.userType = userType;
        return this;
    }
}

 

step2.添加一个CustomUserDetailsService,并添加一个带有用户名,用户类型的方法

public class CustomUserDetailsService implements UserDetailsService {

    @Override
    public UserDetails loadUserByUsername(String username) {
        return new User(username, null, null);
    }

    public UserDetails loadUserByUsername(String username, String userType) {

        // TODO: 2021/5/12  由于合理只是测试,所以无论传入什么用户名,只要密码是123456,都能过
        
        //獲取該用戶的密碼(测试密码)
        String password = "$2a$10$u2.TGFJuzx13g1lDXoy.KeUQU8s6/HoqTaHCqWMV8/eeyLUEyYs9W";

        //獲取該用戶的權限資料(测试权限资料)
        List<String> authorityStrList = new ArrayList<>();
        authorityStrList.add("authorityTest");

        List<SimpleGrantedAuthority> authorities =new ArrayList<>();
        Optional.ofNullable(authorityStrList).orElse(new ArrayList<>()).forEach(authorityStr->{
            authorities.add(new SimpleGrantedAuthority(authorityStr));
        });

        return new CustomUser(username, password, userType, authorities);
    }
}

step3.自定义WebAuthenticationDetails 

当授权类型为授权码模式时,需要使用。

public class CustomWebAuthenticationDetails  extends WebAuthenticationDetails {

    private final String userType;

    public CustomWebAuthenticationDetails(HttpServletRequest request) {
        super(request);
        userType = request.getParameter("userType");
    }

    public String getUserType() {
        return userType;
    }
}

 

step4.自定义AbstractUserDetailsAuthenticationProvider 

         由于需要在授权的过程中使用我们新添加的方法UserDetails loadUserByUsername(String username, String userType),所以需要自定义AbstractUserDetailsAuthenticationProvider ,并重写UserDetails retrieveUser(String username,                                          UsernamePasswordAuthenticationToken authentication)

public class CustomUserDetailsAuthenticationProvider extends AbstractUserDetailsAuthenticationProvider {

    private static final String USER_NOT_FOUND_PASSWORD = "userNotFoundPassword";

    private PasswordEncoder passwordEncoder;

    private volatile String userNotFoundEncodedPassword;

    private CustomUserDetailsService userDetailsService;

    private UserDetailsPasswordService userDetailsPasswordService;

    public CustomUserDetailsAuthenticationProvider() {
        setPasswordEncoder(PasswordEncoderFactories.createDelegatingPasswordEncoder());
    }

    protected void additionalAuthenticationChecks(UserDetails userDetails,
                                                  UsernamePasswordAuthenticationToken authentication)
            throws AuthenticationException {
        if (authentication.getCredentials() == null) {
            logger.debug("Authentication failed: no credentials provided");

            throw new BadCredentialsException(messages.getMessage(
                    "AbstractUserDetailsAuthenticationProvider.badCredentials",
                    "Bad credentials"));
        }

        String presentedPassword = authentication.getCredentials().toString();

        if (!passwordEncoder.matches(presentedPassword, userDetails.getPassword())) {
            logger.debug("Authentication failed: password does not match stored value");

            throw new BadCredentialsException(messages.getMessage(
                    "AbstractUserDetailsAuthenticationProvider.badCredentials",
                    "Bad credentials"));
        }
    }

    protected void doAfterPropertiesSet() {
        Assert.notNull(this.userDetailsService, "A UserDetailsService must be set");
    }

    protected final UserDetails retrieveUser(String username,
                                             UsernamePasswordAuthenticationToken authentication)
            throws AuthenticationException {
        prepareTimingAttackProtection();

        try {
            String userType = "";

            //獲取用戶類型
            if (authentication.getDetails() instanceof LinkedHashMap) {
            //
                Map<String, String> map = (Map<String, String>) authentication.getDetails();
                userType = map.get("userType");
            } else if (authentication.getDetails() instanceof WebAuthenticationDetails) {
                 //grant_type=code时
                 CustomWebAuthenticationDetails webAuthenticationDetails = (CustomWebAuthenticationDetails) authentication.getDetails();
                userType = webAuthenticationDetails.getUserType();
            }

            UserDetails loadedUser = this.getUserDetailsService().loadUserByUsername(username, userType);

            if (loadedUser == null) {
                throw new InternalAuthenticationServiceException(
                        "UserDetailsService returned null, which is an interface contract violation");
            }
            return loadedUser;
        } catch (UsernameNotFoundException ex) {
            mitigateAgainstTimingAttack(authentication);
            throw ex;
        } catch (InternalAuthenticationServiceException ex) {
            throw ex;
        } catch (Exception ex) {
            throw new InternalAuthenticationServiceException(ex.getMessage(), ex);
        }
    }

    @Override
    protected Authentication createSuccessAuthentication(Object principal, Authentication authentication, UserDetails user) {
        boolean upgradeEncoding = this.userDetailsPasswordService != null
                && this.passwordEncoder.upgradeEncoding(user.getPassword());
        if (upgradeEncoding) {
            String presentedPassword = authentication.getCredentials().toString();
            String newPassword = this.passwordEncoder.encode(presentedPassword);
            user = this.userDetailsPasswordService.updatePassword(user, newPassword);
        }

        return super.createSuccessAuthentication(principal, authentication, user);
    }

    private void prepareTimingAttackProtection() {
        if (this.userNotFoundEncodedPassword == null) {
            this.userNotFoundEncodedPassword = this.passwordEncoder.encode(USER_NOT_FOUND_PASSWORD);
        }
    }

    private void mitigateAgainstTimingAttack(UsernamePasswordAuthenticationToken authentication) {
        if (authentication.getCredentials() != null) {
            String presentedPassword = authentication.getCredentials().toString();
            this.passwordEncoder.matches(presentedPassword, this.userNotFoundEncodedPassword);
        }
    }

    public void setPasswordEncoder(PasswordEncoder passwordEncoder) {
        Assert.notNull(passwordEncoder, "passwordEncoder cannot be null");
        this.passwordEncoder = passwordEncoder;
        this.userNotFoundEncodedPassword = null;
    }

    protected PasswordEncoder getPasswordEncoder() {
        return passwordEncoder;
    }

    public void setUserDetailsService(CustomUserDetailsService userDetailsService) {
        this.userDetailsService = userDetailsService;
    }

    protected CustomUserDetailsService getUserDetailsService() {
        return userDetailsService;
    }

    public void setUserDetailsPasswordService(
            UserDetailsPasswordService userDetailsPasswordService) {
        this.userDetailsPasswordService = userDetailsPasswordService;
    }
}

 

step5.自定义TokenStore,用于根据用户类型不同查询用户,并把用户信息一并存入token中

这里例子使用InMemoryTokenStore

public interface CustomTokenStore extends TokenStore {

    Map<String, Object> readUserInfo(String tokenValue);

}
public class CustomInMemoryTokenStore extends InMemoryTokenStore implements CustomTokenStore {

    private final ConcurrentHashMap<String, Map<String, Object>> userInfoStore = new ConcurrentHashMap();

    @Override
    public void storeAccessToken(OAuth2AccessToken token, OAuth2Authentication authentication) {

        super.storeAccessToken(token, authentication);

        CustomUser map = (CustomUser) authentication.getUserAuthentication().getPrincipal();
        String userType = map.getUserType();
        String username = map.getUsername();

        Map<String, Object> userInfo = new HashMap<>();
        userInfo.put("userDetails", "testUserDetailInfo");
        userInfoStore.put(token.getValue(), userInfo);
    }

    @Override
    public Map<String, Object> readUserInfo(String token) {
        return this.userInfoStore.get(token);
    }

    @Override
    public void removeAccessToken(OAuth2AccessToken accessToken) {

        super.removeAccessToken(accessToken);

        userInfoStore.remove(accessToken.getValue());
    }

    @Override
    public void removeAccessToken(String tokenValue) {

        super.removeAccessToken(tokenValue);

        userInfoStore.remove(tokenValue);
    }
}
public class CustomAccessTokenConverter extends DefaultAccessTokenConverter {

    private CustomTokenStore customTokenStore;

    public CustomAccessTokenConverter(CustomTokenStore customTokenStore) {
        this.customTokenStore = customTokenStore;
    }

    /**
     * 將額外信息(用戶信息)添加到token中
     *
     * @return
     */
    @Override
    public Map<String, ?> convertAccessToken(OAuth2AccessToken token, OAuth2Authentication authentication) {

        DefaultOAuth2AccessToken defaultOAuth2AccessToken = new DefaultOAuth2AccessToken(token);

        defaultOAuth2AccessToken.setAdditionalInformation(customTokenStore.readUserInfo(token.getValue()));

        Map<String, ?> response = super.convertAccessToken(defaultOAuth2AccessToken, authentication);

        return response;
    }
}

 

step6.配置

@Configuration
@EnableAuthorizationServer
public class OAuth2ServerConfig extends AuthorizationServerConfigurerAdapter {

    @Autowired
    private AuthenticationManager authenticationManager;

    @Autowired
    private DataSource dataSource;

    @Autowired
    private CustomTokenStore customTokenStore;

    @Override
    public void configure(AuthorizationServerSecurityConfigurer oauthServer) {
        oauthServer.realm("oauth2-resources").tokenKeyAccess("permitAll()").checkTokenAccess("permitAll()")
                .allowFormAuthenticationForClients();
    }

    @Override
    public void configure(AuthorizationServerEndpointsConfigurer endpoints) {
        endpoints.authenticationManager(authenticationManager)
                .allowedTokenEndpointRequestMethods(HttpMethod.GET, HttpMethod.POST)
                .accessTokenConverter(new CustomAccessTokenConverter(customTokenStore))
                .tokenStore(customTokenStore);
    }

    @Override
    public void configure(ClientDetailsServiceConfigurer clients) throws Exception {
        clients.jdbc(dataSource);
    }

}
@Component
@EnableGlobalMethodSecurity(prePostEnabled = true)
@EnableWebSecurity
public class SecurityConfiguration extends WebSecurityConfigurerAdapter {
    
    @Autowired
    private AuthenticationProvider authenticationProvider;

    @Autowired
    private CustomUserDetailsService customUserDetailsService;

    @Override
    public void configure(HttpSecurity http) throws Exception {
        http.csrf().disable();
        http.requestMatchers().antMatchers("/oauth/**", "/login/**", "/logout/**")
                .and().authorizeRequests().antMatchers("/oauth/**").authenticated()
                .and().formLogin().permitAll();
    }

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

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

    @Override
    protected CustomUserDetailsService userDetailsService() {
        return customUserDetailsService;
    }

}

 

@Configuration
public class CustomServiceConfiguration {

    @Bean
    public CustomTokenStore customInMemoryTokenStore(DataSource dataSource) {
        return new CustomInMemoryTokenStore();
    }

    @Bean
    public AuthenticationProvider customAuthenticationProvider(CustomUserDetailsService customUserDetailsService) {
        CustomUserDetailsAuthenticationProvider tmacsUserDetailsAuthenticationProvider = new CustomUserDetailsAuthenticationProvider();
        tmacsUserDetailsAuthenticationProvider.setUserDetailsService(customUserDetailsService);
        tmacsUserDetailsAuthenticationProvider.setHideUserNotFoundExceptions(false);
        tmacsUserDetailsAuthenticationProvider.setPasswordEncoder(this.passwordEncoder());
        return tmacsUserDetailsAuthenticationProvider;
    }

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

    @Bean
    public CustomUserDetailsService customUserDetailsService() {
        return new CustomUserDetailsService();
    }
}

 

step6.测试

获取token

http://127.0.0.1:8080/oauth/token?client_id=demoApp&client_secret=123456&username=test&password=123456&grant_type=password&userType=1

Response Body

{
    "access_token": "9eb80e8d-50db-450e-a980-4887b5cb15a6",
    "token_type": "bearer",
    "refresh_token": "21dc5b10-261b-4fa8-9bb4-c43c9d9338bc",
    "expires_in": 3571,
    "scope": "all"
}

获取用户信息

http://127.0.0.1:8080/oauth/check_token?token=9eb80e8d-50db-450e-a980-4887b5cb15a6

{
    "aud": [
        "oauth2-resource"
    ],
    "user_name": "test",
    "scope": [
        "all"
    ],
    "active": true,
    "exp": 1620786779,
    "userDetails": "testUserDetailInfo",
    "authorities": [
        "authorityTest"
    ],
    "client_id": "demoApp"
}

 

相关源码可参照《spring oauth 多用户类型登录 例子

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Spring Boot 中使用 OAuth2 时,默认情况下,访问 /oauth/token 端点会返回以下参数: access_token: 访问令牌 token_type: 令牌类型 expires_in: 令牌过期时间 scope: 令牌范围 如果你希望自定义 /oauth/token 端点的返回格式,你可以通过实现 TokenEndpoint 类并重写 postAccessToken() 方法来实现。 这是一个示例实现: ```java @Component public class CustomTokenEndpoint extends TokenEndpoint { @Override public ResponseEntity<OAuth2AccessToken> postAccessToken(Principal principal, @RequestParam Map<String, String> parameters) throws HttpRequestMethodNotSupportedException { // 调用父类的 postAccessToken() 方法获取 OAuth2AccessToken 对象 ResponseEntity<OAuth2AccessToken> tokenResponse = super.postAccessToken(principal, parameters); // 从 OAuth2AccessToken 对象中获取访问令牌 OAuth2AccessToken accessToken = tokenResponse.getBody(); // 创建一个新的响应实体,并使用自定义的响应参数格式返回 Map<String, Object> responseBody = new LinkedHashMap<>(); responseBody.put("access_token", accessToken.getValue()); responseBody.put("token_type", accessToken.getTokenType()); responseBody.put("expires_in", accessToken.getExpiresIn()); responseBody.put("scope", accessToken.getScope()); // 将自定义的响应参数封装到新的响应实体中返回 return new ResponseEntity<>(responseBody, HttpStatus.OK); } } ``` 在上面的代码中,我们通过调用父类的 postAccessToken() 方法获取到了 OAuth2AccessToken 对象,然后从中获取了访问令牌、令牌类型、令牌过期时间和令牌范围,并使

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值