栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

SpringSecurity框架的使用

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

SpringSecurity框架的使用

1、准备SpringMVC的环境,搭建web工程​​​​​​​。

2、在web工程中加入SpringSecurity的依赖



    org.springframework.security
    spring-security-web
    4.2.10.RELEASE



    org.springframework.security
    spring-security-config
    4.2.10.RELEASE



    org.springframework.security
    spring-security-taglibs
    4.2.10.RELEASE

3、在web.xml配置文件中配置Filter过滤器

SpringSecurity使用的是过滤器Filter而不是拦截器Interceptor,意味着SpringSecurity能够管理的不仅仅是 SpringMVC 中的 handler 请求,还包含 Web 应用中所有请求。


    springSecurityFilterChain
    org.springframework.web.filter.DelegatingFilterProxy


    springSecurityFilterChain
    /*

DelegatingFilterProxy 初始化时需要到 IOC 容器查找一个 bean, 这个 bean 所在的 IOC 容器要看是谁扫描了 WebAppSecurityConfig。 

如果是 Spring 扫描了 WebAppSecurityConfig,那么 Filter 需要的 bean 就在 Spring 的 IOC 容器(ContextLoaderListener创建的SpringIOC容器)。 

如果是 SpringMVC 扫描了 WebAppSecurityConfig,那么 Filter 需要的 bean 就在 SpringMVC 的 IOC 容器(DispatcherServlet创建的SpringMVCIOC容器)。

​​​​​​​

因为两个容器,可以将两个容器合二为一,使所有的bean都存入springMVC容器中就可以扫描到了。

3、加入配置类

这个配置类一定要继承WebSecurityConfigurerAdapter。需要将这个类放到扫描包的下面才能将该类放入到spring容器中。

// 这个类一定要放在自动扫描的包下,要不然所有的配置都不会生效
@Configuration
// 启用web环境下权限控制的功能
@EnableWebSecurity
public class WebAppSecurityConfig extends WebSecurityConfigurerAdapter {
   
    @Override
    protected void configure(HttpSecurity security) throws Exception{
        // 与SpringSecurity环境下用户登录相关
    
    }

    @Override
    protected void configure(AuthenticationManagerBuilder builder) throws Exception {
        // 与SpringSecurity环境下请求授权相关

    }
}

到此为止的效果 

  1. 所有请求都被 SpringSecurity 拦截,要求登录才可以访问。  
  2. 静态资源也都被拦截,要求登录。 
  3. 登录失败有错误提示。

实验一:放行首页和静态资源

// 这个类一定要放在自动扫描的包下,要不然所有的配置都不会生效
@Configuration
// 启用web环境下权限控制的功能
@EnableWebSecurity
public class WebAppSecurityConfig extends WebSecurityConfigurerAdapter {
    @Override
    protected void configure(HttpSecurity security) throws Exception {
        security
                .authorizeRequests()        // 对请求进行授权
                .antMatchers("/index.jsp")  // 针对index.jsp路径进行授权
                .permitAll()                // 可以无条件访问
                .antMatchers("/layui/**")
                .permitAll()
                .and()
                // 注意一定要将范围小的放在前面,如果将anyrequest放在前面,就都被挡住了
                .authorizeRequests()        // 对请求进行授权
                .anyRequest()               // 任意请求
                .authenticated();           // 需要登录以后才可以访问
    }
}

效果:1⃣️对于已授权的index页面和静态样式可以直接显示。

            2⃣️对于其他请求,跳转到403被禁止页面。

实验二:未认证请求跳转到登录页并设置登录系统的账号、密码

@Override
protected void configure(HttpSecurity security) throws Exception {
    security
            .authorizeRequests() //对请求进行授权
            .antMatchers("/layui/**","/index.jsp") //使用 ANT 风格设置要授权的 URL 地 址
            .permitAll() //允许上面使用 ANT 风格设置的全部请求
            .anyRequest() //其他未设置的全部请求
            .authenticated() //需要认证
            .and()
            // 关于formLogin()的特殊说明
            // 指定登陆页面的同时会影响到:"提交登陆表单的地址"、"退出登录地址"、"登陆失败的地址"

            .formLogin() //设置未授权请求跳转到登录页面
            .loginPage("/index.jsp") //指定登录页
            .loginProcessingUrl("/do/login.html") // 指定提交按钮登陆表单的地址
            .usernameParameter("loginAcct") // 定制登录账号的请求参数名
            .passwordParameter("userPswd") // 定制登录密码的请求参数名
            .defaultSuccessUrl("/main.html") // 登录成功前往的地址
    ;
}

实验三:退出登录

1⃣️禁用CSRF功能的退出

<%--没有CSRF功能的退出--%>
退出


.and()
.csrf() // 禁用csrf功能
.disable()
.logout() // 开启退出功能
.logoutUrl("/do/logout.html") // 指定处理退出请求的URL地址
.logoutSuccessUrl("/index.jsp") // 退出成功后前往的地址

2⃣️没有禁用CSRF功能的退出

退出 .and() .logout() // 开启退出功能 .logoutUrl("/do/logout.html") // 指定处理退出请求的URL地址 .logoutSuccessUrl("/index.jsp") // 退出成功后前往的地址

实验四:基于角色或权限进行访问控制

用户通过角色或者权限访问资源

@Override
protected void configure(HttpSecurity security) throws Exception {
    security
            .authorizeRequests() //对请求进行授权
            .antMatchers("/layui/**","/index.jsp") //使用 ANT 风格设置要授权的 URL 地 址
            .permitAll() //允许上面使用 ANT 风格设置的全部请求
            .antMatchers("/level1/**")
            .hasRole("学徒")
            .antMatchers("/level2/**")
            .hasAuthority("内门弟子")
            .anyRequest() //其他未设置的全部请求
            .authenticated() //需要认证
            .and()
            // 关于formLogin()的特殊说明
            // 指定登陆页面的同时会影响到:"提交登陆表单的地址"、"退出登录地址"、"登陆失败的地址"
}

@Override
protected void configure(AuthenticationManagerBuilder builder) throws Exception {
    builder.inMemoryAuthentication() // 内存中完成账号密码的认证
            .withUser("tom")
            .password("123")
            .roles("ADMIN","学徒") // 指定当前用户的角色
            .and()
            .withUser("jerry")
            .password("456")
            .authorities("SAVE","EDIT","内门弟子") // 指定当前用户的权限
            ;
}

注意:角色和权限统一都被放到authorities中,为了区分role和authorities,要在角色前面加上“ROLE_”来区分角色和权限。在内存中完成账号和密码的认证的时候,会加上前缀,但是从数据库中查询到的用户信息、角色信息和权限信息需要自己手动组装,需要手动给角色前面加上“ROLE_”。

实验五:自定义 403 错误页面

.and()
.exceptionHandling() // 指定异常处理器
// .accessDeniedPage("/to/no/auth/page.html") // 访问被拒绝时前往handler指定的页面
// 当访问被拒绝时可以使用函数
.accessDeniedHandler(new AccessDeniedHandler() {
    @Override
    public void handle(HttpServletRequest request, HttpServletResponse response, AccessDeniedException e) throws IOException, ServletException {
        request.setAttribute("message","抱歉!您无法访问这个资源!javaweb");
        request.getRequestDispatcher("/WEB-INF/views/no_auth.jsp").forward(request,response);
    }
})
;

实验六:记住我-内存版(不重要)

.and()
.rememberMe()

实验七:记住我-数据库版(不重要)

1⃣️配置数据库

1⃣️配置依赖


    com.alibaba
    druid
    1.1.12





    mysql
    mysql-connector-java
    5.1.47


    org.springframework
    spring-orm
    4.3.20.RELEASE


2⃣️装配数据库


    
    
    
    




    

2⃣️WebAppSecurityConfig

protected void configure(HttpSecurity security) throws Exception {
    JdbcTokenRepositoryImpl tokenRepository = new JdbcTokenRepositoryImpl();
    tokenRepository.setDataSource(dataSource);

    security.tokenRepository(tokenRepository)

实验八:查询数据库完成认证

自定义数据库查询方式

1⃣️自建数据库

create table t_admin ( 
    id int not null auto_increment, 
    loginacct varchar(255) not null, 
    userpswd char(32) not null, 
    username varchar(255) not null, 
    email varchar(255) not null, 
    createtime char(19), 
    primary key (id) 
);

2⃣️重写MyUserDetailService类

@Component
public class MyUserDetailService implements UserDetailsService {
    @Autowired
    private JdbcTemplate jdbcTemplate;

    // 总目标:根据表单提交的用户名查询User对象,并装配角色、权限信息
    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        // 1、从数据库查询Admin对象
        String sql = "SELECt id,loginacct,userpswd,username,email,createtime FROM t_admin WHERe loginacct = ?";

        List list = jdbcTemplate.query(sql, new BeanPropertyRowMapper<>(Admin.class), username);
        Admin admin = list.get(0);

        // 2、 给Admin设置角色权限信息
        List authorities = new ArrayList<>();
        authorities.add(new SimpleGrantedAuthority("ROLE_ADMIN"));
        authorities.add(new SimpleGrantedAuthority("UPDATE"));

        // 3、把admin和authorities封装到UserDetail中
        String userpswd = admin.getUserpswd();
        return new User(username,userpswd,authorities);
    }
}

3⃣️装配userDetailsService对象

@Override
protected void configure(AuthenticationManagerBuilder builder) throws Exception {
    // 装配userDetailsService对象
    builder.userDetailsService(userDetailService);

    // builder.inMemoryAuthentication() // 内存中完成账号密码的认证
    //         .withUser("tom")
    //         .password("123")
    //         .roles("ADMIN","学徒") // 指定当前用户的角色
    //         .and()
    //         .withUser("jerry")
    //         .password("456")
    //         .authorities("SAVE","EDIT","内门弟子") // 指定当前用户的权限
    //         ;
}

实验九:整合到springMVC

上面都一样,不一样的是需要从数据库中查到admin以及其角色和权限,因为原始的admin对象中没有角色和权限信息,所以需要创建一个CrowdUserDetailsService类,实现UserDetailsService接口,其包含了admin的原始对象的账号密码和权限信息。然后在builder.userDetailsService(userDetailsService);

@Component
public class CrowdDetailUserService implements UserDetailsService {
    @Autowired
    private AdminService adminService;

    @Autowired
    private RoleService roleService;

    @Autowired
    private AuthService authService;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        // 1、根据账号名称查询Admin对象
        Admin admin = adminService.getAdminByLoginAcct(username);

        // 2、获取admin的id,根据id查询角色、权限信息
        List assignedRoleList = roleService.getAssignedRole(admin.getId());
        List authNameList = authService.getAssignedAuthNameByAdminId(admin.getId());

        // 3、创建集合对象用来存储
        ArrayList authorities = new ArrayList<>();

        // 4、存入角色信息
        for (Role role : assignedRoleList) {
            // 注意不要忘记加前缀
            String roleName = "ROLE_" + role.getName();

            SimpleGrantedAuthority simpleGrantedAuthority = new SimpleGrantedAuthority(roleName);

            authorities.add(simpleGrantedAuthority);
        }

        // 5、存入权限信息
        for (String  authName : authNameList) {
            SimpleGrantedAuthority simpleGrantedAuthority = new SimpleGrantedAuthority(authName);

            authorities.add(simpleGrantedAuthority);
        }

        // 6、封装SecurityAdmin对象
        SecurityAdmin securityAdmin = new SecurityAdmin(admin, authorities);

        return securityAdmin;
    }
}

实验十:设置角色和权限

1、在security的配置文件中进行权限设置

security
    .antMatchers("/admin/get/page.html")  // 对于某个路径映射的方法进行设置
    // .hasRole("经理")                    // 必须有“经理”这个角色才可以调用这个方法
    // .hasAuthority("user:get")          // 必须有“user:get”这个权限才可以调用
    .access("hasRole('经理') or hasAuthority('user:get')")
    // 也可以使用access语句进行设置

2、在方法中使用注解设置

1⃣️先在配置文件上面添加@EnableGlobalMethodSecurity(prePostEnabled = true)注解

// 启用全局方法权限控制功能,并且设置prePostEnabled=true,保证注解@PreAuthorize、@PostAuthorize、@PreFilter、@PostFilter等注解生效
@EnableGlobalMethodSecurity(prePostEnabled = true)
public class WebAppSecurityConfig extends WebSecurityConfigurerAdapter {

2⃣️在方法中使用@PreAuthorize()注解

@PreAuthorize("hasAuthority('user:save')")
@RequestMapping("/admin/save.html")
public String addAdmin(Admin admin){
    adminService.saveAdmin(admin);
    return "redirect:/admin/get/page.html?pageNum="+Integer.MAX_VALUE;
}

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/970936.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号