Springboot整合SpringSecurity实现登录验证

SpringSecurity


简介

Spring Security是针对Spring项目的安全框架,也是Springboot底层安全模块默认的技术选型,他可以实现强大的Web安全控制,对于安全控制,我么仅需要引入spring-boot-starter-security模块,进行少量的配置,即可实现强大的安全管理。

记住几个类:

- WebSecurityConfigurerAdapter:自定义Security策略
- AuthenticationManagerBuilder:自定义认证策略
- @EnableWebSecurity:开启WebSecurity模式

Spring Security的两个主要目标是认证和授权。

代码

引入maven

    <dependencies>
            <dependency>
                <groupId>org.springframework.bootgroupId>
                <artifactId>spring-boot-starter-securityartifactId>
            dependency>
            <dependency>
                <groupId>org.springframework.bootgroupId>
                <artifactId>spring-boot-starter-thymeleafartifactId>
            dependency>
            <dependency>
                <groupId>org.thymeleaf.extrasgroupId>
                <artifactId>thymeleaf-extras-springsecurity5artifactId>
                <version>3.0.4.RELEASEversion>
            dependency>
            <dependency>
                <groupId>org.springframework.bootgroupId>
                <artifactId>spring-boot-starter-webartifactId>
            dependency>
    dependencies>

Controller实现页面跳转

    @Controller
    public class RouterController {
    
        @RequestMapping({"/", "/index"})
        public String index() {
            return "index";
        }
    
        @RequestMapping("/toLogin")
        public String toLogin() {
            return "views/login";
        }
    
        @RequestMapping("/level1/{id}")
        public String level1(@PathVariable("id") int id) {
            return "views/level1/" + id;
        }
    
        @RequestMapping("/level2/{id}")
        public String level2(@PathVariable("id") int id) {
            return "views/level2/" + id;
        }
    
        @RequestMapping("/level3/{id}")
        public String level3(@PathVariable("id") int id) {
            return "views/level3/" + id;
        }
    }

自定义SecurityConfig类

    @EnableWebSecurity
    public class SecurityConfig extends WebSecurityConfigurerAdapter {
    
        //授权
        @Override
        protected void configure(HttpSecurity http) throws Exception {
            //首页所有人都可以访问,功能页只有对应有权限的人才能访问
            //请求授权的规则
            http.authorizeRequests().antMatchers("/").permitAll()
                    .antMatchers("/level1/**").hasRole("vip1")
                    .antMatchers("/level2/**").hasRole("vip2")
                    .antMatchers("/level3/**").hasRole("vip3");
    
            //开启默认登录页面
          	//定制登录页
            http.formLogin().loginPage("/toLogin").usernameParameter("username")
                    .passwordParameter("password").loginProcessingUrl("/login");
    
            //开启注销功能,跳到首页
            http.csrf().disable();//关闭csrf功能,登录失败可能存在的问题
            http.logout().logoutSuccessUrl("/");
    
            //开启记住我功能,cookie默认保存两周,自定义接收前端的参数
            http.rememberMe().rememberMeParameter("remeber");
        }
    
        //认证
        //密码编码:PasswordEncoder
        //在Spring Security5.0+ 新增了很多加密方法
        @Override
        protected void configure(AuthenticationManagerBuilder auth) throws Exception {
            auth.inMemoryAuthentication().passwordEncoder(new BCryptPasswordEncoder())
                    .withUser("wangwu").password(new BCryptPasswordEncoder().encode("123456")).roles("vip1")
                    .and()
                    .withUser("zhangsan").password(new BCryptPasswordEncoder().encode("123456")).roles("vip1", "vip2")
                    .and()
                    .withUser("lisi").password(new BCryptPasswordEncoder().encode("123456")).roles("vip1", "vip2",
                    "vip3");
        }
    }

引入

xmlns:sec="https://www.thymeleaf.org/thymeleaf-extras-springsecurity5"

实现前端验证

    
    <div sec:authorize="!isAuthenticated()">
        <h2 align="center"><a th:href="@{/login}">请登录a>h2>
    div>
    
    <div sec:authorize="isAuthenticated()">
        <h2 align="center"><a th:href="@{/logout}">注销a>h2>
    div>
    <div sec:authorize="isAuthenticated()">
        用户名:<span sec:authentication="name">span>
        权限:<span sec:authentication="principal.authorities">span>
    div>
    
    <div sec:authorize="hasRole('')">
    div>
    ```



你可能感兴趣的:(Spring)