• SpringBoot整合SpringSecurity:集中式项目


    代码已提交至github:https://github.com/JGZY/springboot-security-family

    sql脚本在resource目录下,用户密码是1234.

    只实现了部分主要功能(认证授权),增删改查没有实现。

    pom依赖

    注意打包方式要改成war包

    <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.boot</groupId>
        <artifactId>spring-boot-starter-tomcat</artifactId>
    </dependency>
    
    <dependency>
        <groupId>org.apache.tomcat.embed</groupId>
        <artifactId>tomcat-embed-jasper</artifactId>
    </dependency>
    
    <dependency>
        <groupId>mysql</groupId>
        <artifactId>mysql-connector-java</artifactId>
    </dependency>
    
    <dependency>
        <groupId>tk.mybatis</groupId>
        <artifactId>mapper-spring-boot-starter</artifactId>
        <version>2.1.5</version>
    </dependency>
    

    配置文件

    spring.mvc.view.prefix=/pages/
    spring.mvc.view.suffix=.jsp
    
    spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
    spring.datasource.url=jdbc:mysql:///security_authority?serverTimezone=UTC
    spring.datasource.username=root
    spring.datasource.password=1234
    
    mybatis.type-aliases-package=com.wj.springsecurity.domain
    mybatis.configuration.map-underscore-to-camel-case=true
    
    logging.level.com.wj.springsecurity.mapper=debug
    

    配置类

    @EnableGlobalMethodSecurity(securedEnabled = true)//开启@Secured注解
    @EnableWebSecurity
    public class SecurityConfig extends WebSecurityConfigurerAdapter {
    
        @Autowired
        private UserService userService;
    
        @Bean
        public BCryptPasswordEncoder passwordEncoder(){
            return new BCryptPasswordEncoder();
        }
    
        @Override
        public void configure(HttpSecurity http) throws Exception {
            http.authorizeRequests()
                    .antMatchers("/login.jsp","/failer.jsp","/css/**","/img/**","/plugins/**","/favicon.ico").permitAll()
                    .antMatchers("/**").hasAnyRole("USER","ADMIN")
                    .anyRequest().authenticated()
                    .and()
                    .formLogin().loginPage("/login.jsp").loginProcessingUrl("/login")
                    .successForwardUrl("/index.jsp").failureForwardUrl("/failer.jsp")
                    .permitAll()
                    .and()
                    .logout().logoutUrl("/logout").logoutSuccessUrl("/login.jsp")
                    .invalidateHttpSession(true)//是否清空session
                    .permitAll()
                    .and()
                    .csrf().disable();
        }
    
        /**
         * 认证的来源(内存还是数据库)
         * @param auth
         * @throws Exception
         */
        @Override
        public void configure(AuthenticationManagerBuilder auth) throws Exception {
            //auth.inMemoryAuthentication().withUser("user").password("{noop}1234").roles("USER");
            auth.userDetailsService(userService).passwordEncoder(passwordEncoder());
        }
    }
    
    

    主启动类

    @MapperScan("com.wj.springsecurity.mapper")
    @SpringBootApplication
    public class SpringbootSecurityJspApplication {
    
        public static void main(String[] args) {
            SpringApplication.run(SpringbootSecurityJspApplication.class, args);
        }
    
    }
    

    UserService

    实体类

    SysUser

    public class SysUser implements UserDetails {
    
        private Integer id;
        private String username;
        private String password;
        private Integer status;
    
        private List<SysRole> roles;
    
        public List<SysRole> getRoles() {
            return roles;
        }
    
        public void setRoles(List<SysRole> roles) {
            this.roles = roles;
        }
    
        public void setId(Integer id) {
            this.id = id;
        }
    
        public void setUsername(String username) {
            this.username = username;
        }
    
        public void setPassword(String password) {
            this.password = password;
        }
    
        public void setStatus(Integer status) {
            this.status = status;
        }
    
        public Integer getId() {
            return id;
        }
    
        public Integer getStatus() {
            return status;
        }
    
        @JsonIgnore
        @Override
        public Collection<? extends GrantedAuthority> getAuthorities() {
            return roles;
        }
    
        @Override
        public String getPassword() {
            return this.password;
        }
    
        @Override
        public String getUsername() {
            return this.username;
        }
    
        @JsonIgnore
        @Override
        public boolean isAccountNonExpired() {
            return true;
        }
    
        @JsonIgnore
        @Override
        public boolean isAccountNonLocked() {
            return true;
        }
    
        @JsonIgnore
        @Override
        public boolean isCredentialsNonExpired() {
            return true;
        }
    
        @JsonIgnore
        @Override
        public boolean isEnabled() {
            return true;
        }
    }
    
    

    SysRole

    注意重写的方法要写对。

    public class SysRole implements GrantedAuthority {
        private Integer id;
        private String roleName;
        private String roleDesc;
    
        @JsonIgnore
        @Override
        public String getAuthority() {
            return null;
        }
    
        public Integer getId() {
            return id;
        }
    
        public void setId(Integer id) {
            this.id = id;
        }
    
        public String getRoleName() {
            return roleName;
        }
    
        public void setRoleName(String roleName) {
            this.roleName = roleName;
        }
    
        public String getRoleDesc() {
            return roleDesc;
        }
    
        public void setRoleDesc(String roleDesc) {
            this.roleDesc = roleDesc;
        }
    
    }
    
    

    service

    接口

    public interface UserService extends UserDetailsService {
    }
    

    实现类

    @Service
    public class UserServiceImpl implements UserService {
    
        @Autowired
        private UserMapper userMapper;
    
        @Override
        public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
            return userMapper.findByName(username);
        }
    }
    

    Mapper

    public interface UserMapper extends Mapper<SysUser> {
    
        @Select("select * from sys_user where username = #{username}")
        @Results({
                @Result(id = true, property = "id", column = "id"),
                @Result(property = "roles", column = "id", javaType = List.class,
                    many = @Many(select = "com.wj.springsecurity.mapper.RoleMapper.findByUid"))
        })
        public SysUser findByName(String username);
    }
    
    public interface RoleMapper extends Mapper<SysRole> {
    
        @Select("select r.id,r.role_name as roleName,r.role_desc as roleDesc " +
                "from sys_role r , sys_user_role ur " +
                "where uid = #{uid} and r.id = ur.rid")
        public List<SysRole> findByUid(Integer uid);
    }
    

    权限控制

    在controller层:

    @Controller
    @RequestMapping("/product")
    public class ProductController {
    
        @Secured({"ROLE_USER"})
        @RequestMapping("/findAll")
        public String findAll(){
            return "product-list";
        }
    }
    

    我这里踩了一个坑,权限必须要是"ROLE_"开头,否则会有问题。

    启动项目

    点击m按钮

    image-20201005131707813

    输入:spring-boot:run,按下enter键

    image-20201005131803585

    运行成功

    进入http://localhost:8080/login.jsp

    image-20201005131836837

    用户名:wj

    密码:1234

    image-20201005131911780

    如果能进入系统,说明搭建整合成功。

    点击产品管理,能进入产品管理界面,则权限控制成功。

    image-20201005202258253

  • 相关阅读:
    <c:forTokens/>标签
    小小的心得
    wordcount编写和提交集群运行问题解决方案
    全国主要城市空气质量
    模拟迁途箭头圆圈
    模拟迁途.html
    大规模markpoint特效
    hadoop例子程序:求圆周率和wordcount
    测试
    hadoop集群安装好之后的启动操作
  • 原文地址:https://www.cnblogs.com/wwjj4811/p/13769782.html
Copyright © 2020-2023  润新知