SpringBoot 整合 Spring Security OAuth2 基于数据库实现

看这篇之前,相信你对SpringBoot,Spring Security,OAuth2都有个大概的了解,什么?不了解?篇幅太长,本人太懒,木有关系,已经替你找好博客了,springBoot介绍Oauth2 0.0介绍弹簧安全介绍

如果你是第一次接触,估计看完上面介绍还有有点懵,建议还是多了解一下,其实OAuth2.0的的就是一个协议,了解下它的运行原理,按照协议写代码就好了,OK,了解之后,开工

Spring Security OAuth2
1.导入jar包


    org.springframework.security.oauth
    spring-security-oauth2



    org.springframework.boot
    spring-boot-starter-security



    org.springframework.boot
    spring-boot-starter-web

2.建立数据表,主要存储认证信息以及令牌

表说明文档http://andaily.com/spring-oauth-server/db_table_description.html

create table oauth_client_details (
  client_id VARCHAR(256) PRIMARY KEY,
  resource_ids VARCHAR(256),
  client_secret VARCHAR(256),
  scope VARCHAR(256),
  authorized_grant_types VARCHAR(256),
  web_server_redirect_uri VARCHAR(256),
  authorities VARCHAR(256),
  access_token_validity INTEGER,
  refresh_token_validity INTEGER,
  additional_information VARCHAR(4096),
  autoapprove VARCHAR(256)
);




create table oauth_client_token (
  token_id VARCHAR(256),
  token blob,
  authentication_id VARCHAR(256) PRIMARY KEY,
  user_name VARCHAR(256),
  client_id VARCHAR(256)
);

create table oauth_access_token (
  token_id VARCHAR(256),
  token blob,
  authentication_id VARCHAR(256) PRIMARY KEY,
  user_name VARCHAR(256),
  client_id VARCHAR(256),
  authentication blob,
  refresh_token VARCHAR(256)
);

create table oauth_refresh_token (
  token_id VARCHAR(256),
  token blob,
  authentication blob
);

create table oauth_code (
  code VARCHAR(256), authentication blob
);

create table oauth_approvals (
	userId VARCHAR(256),
	clientId VARCHAR(256),
	scope VARCHAR(256),
	status VARCHAR(10),
	expiresAt TIMESTAMP,
	lastModifiedAt TIMESTAMP
);

也许你会问,表为什么这么建,不要着急,下面会慢慢讲到

3.认证服务器及资源服务器

@Configuration
public class OAuth2ServerConfig {

    private static final String DEMO_RESOURCE_ID = "test";

    @Configuration
    @EnableResourceServer
    protected static class ResourceServerConfiguration extends ResourceServerConfigurerAdapter {

        @Override
        public void configure(ResourceServerSecurityConfigurer resources) {
            resources.resourceId(DEMO_RESOURCE_ID).stateless(true);
        }

    }

    @Configuration
    @EnableAuthorizationServer
    @Slf4j
    protected static class AuthorizationServerConfiguration extends AuthorizationServerConfigurerAdapter {

        @Autowired
        AuthenticationManager authenticationManager;
        @Autowired
        RedisConnectionFactory redisConnectionFactory;

        @Autowired
        UserDetailsService userDetailsService;
//        @Autowired
//        @Qualifier("myMemoryTokenStore")
//        TokenStore myTokenStore;

        @Autowired
        private DataSource dataSource;

        @Bean // 声明TokenStore实现
        public TokenStore tokenStore() {
            return new JdbcTokenStores(dataSource);
        }

        @Bean
        public ClientDetailsService clientDetails() {
            return new JdbcClientDetailsService(dataSource);
        }

        @Override
        public void configure(ClientDetailsServiceConfigurer clients) throws Exception {
            //配置两个客户端,一个用于password认证一个用于client认证
//            clients.inMemory().withClient("client_1")
////                    .resourceIds(DEMO_RESOURCE_ID)
//                    .authorizedGrantTypes("client_credentials")
//                    .scopes("select")
//                    .authorities("ROLE_ADMIN","ROLE_USER")
//                    .secret("123456")
//                    .and().withClient("client_2")
////    a                .resourceIds(DEMO_RESOURCE_ID)
//                    .authorizedGrantTypes("password", "refresh_token")
//                    .scopes("select")
//                    .accessTokenValiditySeconds(1800)
//                    .refreshTokenValiditySeconds(3600)
//                    .authorities("ROLE_ADMIN","ROLE_USER")
//                    .secret("123456");

            //默认值InMemoryTokenStore对于单个服务器是完全正常的(即,在发生故障的情况下,低流量和热备份备份服务器)。大多数项目可以从这里开始,也可以在开发模式下运行,以便轻松启动没有依赖关系的服务器。
            //这JdbcTokenStore是同一件事的JDBC版本,它将令牌数据存储在关系数据库中。如果您可以在服务器之间共享数据库,则可以使用JDBC版本,如果只有一个,则扩展同一服务器的实例,或者如果有多个组件,则授权和资源服务器。要使用JdbcTokenStore你需要“spring-jdbc”的类路径。
            //这个地方指的是从jdbc查出数据来存储
            clients.withClientDetails(clientDetails());
        }

        @Override
        public void configure(AuthorizationServerEndpointsConfigurer endpoints) throws Exception {
            endpoints
                    .tokenStore(tokenStore())
                    .authenticationManager(authenticationManager)
                    .userDetailsService(userDetailsService)
                    // 2018-4-3 增加配置,允许 GET、POST 请求获取 token,即访问端点:oauth/token
                    .allowedTokenEndpointRequestMethods(HttpMethod.GET, HttpMethod.POST);


            // 配置TokenServices参数
            DefaultTokenServices tokenServices = (DefaultTokenServices) endpoints.getDefaultAuthorizationServerTokenServices();
            tokenServices.setTokenStore(endpoints.getTokenStore());
            tokenServices.setSupportRefreshToken(true);
            // 复用refresh token
            tokenServices.setReuseRefreshToken(true);
            tokenServices.setRefreshTokenValiditySeconds(3600);
            tokenServices.setClientDetailsService(endpoints.getClientDetailsService());
            tokenServices.setTokenEnhancer(endpoints.getTokenEnhancer());
            tokenServices.setAccessTokenValiditySeconds((int) TimeUnit.DAYS.toSeconds(1)); // 1天
            endpoints.tokenServices(tokenServices);

            super.configure(endpoints);

        }

        @Override
        public void configure(AuthorizationServerSecurityConfigurer oauthServer) throws Exception {
            //允许表单认证
            oauthServer.allowFormAuthenticationForClients();
        }
    }



    /**
     * 这里主要测试移除token,登出使用的
     * 
     */
    @FrameworkEndpoint
    public class LogoutEndpoint {
        @Qualifier("myMemoryTokenStore")
        @Autowired
        private TokenStore tokenStore;

        @RequestMapping(value = "/oauth/logout", method= RequestMethod.POST)
        @ResponseStatus(HttpStatus.OK)
        public void logout(HttpServletRequest request, HttpServletResponse response){
            String authHeader = request.getHeader("Authorization");
            if (authHeader != null) {
                String tokenValue = authHeader.replace("Bearer", "").trim();
                OAuth2AccessToken accessToken = tokenStore.readAccessToken(tokenValue);
                tokenStore.removeAccessToken(accessToken);
            }
        }
    }
}

4.整合SecurityConfiguration 

@Configuration
@EnableWebSecurity
@Slf4j
public class SecurityConfiguration extends WebSecurityConfigurerAdapter {
    @Resource(name = "userService")
    private UserService userService;

    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.userDetailsService(userService).passwordEncoder(passwordEncoder());
    }

    /**
     * 这一步的配置是必不可少的,否则SpringBoot会自动配置一个AuthenticationManager,覆盖掉内存中的用户
     */
    @Bean
    @Override
    public AuthenticationManager authenticationManagerBean() throws Exception {
        AuthenticationManager manager = super.authenticationManagerBean();
        return manager;
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        // @formatter:off
        http
                .logout()
                .clearAuthentication(true)
                .and()
                .requestMatchers().anyRequest()
                .and()
                .authorizeRequests()
                .antMatchers("/oauth/*", "/webjars/**", "/resources/**", "index.html", "/logout"
                        , "/swagger","/user/loginIn","/user/resetPwd").permitAll()
                .and()
                .csrf()
                .disable(); 
    }

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

}

5.编写userService

@Service("userService")
@Slf4j
public class UserService implements UserDetailsService {
    @Resource(name = "service.UserService")
    private com.jolly.atplan.umrah.service.service.UserService userService;


    @Override
    public UserDetails loadUserByUsername(String loginId) throws UsernameNotFoundException {
        log.info("LoginID : {}",loginId);
        User user = userService.getUserByLoginId(loginId);

        if(Objects.isNull(user)){
            throw new UsernameNotFoundException("User " + loginId + " was not found in the database");
        }

        Collection grantedAuthorities = new ArrayList<>();


        //返回一个SpringSecurity需要的用户对象
        return new org.springframework.security.core.userdetails.User(
                user.getLoginId(),
                user.getPwd(),
                grantedAuthorities);
    }
}

6.最后一步tokenConfig配置

@Configuration
public class TokenStoreConfig {
    @Autowired
    private DataSource dataSource;
    @Bean(name = "myMemoryTokenStore")
    public org.springframework.security.oauth2.provider.token.TokenStore myMemoryTokenStore() {
//        return new InMemoryTokenStore();
        return  new JdbcTokenStores(dataSource);
    }
}

7,别慌,还有一步,(如果你的控制台报错(找不到访问令牌),令牌找不到)

新建类,重写jdbcStore readAccessToken方法

SpringBoot 整合 Spring Security OAuth2 基于数据库实现_第1张图片

 

public class JdbcTokenStores extends JdbcTokenStore {
    private static final Log LOG = LogFactory.getLog(JdbcTokenStores.class);

    public JdbcTokenStores(DataSource dataSource) {
        super(dataSource);
    }

    @Override
    public OAuth2AccessToken readAccessToken(String tokenValue) {
        OAuth2AccessToken accessToken = null;

        try {
            accessToken = new DefaultOAuth2AccessToken(tokenValue);
        }
        catch (EmptyResultDataAccessException e) {
            if (LOG.isInfoEnabled()) {
                LOG.info("Failed to find access token for token "+tokenValue);
            }
        }
        catch (IllegalArgumentException e) {
            LOG.warn("Failed to deserialize access token for " +tokenValue,e);
            removeAccessToken(tokenValue);
        }

        return accessToken;
    }
}

8.测试访问

SpringBoot 整合 Spring Security OAuth2 基于数据库实现_第2张图片

9.查看数据库表数据

第一张图片是我们自己录入的,后面的则是自动生成的,说明令牌生成成功

SpringBoot 整合 Spring Security OAuth2 基于数据库实现_第3张图片

最后附上官网介绍:https://spring.io/guides/tutorials/spring-boot-oauth2/

你可能感兴趣的:(spring,springboot,的OAuth2.0的,Java的的)