集成SpringSecurity

Spring Security是一个功能强大且高度可定制的身份验证和访问控制框架。它实际上是保护基于spring的应用程序的标准。

Spring Security是一个框架,侧重于为Java应用程序提供身份验证和授权。与所有Spring项目一样,Spring安全性的真正强大之处在于它可以轻松地扩展以满足定制需求。


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

记住几个类:

WebSecurityConfigurerAdapter:自定义Security策略

AuthenticationManagerBuilder:自定义认证策略

@EnableWebSecurity:开启WebSecurity模式

Spring Security的两个主要目标是 “认证” 和 “授权”(访问控制)。

“认证”(Authentication)

身份验证是关于验证您的凭据,如用户名/用户ID和密码,以验证您的身份。

身份验证通常通过用户名和密码完成,有时与身份验证因素结合使用。

“授权” (Authorization)

授权发生在系统成功验证您的身份后,最终会授予您访问资源(如信息,文件,数据库,资金,位置,几乎任何内容)的完全权限。

这个概念是通用的,而不是只在Spring Security 中存在。

认证和授权

引入 Spring Security 模块:

<dependency>
     <groupId>org.springframework.boot</groupId>
     <artifactId>spring-boot-starter-security</artifactId>
 </dependency>

编写基础配置类:

@EnableWebSecurity // 开启WebSecurity模式
public class SecurityConfig extends WebSecurityConfigurerAdapter {

    //链式编程
    //授权
    @Override
    protected void configure(HttpSecurity http) throws Exception {
    }

    //认证,
    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {

    }
}

定制请求的授权规则:

//链式编程
    //授权
    @Override
    protected void configure(HttpSecurity http) throws Exception {
        //首页所有人可以访问,但是功能页只有对应有权限的人才能访问
        //请求授权的规则
        http.authorizeRequests()
                .antMatchers("/").permitAll()
                .antMatchers("/level1/**").hasRole("vip1")
                .antMatchers("/level2/**").hasRole("vip2")
                .antMatchers("/level3/**").hasRole("vip3");
	}

在configure()方法中加入以下配置,开启自动配置的登录功能!:

// 开启自动配置的登录功能
// /login 请求来到登录页
// /login?error 重定向到这里表示登录失败
	http.formLogin();

测试一下:发现,没有权限的时候,会跳转到登录的页面!
定义认证规则,重写configure(AuthenticationManagerBuilder auth)方法

//认证,
    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        //这些数据正常应该从数据库中得到
        auth.inMemoryAuthentication()
                .withUser("benti").password("123456").roles("vip2","vip3")
                .and()
                .withUser("root").password("123456").roles("vip1","vip2","vip3");
    }

测试,我们可以使用这些账号登录进行测试!发现会报错!
原因,我们要将前端传过来的密码进行某种方式加密,否则就无法登录,修改代码:

//认证,
    //密码编码:PasswordEncoder
    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        //这些数据正常应该从数据库中得到
        auth.inMemoryAuthentication()
                .passwordEncoder(new BCryptPasswordEncoder())
                .withUser("benti").password(new BCryptPasswordEncoder().encode("123456")).roles("vip2","vip3")
                .and()
                .withUser("root").password(new BCryptPasswordEncoder().encode("123456")).roles("vip1","vip2","vip3");
    }

权限控制和注销:

开启自动配置的注销的功能:

//定制请求的授权规则
@Override
protected void configure(HttpSecurity http) throws Exception {
   //....
   //开启自动配置的注销的功能
      // /logout 注销请求
   http.logout();
}

我们在前端,增加一个注销的按钮,index.html 导航栏中:

<a class="item" th:href="@{/logout}">
   <i class="address card icon"></i> 注销
</a>

测试一下,登录成功后点击注销,发现注销完毕会跳转到登录页面!
想让他注销成功后,依旧可以跳转到首页:

// .logoutSuccessUrl("/"); 注销成功来到首页
http.logout().logoutSuccessUrl("/");

用户没有登录的时候,导航栏上只显示登录按钮,用户登录之后,导航栏可以显示登录的用户信息及注销按钮!还有就是,比如kuangshen这个用户,它只有 vip2,vip3功能,那么登录则只显示这两个功能,而vip1的功能菜单不显示!
我们需要结合thymeleaf中的一些功能
添加整合依赖:

<!--注意这里使用thymeleaf-extras-springsecurity5 否则会出错-->
<dependency>
   <!--thymeleaf   springsecurity-->
   <groupId>org.thymeleaf.extras</groupId>
   <artifactId>thymeleaf-extras-springsecurity5</artifactId>
   <version>3.0.4.RELEASE</version>
</dependency>

修改我们的 前端页面
导入命名空间:

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

修改导航栏,增加认证判断:

<div class="right menu">
   <!--未登录-->
   <div sec:authorize="!isAuthenticated()">
      <a class="item" th:href="@{/tologin}">
      <i class="address card icon"></i> 登录
      </a>
   </div>
   <!--已登录 显示用户名和角色名  -->
      <div sec:authorize="isAuthenticated()">
       <a class="item">
          用户名:<span sec:authentication="principal.username"></span>
          角色:<span sec:authentication="principal.authorities"></span><!--获取权限-->
       </a>
      </div>
   !--已登录 显示注销  -->
     <div sec:authorize="isAuthenticated()">
         <a class="item" th:href="@{/tologin}">
           <i class="address card icon"></i> 注销
        </a>
    </div>     
 </div>

如果注销404了,就是因为它默认防止csrf跨站请求伪造,因为会产生安全问题,我们可以将请求改为post表单提交,或者在spring security中关闭csrf功能;我们试试:在 配置中增加 http.csrf().disable();

http.csrf().disable();//关闭csrf功能:跨站请求伪造,默认只能通过post方式提交logout请求
http.logout().logoutSuccessUrl("/");

角色功能块认证:

<div class="ui three column stackable grid">
       <!--  菜单根据用户角色动态实现  -->
    <div class="column" sec:authorize="hasRole('vip1')"><!--如果有vip1权限就显示这个,没有就隐藏-->
               ···············`···
    </div>

    <div class="column" sec:authorize="hasRole('vip2')">
        ··················
   </div>

   <div class="column" sec:authorize="hasRole('vip3')">
            ··············
    </div>
 </div>

开启记住我功能:

//定制请求的授权规则
@Override
protected void configure(HttpSecurity http) throws Exception {

   //开启记住我功能  cookie  默认保存两周  自定义接收前端参数
   http.rememberMe().rememberMeParameter("remember");
}
<div class="field">
    <input type="checkbox" name="remember">记住我
</div>

登录成功后,将cookie发送给浏览器保存,以后登录带上这个cookie,只要通过检查就可以免登录了。如果点击注销,则会删除这个cookie


**

定制登录页

**
现在这个登录页面都是spring security 默认的,怎么样可以使用我们自己写的Login界面呢?

在刚才的登录页配置后面指定 loginpage:

//定制登录页面:loginPage("/tologin");
  //设置登录请求的url路径。:loginProcessingUrl("/login")
  //自定义用户名和密码参数:usernameParameter("username")     passwordParameter("password")
   http.formLogin().loginPage("/tologin").usernameParameter("username").passwordParameter("password").loginProcessingUrl("/login");

完整代码:

@EnableWebSecurity // 开启WebSecurity模式
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");

        //没有权限跳转到登录页面,需要开启登录的页面
        //login
        //定制登录页面:loginPage("/tologin");
        //设置登录请求的url路径。:loginProcessingUrl("/login")
        //自定义用户名和密码参数:usernameParameter("username")     passwordParameter("password")
        http.formLogin().loginPage("/tologin").usernameParameter("username").passwordParameter("password").loginProcessingUrl("/login");

        //开启注销功能
        //防止网站攻击,
        http.csrf().disable(); //关闭csrf功能   登出失败可能的原因
        http.logout().logoutSuccessUrl("/");

        //开启记住我功能  cookie  默认保存两周  自定义接收前端参数
        http.rememberMe().rememberMeParameter("remember");
    }

    @Autowired
    private DataSource dataSource;

    //认证,
    //密码编码:PasswordEncoder
    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {

        //这些数据正常应该从数据库中得到
        auth.inMemoryAuthentication()
                .passwordEncoder(new BCryptPasswordEncoder())
                .withUser("benti").password(new BCryptPasswordEncoder().encode("123456")).roles("vip2","vip3")
                .and()
                .withUser("root").password(new BCryptPasswordEncoder().encode("123456")).roles("vip1","vip2","vip3");

//           PasswordEncoder users = PasswordEncoderFactories.createDelegatingPasswordEncoder();
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值