IT序号网

springboot 与oauth2集成

shasha 2021年06月13日 编程语言 281 0

pom.xml

        <!--auth2.0--> 
        <dependency> 
            <groupId>org.springframework.security.oauth</groupId> 
            <artifactId>spring-security-oauth2</artifactId> 
            <version>2.0.14.RELEASE</version> 
        </dependency> 
        <dependency> 
            <groupId>org.springframework.boot</groupId> 
            <artifactId>spring-boot-starter-security</artifactId> 
        </dependency>

创建 config

package com.jdels.project.configurer; 
 
import com.github.pagehelper.PageHelper; 
 
import org.apache.ibatis.plugin.Interceptor; 
import org.apache.ibatis.session.SqlSessionFactory; 
import org.mybatis.spring.SqlSessionFactoryBean; 
import org.springframework.beans.factory.annotation.Qualifier; 
import org.springframework.boot.autoconfigure.AutoConfigureAfter; 
import org.springframework.context.annotation.Bean; 
import org.springframework.context.annotation.Conditional; 
import org.springframework.context.annotation.Configuration; 
import org.springframework.core.io.support.PathMatchingResourcePatternResolver; 
import org.springframework.core.io.support.ResourcePatternResolver; 
 
import tk.mybatis.spring.mapper.MapperScannerConfigurer; 
 
import javax.annotation.Resource; 
import javax.sql.DataSource; 
 
import java.util.Properties; 
 
import static com.jdels.project.core.ProjectConstant.*; 
 
/** 
 * Mybatis & Mapper & PageHelper 配置 
 */ 
@Configuration 
public class MybatisConfigurer { 
 
    @Bean 
    public SqlSessionFactory sqlSessionFactoryBean(DataSource dataSource) throws Exception { 
        SqlSessionFactoryBean factory = new SqlSessionFactoryBean(); 
        factory.setDataSource(dataSource); 
        factory.setTypeAliasesPackage(MODEL_PACKAGE); 
 
        //配置分页插件,详情请查阅官方文档 
        PageHelper pageHelper = new PageHelper(); 
        Properties properties = new Properties(); 
        properties.setProperty("pageSizeZero", "true");//分页尺寸为0时查询所有纪录不再执行分页 
        properties.setProperty("reasonable", "true");//页码<=0 查询第一页,页码>=总页数查询最后一页 
        properties.setProperty("supportMethodsArguments", "true");//支持通过 Mapper 接口参数来传递分页参数 
        pageHelper.setProperties(properties); 
 
        //添加插件 
        factory.setPlugins(new Interceptor[]{pageHelper}); 
 
        //添加XML目录 
        ResourcePatternResolver resolver = new PathMatchingResourcePatternResolver(); 
        factory.setMapperLocations(resolver.getResources("classpath:mapper/*.xml")); 
        return factory.getObject(); 
    } 
 
    @Bean 
    public MapperScannerConfigurer mapperScannerConfigurer() { 
        MapperScannerConfigurer mapperScannerConfigurer = new MapperScannerConfigurer(); 
        mapperScannerConfigurer.setSqlSessionFactoryBeanName("sqlSessionFactoryBean"); 
        mapperScannerConfigurer.setBasePackage(MAPPER_PACKAGE); 
 
        //配置通用Mapper,详情请查阅官方文档 
        Properties properties = new Properties(); 
        properties.setProperty("mappers", MAPPER_INTERFACE_REFERENCE); 
        properties.setProperty("notEmpty", "false");//insert、update是否判断字符串类型!='' 即 test="str != null"表达式内是否追加 and str != '' 
        properties.setProperty("IDENTITY", "MYSQL"); 
        mapperScannerConfigurer.setProperties(properties); 
 
        return mapperScannerConfigurer; 
    } 
 
} 
 
package com.jdels.project.configurer; 
 
import org.springframework.beans.factory.annotation.Value; 
import org.springframework.context.annotation.Configuration; 
import org.springframework.security.config.annotation.web.builders.HttpSecurity; 
import org.springframework.security.oauth2.config.annotation.web.configuration.EnableResourceServer; 
import org.springframework.security.oauth2.config.annotation.web.configuration.ResourceServerConfigurerAdapter; 
 
@Configuration 
@EnableResourceServer 
public class ResourceServerConfiguration extends ResourceServerConfigurerAdapter { 
 
	@Value("#{'${security.antMatche.permit}'.split(',')}") 
	private String[] securityPermit; 
	     
    @Override 
    public void configure(HttpSecurity http) throws Exception { 
    	 
        http.authorizeRequests().antMatchers("/auth/*").authenticated() 
        .antMatchers(securityPermit).permitAll() 
        .anyRequest().authenticated(); 
    } 
 
} 
package com.jdels.project.configurer; 
 
import com.jdels.project.service.OAuthUserService; 
 
import org.springframework.beans.factory.annotation.Autowired; 
import org.springframework.context.annotation.Configuration; 
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder; 
import org.springframework.security.config.annotation.authentication.configurers.GlobalAuthenticationConfigurerAdapter; 
 
@Configuration 
public class WebSecurityConfiguration extends GlobalAuthenticationConfigurerAdapter { 
 
    private final OAuthUserService oauthUserService; 
 
    @Autowired 
    public WebSecurityConfiguration(OAuthUserService oauthUserService) { 
        this.oauthUserService = oauthUserService; 
    } 
 
    @Override 
    public void init(AuthenticationManagerBuilder auth) throws Exception { 
        auth.userDetailsService(oauthUserService); 
 
    } 
 
} 

创建 model

package com.jdels.project.model; 
 
import java.io.Serializable; 
 
public class OAuthUser implements Serializable { 
    private String username; 
    private String password; 
 
    public String getUsername() { 
        return username; 
    } 
 
    public void setUsername(String username) { 
        this.username = username; 
    } 
 
    public String getPassword() { 
        return password; 
    } 
 
    public void setPassword(String password) { 
        this.password = password; 
    } 
 
 
} 
package com.jdels.project.model; 
 
import java.util.Collections; 
 
public class OAuthUserDetails extends org.springframework.security.core.userdetails.User { 
 
    private OAuthUser user; 
 
    public OAuthUserDetails(OAuthUser oauthUser) { 
        super(oauthUser.getUsername(), oauthUser.getPassword(), true, true, true, true, Collections.EMPTY_SET); 
        this.user = oauthUser; 
    } 
 
    public OAuthUser getUser() { 
        return user; 
    } 
 
    public void setUser(OAuthUser user) { 
        this.user = user; 
    } 
}

创建Service

package com.jdels.project.service; 
 
import org.springframework.security.core.userdetails.UserDetailsService; 
 
public interface OAuthUserService extends UserDetailsService { 
    //后期在此新增UserService的业务接口 
} 

创建表结构

-- ---------------------------- 
-- Table structure for oauth_access_token 
-- ---------------------------- 
DROP TABLE IF EXISTS `oauth_access_token`; 
CREATE TABLE `oauth_access_token`  ( 
  `token_id` varchar(256) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL, 
  `token` blob NULL, 
  `authentication_id` varchar(250) CHARACTER SET utf8 COLLATE utf8_general_ci NOT NULL, 
  `user_name` varchar(256) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL, 
  `client_id` varchar(256) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL, 
  `authentication` blob NULL, 
  `refresh_token` varchar(256) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL, 
  PRIMARY KEY (`authentication_id`) USING BTREE 
) ENGINE = InnoDB CHARACTER SET = utf8 COLLATE = utf8_general_ci ROW_FORMAT = Dynamic; 
 
-- ---------------------------- 
-- Table structure for oauth_client_details 
-- ---------------------------- 
DROP TABLE IF EXISTS `oauth_client_details`; 
CREATE TABLE `oauth_client_details`  ( 
  `client_id` varchar(250) CHARACTER SET utf8 COLLATE utf8_general_ci NOT NULL, 
  `resource_ids` varchar(256) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL, 
  `client_secret` varchar(256) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL, 
  `scope` varchar(256) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL, 
  `authorized_grant_types` varchar(256) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL, 
  `web_server_redirect_uri` varchar(256) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL, 
  `authorities` varchar(256) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL, 
  `access_token_validity` int(11) NULL DEFAULT NULL, 
  `refresh_token_validity` int(11) NULL DEFAULT NULL, 
  `additional_information` varchar(4096) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL, 
  `autoapprove` varchar(256) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL, 
  PRIMARY KEY (`client_id`) USING BTREE 
) ENGINE = InnoDB CHARACTER SET = utf8 COLLATE = utf8_general_ci ROW_FORMAT = Dynamic; 
 
-- ---------------------------- 
-- Table structure for oauth_refresh_token 
-- ---------------------------- 
DROP TABLE IF EXISTS `oauth_refresh_token`; 
CREATE TABLE `oauth_refresh_token`  ( 
  `token_id` varchar(256) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL, 
  `token` blob NULL, 
  `authentication` blob NULL 
) ENGINE = InnoDB CHARACTER SET = utf8 COLLATE = utf8_general_ci ROW_FORMAT = Dynamic; 
 
--------------------- 

添加ClientDetail 有如下几种方式

package com.jdels.project.web; 
import java.util.List; 
 
import javax.annotation.Resource; 
 
import org.springframework.beans.factory.annotation.Autowired; 
import org.springframework.security.oauth2.config.annotation.builders.JdbcClientDetailsServiceBuilder; 
import org.springframework.security.oauth2.config.annotation.configurers.ClientDetailsServiceConfigurer; 
import org.springframework.security.oauth2.provider.ClientDetails; 
import org.springframework.security.oauth2.provider.client.BaseClientDetails; 
import org.springframework.security.oauth2.provider.client.JdbcClientDetailsService; 
import org.springframework.web.bind.annotation.GetMapping; 
import org.springframework.web.bind.annotation.PostMapping; 
import org.springframework.web.bind.annotation.RequestMapping; 
import org.springframework.web.bind.annotation.RequestParam; 
import org.springframework.web.bind.annotation.RestController; 
 
import com.github.pagehelper.PageHelper; 
import com.github.pagehelper.PageInfo; 
import com.jdels.project.configurer.AuthorizationConfig; 
import com.jdels.project.core.Result; 
import com.jdels.project.core.ResultGenerator; 
import com.jdels.project.model.ElsEmployee; 
import com.jdels.project.service.ElsEmployeeService; 
import com.jdels.project.service.OAuthUserService; 
 
/** 
* Created by cyt on 2018/09/30. 
*/ 
@RestController 
@RequestMapping("/els/employee") 
public class ElsEmployeeController { 
 
 
     
    @Autowired 
    private javax.sql.DataSource dataSource; 
     
    @Autowired 
    private AuthorizationConfig config; 
     
    @GetMapping("/addClient") 
    public Result addClient() throws Exception { 
    	    	 
    	JdbcClientDetailsServiceBuilder client = new JdbcClientDetailsServiceBuilder();  
    	client.dataSource(dataSource); 
    	 
    	client.withClient("clientapp") 
        .authorizedGrantTypes("password", "refresh_token") 
        .authorities("USER") 
        .scopes("read", "write") 
        .resourceIds("") 
        .secret("123456").and().build(); 
         
        return ResultGenerator.genSuccessResult(); 
    } 
     
    @GetMapping("/addClient1") 
    public Result addClient1() throws Exception { 
    	    	 
    	BaseClientDetails client=new BaseClientDetails(); 
    	 
    	client.setClientId("abc"); 
    	config.clientDetails().addClientDetails(client); 
 
        return ResultGenerator.genSuccessResult(); 
    } 
     
 
 
 
} 

评论关闭
IT序号网

微信公众号号:IT虾米 (左侧二维码扫一扫)欢迎添加!