pursue wind pursue wind
首页
Java
Python
数据库
框架
Linux
中间件
前端
计算机基础
DevOps
项目
面试
书
关于
归档
MacOS🤣 (opens new window)
GitHub (opens new window)
首页
Java
Python
数据库
框架
Linux
中间件
前端
计算机基础
DevOps
项目
面试
书
关于
归档
MacOS🤣 (opens new window)
GitHub (opens new window)
  • mybatis

  • mybatis-plus

  • Spring

  • SpringBoot

  • SpringSecurity

    • Spring Security OAuth
    • Spring Security oAuth2
    • SpringSecurity
    • SpringSecurity踩坑记录
    • SpringCloud

    • 单元测试框架Mockito
    • 框架
    • SpringSecurity
    pursuewind
    2020-11-23
    目录

    SpringSecurity踩坑记录

    # 认证服务器配置

    package cn.mirrorming.oauth2.server.config;
    
    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.boot.context.properties.ConfigurationProperties;
    import org.springframework.boot.jdbc.DataSourceBuilder;
    import org.springframework.context.annotation.Bean;
    import org.springframework.context.annotation.Configuration;
    import org.springframework.context.annotation.Primary;
    import org.springframework.security.authentication.AuthenticationManager;
    import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
    import org.springframework.security.oauth2.config.annotation.configurers.ClientDetailsServiceConfigurer;
    import org.springframework.security.oauth2.config.annotation.web.configuration.AuthorizationServerConfigurerAdapter;
    import org.springframework.security.oauth2.config.annotation.web.configuration.EnableAuthorizationServer;
    import org.springframework.security.oauth2.config.annotation.web.configurers.AuthorizationServerEndpointsConfigurer;
    import org.springframework.security.oauth2.config.annotation.web.configurers.AuthorizationServerSecurityConfigurer;
    import org.springframework.security.oauth2.provider.ClientDetailsService;
    import org.springframework.security.oauth2.provider.client.JdbcClientDetailsService;
    import org.springframework.security.oauth2.provider.token.TokenStore;
    import org.springframework.security.oauth2.provider.token.store.JdbcTokenStore;
    
    import javax.sql.DataSource;
    
    /**
     * @Author mirror
     * @Date 2019/9/4 14:06
     * @since v1.0.0
     */
    @Configuration
    @EnableAuthorizationServer
    public class AuthorizationServerConfiguration extends AuthorizationServerConfigurerAdapter {
    
        /**
         * 注入用于支持 password 模式
         */
        @Autowired
        private AuthenticationManager authenticationManager;
    
        @Bean
        @Primary
        @ConfigurationProperties(prefix = "spring.datasource")
        public DataSource dataSource() {
            // 配置数据源(注意,我使用的是 HikariCP 连接池),以上注解是指定数据源,否则会有冲突
            return DataSourceBuilder.create().build();
        }
    
        @Bean
        public TokenStore tokenStore() {
            // 基于 JDBC 实现,令牌保存到数据
            return new JdbcTokenStore(dataSource());
        }
    
        @Bean
        public ClientDetailsService jdbcClientDetails() {
            // 基于 JDBC 实现,需要事先在数据库配置客户端信息
            return new JdbcClientDetailsService(dataSource());
        }
    
        @Override
        public void configure(AuthorizationServerSecurityConfigurer security) throws Exception {
            security
                    // 允许客户端访问 /oauth/check_token 检查 token
                    .checkTokenAccess("isAuthenticated()")
                    .allowFormAuthenticationForClients();
        }
    
        @Override
        public void configure(AuthorizationServerEndpointsConfigurer endpoints) throws Exception {
            // 设置令牌
            endpoints
                    // 用于支持密码模式
                    .authenticationManager(authenticationManager)
                    .tokenStore(tokenStore());
        }
    
        @Override
        public void configure(ClientDetailsServiceConfigurer clients) throws Exception {
            // 读取客户端配置
            clients.withClientDetails(jdbcClientDetails());
        }
    }
    
    
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    48
    49
    50
    51
    52
    53
    54
    55
    56
    57
    58
    59
    60
    61
    62
    63
    64
    65
    66
    67
    68
    69
    70
    71
    72
    73
    74
    75
    76
    77
    78
    79
    80
    81
    package cn.mirrorming.oauth2.server.config;
    
    import cn.mirrorming.oauth2.server.servive.UserDetailsServiceImpl;
    import org.springframework.context.annotation.Bean;
    import org.springframework.context.annotation.Configuration;
    import org.springframework.security.authentication.AuthenticationManager;
    import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
    import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
    import org.springframework.security.config.annotation.web.builders.HttpSecurity;
    import org.springframework.security.config.annotation.web.builders.WebSecurity;
    import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
    import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
    import org.springframework.security.config.http.SessionCreationPolicy;
    import org.springframework.security.core.userdetails.UserDetailsService;
    import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
    
    /**
     * @Author mirror
     * @Date 2019/9/4 14:13
     * @since v1.0.0
     */
    @Configuration
    @EnableWebSecurity
    @EnableGlobalMethodSecurity(prePostEnabled = true, securedEnabled = true, jsr250Enabled = true)
    public class WebSecurityConfiguration extends WebSecurityConfigurerAdapter {
        @Bean
        public BCryptPasswordEncoder passwordEncoder() {
            // 设置默认的加密方式
            return new BCryptPasswordEncoder();
        }
    
        @Bean
        @Override
        public UserDetailsService userDetailsService() {
            return new UserDetailsServiceImpl();
        }
    
        /**
         * 用于支持 password 模式
         *
         * @return
         * @throws Exception
         */
        @Bean
        @Override
        public AuthenticationManager authenticationManagerBean() throws Exception {
            return super.authenticationManagerBean();
        }
    
        @Override
        protected void configure(AuthenticationManagerBuilder auth) throws Exception {
            // 使用自定义认证与授权
            auth.userDetailsService(userDetailsService());
        }
    
        @Override
        public void configure(WebSecurity web) throws Exception {
            // 将 check_token 暴露出去,否则资源服务器访问时报 403 错误
            web.ignoring().antMatchers("/oauth/check_token");
        }
    
        @Override
        protected void configure(HttpSecurity http) throws Exception {
            http
                    .formLogin()
                    //这里打开之后无法使用表单登录获得校验码
    //                .and()
    //                .sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS)
                    ;
        }
    
        public static void main(String[] args) {
            System.out.println(new BCryptPasswordEncoder().encode("1234"));
        }
    }
    
    
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    48
    49
    50
    51
    52
    53
    54
    55
    56
    57
    58
    59
    60
    61
    62
    63
    64
    65
    66
    67
    68
    69
    70
    71
    72
    73
    74
    75
    76
    package cn.mirrorming.oauth2.server.servive;
    
    import cn.mirrorming.oauth2.server.domain.po.Permission;
    import cn.mirrorming.oauth2.server.domain.po.Users;
    import org.assertj.core.util.Lists;
    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.security.core.GrantedAuthority;
    import org.springframework.security.core.authority.SimpleGrantedAuthority;
    import org.springframework.security.core.userdetails.User;
    import org.springframework.security.core.userdetails.UserDetails;
    import org.springframework.security.core.userdetails.UserDetailsService;
    import org.springframework.security.core.userdetails.UsernameNotFoundException;
    
    import java.util.List;
    
    /**
     * @Author mirror
     * @Date 2019/9/4 16:54
     * @since v1.0.0
     */
    public class UserDetailsServiceImpl implements UserDetailsService {
    
        @Autowired
        private UserService userService;
    
        @Autowired
        private PermissionService permissionService;
    
        @Override
        public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
            // 查询用户信息
            Users users = userService.getByUsername(username);
            List<GrantedAuthority> grantedAuthorities = Lists.newArrayList();
            if (users != null) {
                // 获取用户授权
                List<Permission> permissions = permissionService.selectPermissionByUserId(users.getId());
    
                // 声明用户授权
                permissions.parallelStream().forEach(permission -> {
                    if (permission != null && permission.getEnname() != null) {
                        GrantedAuthority grantedAuthority = new SimpleGrantedAuthority(permission.getEnname());
                        grantedAuthorities.add(grantedAuthority);
                    }
                });
            }
    
            // 由框架完成认证工作
            return new User(users.getUsername(), users.getPassword(), grantedAuthorities);
        }
    }
    
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    48
    49
    50
    # ===================================================================
    # Spring 配置
    # ===================================================================
    spring:
      application:
        name: oauth2-server
      security:
        user:
          # 账号
          name: root
          # 密码
          password: 123456
      # ===================================================================
      # MySQL 配置
      # ===================================================================
      datasource:
        type: com.zaxxer.hikari.HikariDataSource
        driver-class-name: com.mysql.cj.jdbc.Driver
        jdbc-url: jdbc:mysql://mirrorming.cn:3306/springsecurity?useUnicode=true&characterEncoding=utf-8&useSSL=false
        username: root
        password: a17770060561
        hikari:
          minimum-idle: 5
          idle-timeout: 600000
          maximum-pool-size: 10
          auto-commit: true
          pool-name: MyHikariCP
          max-lifetime: 1800000
          connection-timeout: 30000
          connection-test-query: SELECT 1
    # ===================================================================
    # 端口 配置
    # ===================================================================
    server:
      port: 7080
    # ===================================================================
    # mybatis-plus 配置
    # ===================================================================
    mybatis-plus:
      type-aliases-package: cn.mirrorming.oauth2.server.domain.po
      mapper-locations: classpath:mapper/**.xml
      configuration:
        map-underscore-to-camel-case: true
        log-impl: org.apache.ibatis.logging.stdout.StdOutImpl
    
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44

    # 资源服务器配置

    package cn.mirrorming.oauth2.resources.config;
    
    import org.springframework.boot.context.properties.ConfigurationProperties;
    import org.springframework.boot.jdbc.DataSourceBuilder;
    import org.springframework.context.annotation.Bean;
    import org.springframework.context.annotation.Configuration;
    import org.springframework.context.annotation.Primary;
    import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
    import org.springframework.security.config.annotation.web.builders.HttpSecurity;
    import org.springframework.security.config.http.SessionCreationPolicy;
    import org.springframework.security.oauth2.config.annotation.web.configuration.EnableResourceServer;
    import org.springframework.security.oauth2.config.annotation.web.configuration.ResourceServerConfigurerAdapter;
    
    import javax.sql.DataSource;
    
    /**
     * @Author mirror
     * @Date 2019/9/5 9:53
     * @since v1.0.0
     */
    @Configuration
    @EnableResourceServer
    @EnableGlobalMethodSecurity(prePostEnabled = true, securedEnabled = true, jsr250Enabled = true)
    public class ResourceServerConfiguration extends ResourceServerConfigurerAdapter {
        @Bean
        @Primary
        @ConfigurationProperties(prefix = "spring.datasource")
        public DataSource dataSource() {
            // 配置数据源(注意,我使用的是 HikariCP 连接池),以上注解是指定数据源,否则会有冲突
            return DataSourceBuilder.create().build();
        }
    
        @Override
        public void configure(HttpSecurity http) throws Exception {
            http
                    .exceptionHandling()
                    .and()
                    .sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS)
                    .and()
                    .authorizeRequests()
                    // 以下为配置所需保护的资源路径及权限,需要与认证服务器配置的授权部分对应
                    .antMatchers("/").hasAuthority("SystemContent")
                    .antMatchers("/view/**").hasAuthority("SystemContentView")
                    .antMatchers("/insert/**").hasAuthority("SystemContentInsert")
                    .antMatchers("/update/**").hasAuthority("SystemContentUpdate")
                    .antMatchers("/delete/**").hasAuthority("SystemContentDelete");
        }
    
    }
    
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    48
    49
    spring:
      application:
        name: oauth2-resource
      # ===================================================================
      # MySQL 配置
      # ===================================================================
      datasource:
        type: com.zaxxer.hikari.HikariDataSource
        driver-class-name: com.mysql.cj.jdbc.Driver
        jdbc-url: jdbc:mysql://mirrorming.cn:3306/springsecurity?useUnicode=true&characterEncoding=utf-8&useSSL=false
        username: root
        password: a17770060561
        hikari:
          minimum-idle: 5
          idle-timeout: 600000
          maximum-pool-size: 10
          auto-commit: true
          pool-name: MyHikariCP
          max-lifetime: 1800000
          connection-timeout: 30000
          connection-test-query: SELECT 1
    
    security:
      oauth2:
        client:
          client-id: client
          client-secret: secret
          access-token-uri: http://localhost:7080/oauth/token
          user-authorization-uri: http://localhost:7080/oauth/authorize
        resource:
          token-info-uri: http://localhost:7080/oauth/check_token
    
    server:
      port: 7081
      servlet:
        context-path: /contents
    
    
    # ===================================================================
    # mybatis-plus 配置
    # ===================================================================
    mybatis-plus:
      type-aliases-package: cn.mirrorming.oauth2.resources.domain.po
      mapper-locations: classpath:mapper/**.xml
      configuration:
        map-underscore-to-camel-case: true
        log-impl: org.apache.ibatis.logging.stdout.StdOutImpl
    logging:
      level:
        root: INFO
        org.springframework.web: INFO
        org.springframework.security: INFO
        org.springframework.security.oauth2: INFO
    
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    48
    49
    50
    51
    52
    53
    Last Updated: 2023/01/30, 11:01:00
    SpringSecurity
    SpringCloud-广告系统实战(七)----广告检索系统(加载全量索引)

    ← SpringSecurity SpringCloud-广告系统实战(七)----广告检索系统(加载全量索引)→

    Theme by Vdoing | Copyright © 2019-2023 pursue-wind | 粤ICP备2022093130号
    • 跟随系统
    • 浅色模式
    • 深色模式
    • 阅读模式
    • 飙升榜
    • 新歌榜
    • 云音乐民谣榜
    • 美国Billboard榜
    • UK排行榜周榜
    • 网络DJ