zoukankan      html  css  js  c++  java
  • SpringSecurity整合SpringBoot

    pom.xml

        <dependencies>
            <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>
                <version>5.1.47</version>
            </dependency>
            <dependency>
                <groupId>tk.mybatis</groupId>
                <artifactId>mapper-spring-boot-starter</artifactId>
                <version>2.1.5</version>
            </dependency>
        </dependencies>

     yaml文件

    server:
      port: 8080
    spring:
      mvc:
        view:
          prefix: /pages/
          suffix: .jsp
      datasource:
        driver-class-name: com.mysql.jdbc.Driver
        url: jdbc:mysql:///security_authority
        username: root
        password: 123456
    mybatis:
      type-aliases-package: com.topcheer.domain
      configuration:
        map-underscore-to-camel-case: true
    logging:
      level:
        com.itheima: debug

    异常处理类:

    @ControllerAdvice
    public class HandlerControllerException {
    
        @ExceptionHandler(RuntimeException.class)
        public String handException(RuntimeException e){
            if(e instanceof AccessDeniedException){
                return "redirect:/403.jsp";
            }
            return "redirect:/500.jsp";
        }
    }

     配置类:

    @Configuration
    @EnableWebSecurity
    @EnableGlobalMethodSecurity(securedEnabled=true)
    public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
    
        @Autowired
        private UserService userService;
    
        @Bean
        public BCryptPasswordEncoder passwordEncoder(){
            return new BCryptPasswordEncoder();
        }
    
        //指定认证对象的来源
        @Override
        public void configure(AuthenticationManagerBuilder auth) throws Exception {
            auth.userDetailsService(userService).passwordEncoder(passwordEncoder());
        }
        //SpringSecurity配置信息
        @Override
        public void configure(HttpSecurity http) throws Exception {
            http.authorizeRequests()
                    .antMatchers("/login.jsp", "failer.jsp", "/css/**", "/img/**", "/plugins/**").permitAll()
                    .antMatchers("/product").hasAnyRole("USER")
                    .anyRequest().authenticated()
                    .and()
                    .formLogin()
                    .loginPage("/login.jsp")
                    .loginProcessingUrl("/login")
                    .successForwardUrl("/index.jsp")
                    .failureForwardUrl("/failer.jsp")
                    .and()
                    .logout()
                    .logoutSuccessUrl("/logout")
                    .invalidateHttpSession(true)
                    .logoutSuccessUrl("/login.jsp")
                    .and()
                    .csrf()
                    .disable();
        }
    }

     服务类:

    @Service
    @Transactional
    public class UserServiceImpl implements UserService {
    
        @Autowired
        private UserMapper userMapper;
    
        @Override
        public UserDetails loadUserByUsername(String s) throws UsernameNotFoundException {
            return userMapper.findByName(s);
        }
    
    }
    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.topcheer.mapper.RoleMapper.findByUid"))
        })
        public SysUser findByName(String username);
    
    }

    web层

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

    启动类:

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

    实体类

    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 Integer getId() {
            return id;
        }
    
        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 Integer getStatus() {
            return status;
        }
    
        public void setStatus(Integer status) {
            this.status = status;
        }
    
        @JsonIgnore
        @Override
        public Collection<? extends GrantedAuthority> getAuthorities() {
            return roles;
        }
    
        @Override
        public String getPassword() {
            return password;
        }
    
        @Override
        public String getUsername() {
            return 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;
        }
    }
    public class SysRole implements GrantedAuthority {
    
        private Integer id;
        private String roleName;
        private String roleDesc;
    
        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;
        }
    
        @JsonIgnore
        @Override
        public String getAuthority() {
            return roleName;
        }
    }

    当没有权限的时候,被异常捕获到

  • 相关阅读:
    has a / is a 的区别
    Linux头文件作用
    转一篇Decorator模式的讲解文章
    歌手推荐kate st. john
    拷贝构造函数和赋值构造函数声明为私有的作用
    重新认识C++中new的用法
    系统程序员成长计划容器与算法(二)(下)
    深入C++的new
    歌手推荐Cara Dillon
    浅析一道C++设计面试题
  • 原文地址:https://www.cnblogs.com/dalianpai/p/12410741.html
Copyright © 2011-2022 走看看