详解Springboot Oauth2 Server搭建Oauth2认证服务

本教程源码
https://github.com/bestaone/HiAuth

源码比较全面,教程我就只介绍关键代码了,喜欢的点个star,谢谢!

关键词

  • 微服务认证
  • Oauth2
  • 认证中心
  • springboot
  • spring-cloud-starter-oauth2
  • 集成Oauth2
  • Oauth2 客户端

介绍

这里我将介绍两个部分

  • Oauth2 server 的开发 (hi-auth-web模块)
  • Oauth2 client 的开发 (hi-mall-web模块)

效果图

himall.gif

umc.gif

LIVE DEMO

HiMall: http://hiauth.cn/himall

UMC: http://hiauth.cn/umc

Swagger2:http://hiauth.cn/hiauth/swagger-ui.html

Oauth2 server 搭建

数据库表(mysql5.6),其中只有sys_user表由我们自己控制,其他表由框架控制

CREATE TABLE `clientdetails` (
 `appId` varchar(255) NOT NULL,
 `resourceIds` varchar(256) DEFAULT NULL,
 `appSecret` varchar(256) DEFAULT NULL,
 `scope` varchar(256) DEFAULT NULL,
 `grantTypes` varchar(256) DEFAULT NULL,
 `redirectUrl` varchar(256) DEFAULT NULL,
 `authorities` varchar(256) DEFAULT NULL,
 `access_token_validity` int(11) DEFAULT NULL,
 `refresh_token_validity` int(11) DEFAULT NULL,
 `additionalInformation` varchar(4096) DEFAULT NULL,
 `autoApproveScopes` varchar(256) DEFAULT NULL,
 PRIMARY KEY (`appId`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

CREATE TABLE `oauth_access_token` (
 `token_id` varchar(256) DEFAULT NULL,
 `token` blob,
 `authentication_id` varchar(255) NOT NULL,
 `user_name` varchar(256) DEFAULT NULL,
 `client_id` varchar(256) DEFAULT NULL,
 `authentication` blob,
 `refresh_token` varchar(256) DEFAULT NULL,
 PRIMARY KEY (`authentication_id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

CREATE TABLE `oauth_approvals` (
 `userId` varchar(256) DEFAULT NULL,
 `clientId` varchar(256) DEFAULT NULL,
 `scope` varchar(256) DEFAULT NULL,
 `status` varchar(10) DEFAULT NULL,
 `expiresAt` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
 `lastModifiedAt` timestamp NOT NULL DEFAULT '0000-00-00 00:00:00'
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

CREATE TABLE `oauth_client_details` (
 `client_id` varchar(255) NOT NULL,
 `resource_ids` varchar(256) DEFAULT NULL,
 `client_secret` varchar(256) DEFAULT NULL,
 `scope` varchar(256) DEFAULT NULL,
 `authorized_grant_types` varchar(256) DEFAULT NULL,
 `web_server_redirect_uri` varchar(2560) DEFAULT NULL,
 `authorities` varchar(256) DEFAULT NULL,
 `access_token_validity` int(11) DEFAULT NULL,
 `refresh_token_validity` int(11) DEFAULT NULL,
 `additional_information` varchar(4096) DEFAULT NULL,
 `autoapprove` varchar(256) DEFAULT NULL,
 PRIMARY KEY (`client_id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

INSERT INTO `oauth_client_details` VALUES ('client', null, '$2a$10$1N/.LvTJuYpvxDzoJ1KdvuPDdV/kDSQE9Cxm9BzB1PreyzK6gmFRe', 'ALL,AUTH,USER,GOODS,ORDER', 'authorization_code,client_credentials,password,refresh_token', 'http://localhost:8081/mall/callback,http://localhost:9080/user/webjars/springfox-swagger-ui/oauth2-redirect.html,http://localhost:9081/goods/webjars/springfox-swagger-ui/oauth2-redirect.html,http://localhost:9082/order/webjars/springfox-swagger-ui/oauth2-redirect.html,http://localhost/user/webjars/springfox-swagger-ui/oauth2-redirect.html,http://localhost/goods/webjars/springfox-swagger-ui/oauth2-redirect.html,http://localhost/order/webjars/springfox-swagger-ui/oauth2-redirect.html', 'ROLE_USER', '1800', '86400', null, 'false');

CREATE TABLE `oauth_client_token` (
 `token_id` varchar(256) DEFAULT NULL,
 `token` blob,
 `authentication_id` varchar(255) NOT NULL,
 `user_name` varchar(256) DEFAULT NULL,
 `client_id` varchar(256) DEFAULT NULL,
 PRIMARY KEY (`authentication_id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

CREATE TABLE `oauth_code` (
 `code` varchar(256) DEFAULT NULL,
 `authentication` blob
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

CREATE TABLE `oauth_refresh_token` (
 `token_id` varchar(256) DEFAULT NULL,
 `token` blob,
 `authentication` blob
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

CREATE TABLE `sys_user` (
 `id` bigint(20) NOT NULL,
 `name` varchar(20) DEFAULT NULL,
 `username` varchar(20) NOT NULL,
 `password` varchar(128) NOT NULL,
 `tel` varchar(20) DEFAULT NULL,
 `gender` varchar(10) DEFAULT NULL,
 `createTime` datetime DEFAULT NULL,
 PRIMARY KEY (`id`),
 UNIQUE KEY `unique_username` (`username`),
 UNIQUE KEY `unique_tel` (`tel`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

INSERT INTO `sys_user` VALUES ('1', '张三', 'admin', '123456', '13712345678', 'MALE', '2018-12-03 17:57:12');
INSERT INTO `sys_user` VALUES ('2', '李四', 'user', '123456', '13812345678', 'UNKNOWN', '2018-12-03 17:57:12');

pom.xml如下

<dependency>
  <groupId>org.springframework.boot</groupId>
  <artifactId>spring-boot-starter-web</artifactId>
</dependency>
<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>
  <version>2.0.1.RELEASE</version>
</dependency>
<dependency>
  <groupId>org.springframework.boot</groupId>
  <artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
<dependency>
  <groupId>org.springframework.boot</groupId>
  <artifactId>spring-boot-starter-jdbc</artifactId>
</dependency>
<dependency>
  <groupId>mysql</groupId>
  <artifactId>mysql-connector-java</artifactId>
</dependency>
<dependency>
  <groupId>org.mybatis.spring.boot</groupId>
  <artifactId>mybatis-spring-boot-starter</artifactId>
  <version>2.0.0</version>
</dependency>

添加表sys_user的service、mapper

@Mapper
public interface UserMapper {

  @Insert("INSERT INTO sys_user(id,name,username,password,tel,gender,createTime) VALUES(#{id},#{name},#{username},#{password},#{tel},#{gender},#{createTime})")
  void insert(User user);

  @Delete("DELETE FROM sys_user WHERE id = #{id}")
  void delete(Long id);

  @Update("UPDATE sys_user SET name=#{name},username=#{username},password=#{password},tel=#{tel},gender=#{gender},createTime=#{createTime} WHERE id =#{id}")
  int update(User user);

  @ResultMap("BaseResultMap")
  @Select("SELECT * FROM sys_user WHERE id=#{id}")
  User findById(Long id);

  @ResultMap("BaseResultMap")
  @Select("SELECT * FROM sys_user WHERE username=#{username}")
  User findByUsername(String username);

  @ResultMap("BaseResultMap")
  @Select("SELECT * FROM sys_user WHERE tel=#{tel}")
  User findByTel(String tel);

  @ResultMap("BaseResultMap")
  @Select("SELECT * FROM sys_user")
  List<User> findAll();

  @ResultMap("BaseResultMap")
  @Select("SELECT * FROM sys_user WHERE name like #{name}")
  List<User> findByName(String name);

}

@Service
public class UserServiceImpl implements UserService {

  @Resource
  UserMapper mapper;

  @Override
  public User save(User user) {
    if(user.getId()!=null){
      mapper.update(user);
    } else {
      user.setId(System.currentTimeMillis());
      mapper.insert(user);
    }
    return user;
  }

  @Override
  public User findById(Long id) {
    return mapper.findById(id);
  }

  @Override
  public User findByUsername(String username) {
    return mapper.findByUsername(username);
  }

  @Override
  public User findByTel(String tel) {
    return mapper.findByTel(tel);
  }

  @Override
  public List<User> findAll() {
    return mapper.findAll();
  }

  @Override
  public void delete(Long id) {
    mapper.delete(id);
  }

  @Override
  public List<User> findByName(String name) {
    return mapper.findByName("%" + name + "%");
  }

}

添加登录拦截

@Configuration
@EnableWebSecurity
@EnableGlobalMethodSecurity(prePostEnabled = true)
public class SecurityConfig extends WebSecurityConfigurerAdapter {

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

  @Bean
  public UserDetailsService simpleUserDetailsService(){
    return new UserDetailsServiceImpl();
  }

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

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

  @Override
  protected void configure(HttpSecurity http) throws Exception {

    http.userDetailsService(userDetailsService());
    http.csrf().disable();
    http.formLogin()
        .loginPage("/signin").loginProcessingUrl("/signin/form/account").defaultSuccessUrl("/index")
        .and()
        .logout().logoutUrl("/signout").logoutSuccessUrl("/signin")
        .and()
        .authorizeRequests()
        .antMatchers("/signin","/signin/form/tel","/code/image","/code/mobile","/static/**").permitAll()
        .antMatchers("/oauth/**").permitAll()
        .antMatchers("/user/**").hasAnyRole("USER","ADMIN")
        .anyRequest().authenticated();

  }

}

添加登录表单signin.html

<div class="tab-pane fade in active" id="account-login">
  <form th:action="@{/signin/form/account}" method="post">
    <label for="username" class="sr-only">用户名</label>
    <input class="form-control" type="text" name="username" id="username" value="user" placeholder="账号" required>
    <label for="password" class="sr-only">密码</label>
    <input class="form-control" type="password" name="password" id="password" value="123456" placeholder="密码" required>
    <button class="btn btn-lg btn-primary btn-block" type="submit">登录</button>
  </form>
</div>

Oauth2 server Config

@Configuration
@EnableAuthorizationServer
public class OAuth2AuthorizationConfig extends AuthorizationServerConfigurerAdapter {

  @Autowired
  private Environment env;

  @Autowired
  private AuthenticationManager authenticationManager;

  /**
   * 自定义授权页面
   */
  @Autowired
  private AuthorizationEndpoint authorizationEndpoint;

  @PostConstruct
  public void init() {
    authorizationEndpoint.setUserApprovalPage("forward:/oauth/my_approval_page");
    authorizationEndpoint.setErrorPage("forward:/oauth/my_error_page");
  }

  @Bean
  public DataSource dataSource() {
    final DriverManagerDataSource dataSource = new DriverManagerDataSource();
    dataSource.setDriverClassName(env.getProperty("spring.datasource.driver-class-name"));
    dataSource.setUrl(env.getProperty("spring.datasource.url"));
    dataSource.setUsername(env.getProperty("spring.datasource.username"));
    dataSource.setPassword(env.getProperty("spring.datasource.password"));
    return dataSource;
  }

  @Bean
  public ApprovalStore approvalStore() {
    return new JdbcApprovalStore(dataSource());
  }

  @Bean
  protected AuthorizationCodeServices authorizationCodeServices() {
    return new JdbcAuthorizationCodeServices(dataSource());
  }

  @Bean
  public TokenStore tokenStore() {
    return new JdbcTokenStore(dataSource());
  }

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

  @Override
  public void configure(AuthorizationServerEndpointsConfigurer endpoints) {
    // oauth_approvals
    endpoints.approvalStore(approvalStore());
    // oauth_code
    endpoints.authorizationCodeServices(authorizationCodeServices());
    // oauth_access_token & oauth_refresh_token
    endpoints.tokenStore(tokenStore());
    // 支持password grant type
    endpoints.authenticationManager(authenticationManager);
  }

  @Override
  public void configure(AuthorizationServerSecurityConfigurer oauthServer) {
    oauthServer.allowFormAuthenticationForClients();
  }
}

Oauth2 client 搭建

pom.xml

<dependency>
  <groupId>org.springframework.boot</groupId>
  <artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
  <groupId>org.springframework.boot</groupId>
  <artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
<dependency>
  <groupId>com.github.scribejava</groupId>
  <artifactId>scribejava-apis</artifactId>
  <version>5.0.0</version>
</dependency>

DefaultApi20

public class AiwanApi extends DefaultApi20 {

  private String accessTokenEndpoint = "http://localhost:8080/oauth/token";
  private String authorizationBaseUrl = "http://localhost:8080/oauth/authorize";

  protected AiwanApi() {}

  private static class InstanceHolder {
    private static final AiwanApi INSTANCE = new AiwanApi();
  }

  public static AiwanApi instance() {
    return InstanceHolder.INSTANCE;
  }

  @Override
  public String getAccessTokenEndpoint() {
    return accessTokenEndpoint;
  }

  @Override
  protected String getAuthorizationBaseUrl() {
    return authorizationBaseUrl;
  }

  @Override
  public TokenExtractor<OAuth2AccessToken> getAccessTokenExtractor() {
    return OAuth2AccessTokenJsonExtractor.instance();
  }

  @Override
  public OAuth20Service createService(OAuthConfig config) {
    return new AiwanService(this, config);
  }

}

OAuth20Service

public class AiwanService extends OAuth20Service {

  public AiwanService(DefaultApi20 api, OAuthConfig config) {
    super(api, config);
  }

  @Override
  protected OAuthRequest createAccessTokenRequest(String code) {
    final OAuthRequest request = new OAuthRequest(getApi().getAccessTokenVerb(), getApi().getAccessTokenEndpoint());
    final OAuthConfig config = getConfig();
    request.addParameter(OAuthConstants.CLIENT_ID, config.getApiKey());
    final String apiSecret = config.getApiSecret();
    if (apiSecret != null) {
      request.addParameter(OAuthConstants.CLIENT_SECRET, apiSecret);
    }
    request.addParameter(OAuthConstants.CODE, code);
    request.addParameter(OAuthConstants.REDIRECT_URI, config.getCallback());
    final String scope = config.getScope();
    if (scope != null) {
      request.addParameter(OAuthConstants.SCOPE, scope);
    }
    request.addParameter(OAuthConstants.GRANT_TYPE, OAuthConstants.AUTHORIZATION_CODE);
    request.addHeader(OAuthConstants.HEADER,
        OAuthConstants.BASIC + ' '
        + Base64Encoder.getInstance()
        .encode(String.format("%s:%s", config.getApiKey(), apiSecret).getBytes(Charset.forName("UTF-8"))));
    return request;
  }
}

获取access_token

@Controller
public class IndexController {

  private static Logger logger = LoggerFactory.getLogger(IndexController.class);

  private static final String SESSION_KEY_ACCESS_TOKEN = "MY_ACCESS_TOKEN";

  /**
   * 为防止CSRF跨站攻击,每次请求STATE的值应该不同,可以放入Session!
   * 由于都是localhost测试,所以session无法保持,用一个固定值。
   */
  private static final String STATE = "secret-rensanning";
  private static final String CLIENT_ID = "client";
  private static final String CLIENT_SECRET = "123456";
  private static final String CALLBACK_URL = "http://localhost:8081/mall/callback";
  private static final String SCOPE = "ALL";
  private OAuth20Service aiwanApi = new ServiceBuilder(CLIENT_ID)
      .apiSecret(CLIENT_SECRET)
      .scope(SCOPE)
      .state(STATE)
      .callback(CALLBACK_URL)
      .build(AiwanApi.instance());

  @GetMapping("/")
  public String index() {
    return "index";
  }

  @GetMapping("/signin")
  public void signin(HttpServletRequest request, HttpServletResponse response) throws IOException {
    logger.debug("signin");
    logger.info("session id:{}", request.getSession().getId());
    String authorizationUrl = aiwanApi.getAuthorizationUrl();
    logger.info("redirectURL:{}", authorizationUrl);
    response.sendRedirect(authorizationUrl);
  }

  @GetMapping("/callback")
  public String callback(@RequestParam(value = "code", required = false) String code,
              @RequestParam(value = "state", required = false) String state, HttpServletRequest request) throws Exception {

    logger.debug("callback [code:{}],[state:{}],[sessionId:{}]", code, state, request.getSession().getId());

    if (STATE.equals(state)) {
      logger.info("State OK!");
    } else {
      logger.error("State NG!");
    }

    OAuth2AccessToken accessToken = aiwanApi.getAccessToken(code);
    request.getSession().setAttribute(SESSION_KEY_ACCESS_TOKEN, accessToken);

    return "profile";
  }

}

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持我们。

(0)

相关推荐

  • springboot+Oauth2实现自定义AuthenticationManager和认证path

    本人在工作中需要构建这么一个后台框架,基于springboot,登录时认证使用自定义AuthenticationManager:同时支持Oauth2访问指定API接口,认证时的AuthenticationManager和登录规则不同.在研究了源码的基础上参考很多文章,目前基本得以解决. @Configuration public class OAuth2Configuration { @SpringBootApplication @RestController @EnableResourceSe

  • 详解Springboot Oauth2 Server搭建Oauth2认证服务

    本教程源码 https://github.com/bestaone/HiAuth 源码比较全面,教程我就只介绍关键代码了,喜欢的点个star,谢谢! 关键词 微服务认证 Oauth2 认证中心 springboot spring-cloud-starter-oauth2 集成Oauth2 Oauth2 客户端 介绍 这里我将介绍两个部分 Oauth2 server 的开发 (hi-auth-web模块) Oauth2 client 的开发 (hi-mall-web模块) 效果图 himall.g

  • 详解SpringBoot修改启动端口server.port的四种方式

    方式一: 配置文件 application.properties server.port=7788 方式二: java启动命令 # 以应用参数的方式 java -jar <path/to/my/jar> --server.port=7788 # 或以 JDK 参数的方式 java -Dserver.port=7788 -jar <path/to/my/jar> 方式三: 环境变量 SERVER_PORT Linux: SERVER_PORT=7788 java -jar <p

  • 详解springboot+aop+Lua分布式限流的最佳实践

    一.什么是限流?为什么要限流? 不知道大家有没有做过帝都的地铁,就是进地铁站都要排队的那种,为什么要这样摆长龙转圈圈?答案就是为了限流!因为一趟地铁的运力是有限的,一下挤进去太多人会造成站台的拥挤.列车的超载,存在一定的安全隐患.同理,我们的程序也是一样,它处理请求的能力也是有限的,一旦请求多到超出它的处理极限就会崩溃.为了不出现最坏的崩溃情况,只能耽误一下大家进站的时间. 限流是保证系统高可用的重要手段!!! 由于互联网公司的流量巨大,系统上线会做一个流量峰值的评估,尤其是像各种秒杀促销活动,

  • 详解springboot+mybatis-plue实现内置的CRUD使用详情

    mybatis-plus的特性 无侵入:只做增强不做改变,引入它不会对现有工程产生影响,如丝般顺滑 损耗小:启动即会自动注入基本CURD,性能基本无损耗,直接面向对象操作 强大的 CRUD操作:内置通用 Mapper.通用Service,仅仅通过少量配置即可实现单表大部分 CRUD 操作,更有强大的条件构造器,满足各类使用需求 支持 Lambda形式调用:通过 Lambda 表达式,方便的编写各类查询条件,无需再担心字段写错 支持主键自动生成:支持多达 4种主键策略(内含分布式唯一 ID 生成器

  • 详解SpringBoot如何实现整合微信登录

    目录 1.准备工作 1.1 获取微信登录凭证 1.2 配置文件 1.3 添加依赖 1.4 创建读取公共常量的工具类 1.5 HttpClient工具类 2.实现微信登录 2.1 具体流程 2.2 生成微信扫描的二维码(请求CODE) 2.3 回调 1.准备工作 1.1 获取微信登录凭证 前往官网微信开放平台 (qq.com),完成以下步骤: 1.注册 2.邮箱激活 3.完善开发者资料 4.开发者资质认证 5.创建网站应用 1.2 配置文件 在配置文件application.properties添

  • 详解SpringBoot中如何使用布隆过滤器

    目录 前言 一.Guava 实现布隆过滤器 二.Hutool 布隆过滤器 三.Redission 布隆过滤器 四.小结 五.Guava 布隆过滤器结合 Redis 使用 昨天写了一篇Redis布隆过滤器相关的命令的文章,今天来说一说springboot中如何简单在代码中使用布隆过滤器吧. 目前市面上也有好几种实现方式,如果你需要高度定制化,可以完全从零实现,当然这不是一个简单的工程. 如果只是想快速开始的话,那么市面上现成的实现,无疑是最快的. 前言 今天说到的实现方式有以下几种: 引入 Gua

  • 详解springboot整合ehcache实现缓存机制

    EhCache 是一个纯Java的进程内缓存框架,具有快速.精干等特点,是Hibernate中默认的CacheProvider. ehcache提供了多种缓存策略,主要分为内存和磁盘两级,所以无需担心容量问题. spring-boot是一个快速的集成框架,其设计目的是用来简化新Spring应用的初始搭建以及开发过程.该框架使用了特定的方式来进行配置,从而使开发人员不再需要定义样板化的配置. 由于spring-boot无需任何样板化的配置文件,所以spring-boot集成一些其他框架时会有略微的

  • 详解Springboot整合ActiveMQ(Queue和Topic两种模式)

    写在前面: 从2018年底开始学习SpringBoot,也用SpringBoot写过一些项目.这里对学习Springboot的一些知识总结记录一下.如果你也在学习SpringBoot,可以关注我,一起学习,一起进步. ActiveMQ简介 1.ActiveMQ简介 Apache ActiveMQ是Apache软件基金会所研发的开放源代码消息中间件:由于ActiveMQ是一个纯Java程序,因此只需要操作系统支持Java虚拟机,ActiveMQ便可执行. 2.ActiveMQ下载 下载地址:htt

  • 详解SpringBoot 应用如何提高服务吞吐量

    意外和明天不知道哪个先来.没有危机是最大的危机,满足现状是最大的陷阱. 背景 生产环境偶尔会有一些慢请求导致系统性能下降,吞吐量下降,下面介绍几种优化建议. 方案 1.undertow替换tomcat 电子商务类型网站大多都是短请求,一般响应时间都在100ms,这时可以将web容器从tomcat替换为undertow,下面介绍下步骤: 1.增加pom配置 <dependency> <groupid> org.springframework.boot </groupid>

  • 详解SpringBoot中的tomcat优化和修改

    项目背景 在做项目的时候,把SpringBoot的项目打包成安装包了,在客户上面安装运行,一切都是那么的完美,可是发生了意外,对方突然说导出导入的文件都不行了.我急急忙忙的查看日志,发现报了一个错误 java.io.IOException: The temporary upload location [C:\Windows\Temp\tomcat.1351070438015228346.8884\work\Tomcat\localhost\ROOT] is not valid at org.ap

随机推荐