Springbootとoauth 2の統合
11699 ワード
pom.xml
configの作成
モデルの作成
サービスの作成
テーブル構造の作成
ClientDetailを追加するには、次の方法があります.
org.springframework.security.oauth
spring-security-oauth2
2.0.14.RELEASE
org.springframework.boot
spring-boot-starter-security
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);
}
}
モデルの作成
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;
}
}
サービスの作成
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();
}
}