Spring Security详解

一、系统安全

在Web开发中,我们在设计之初就需要考虑系统安全的方面,而不是把功能全部实现完成后,再去考虑。那样的话就会造成两难的境地:一方面,应用会存在严重的漏洞,无法满足用户需求,并可能造成用户信息被攻击者窃取;另一方面,应用的基本架构已经确定,想要修复安全漏洞,可能需要对系统做出较大的调整,因此,耗费大量的人力和物力,因此,我们应该从系统开始做的第一天就应该把安全策略考虑进去,并贯穿在整个应用开发过程中。
目前比较有名的框架有:Shiro,Spring Security
下面我们来了解并实践一下Spring Security

Spring Security官网:https://docs.spring.io/spring-security/site/docs/5.3.13.RELEASE

二、Spring Security简介

Spring Security是一个提供认证、授权和防止常见攻击的框架。

Spring Security 基于 Spring 框架,提供了一套 Web 应用安全性的完整解决方案。一般来说,Web 应用的安全性包括用户认证(Authentication)和用户授权(Authorization)两个部分。用户认证指的是验证某个用户是否为系统中的合法主体,也就是说用户能否访问该系统。用户认证一般要求用户提供用户名和密码。系统通过校验用户名和密码来完成认证过程。用户授权指的是验证某个用户是否有权限执行某个操作。在一个系统中,不同用户所具有的权限是不同的。比如对一个文件来说,有的用户只能进行读取,而有的用户可以进行修改。一般来说,系统会为不同的用户分配不同的角色,而每个角色则对应一系列的权限。

对于上面的情况Spring Security框架都有很好的支持。

在用户认证方面,Spring Security 框架支持主流的认证方式,包括 HTTP 基本认证、HTTP 表单验证、HTTP 摘要认证、OpenID 和 LDAP 等。在用户授权方面,Spring Security 提供了基于角色的访问控制和访问控制列表(Access Control List,ACL),可以对应用中的领域对象进行细粒度的控制。

三、案例

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

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

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

“认证”(Authentication)

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

“授权” (Authorization)

授权发生在系统成功验证您的身份后,最终会授予您访问资源(如信息,文件,数据库等)的完全权限。

1、新建模块

在这里插入图片描述

2、导入静态资源

在这里插入图片描述

3、编写控制器,实现跳转

@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;
    }
}

4、安全功能实现

如果不加入认证和授权功能,我们写的应用是谁都可以访问的,因此我们需要使用Spring Security 增加上认证和授权的功能。
官方文件:https://docs.spring.io/spring-security/site/docs/5.2.15.RELEASE/reference/html5/#jc-authentication

认证和授权

1、编写配置类

    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.inMemoryAuthentication().passwordEncoder(new BCryptPasswordEncoder())
                .withUser("cwy").password(new BCryptPasswordEncoder().encode("123123")).roles("vip2","vip3")
                .and()
                .withUser("root").password(new BCryptPasswordEncoder().encode("123123")).roles("vip1","vip2","vip3")
                .and()
                .withUser("guest").password(new BCryptPasswordEncoder().encode("123123")).roles("vip1");

        //There is no PasswordEncoder mapped for the id "null"

    }

通过内存的方式 创建账户,并且给账户对应的授权角色

权限控制和注销

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

为每一个访问请求分配访问权限,限制用户角色访问。这就是权限控制。
注销功能实现起来也非常简单

        //注销功能
        http.logout().logoutSuccessUrl("/login");

在index页面

<!--注销-->
<a class="item" th:href="@{/logout}">
    <i class="sign-out icon"></i> 注销
</a>

注销后返回登入页面

记住我

 //开启记住我功能
 http.rememberMe().rememberMeParameter("remember" );

在登入界面中

 <div class="field">
     <input type="checkbox" name="remember">记住我
 </div>
 <input type="submit" class="ui blue submit button"/>

记住我功能就是利用cookies来实现的

完整配置类

@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
    /**
     * 授权的
     * @param http
     * @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");

        //没有权限,默认到登录页面
        http.formLogin().loginPage("/tologin").usernameParameter("user").passwordParameter("pwd").loginProcessingUrl("/login");

        //防止网站攻击
        http.csrf().disable();关闭csrf功能:跨站请求伪造,默认只能通过post方式提交logout请求
        //注销功能
        http.logout().logoutSuccessUrl("/login");
        //开启记住我功能
        http.rememberMe().rememberMeParameter("remember" );
    }

    /**
     * 认证的
     * @param auth
     * @throws Exception
     */
    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
    //在内存中定义,也可以再jdbc拿数据
        auth.inMemoryAuthentication().passwordEncoder(new BCryptPasswordEncoder())
                .withUser("cwy").password(new BCryptPasswordEncoder().encode("123123")).roles("vip2","vip3")
                .and()
                .withUser("root").password(new BCryptPasswordEncoder().encode("123123")).roles("vip1","vip2","vip3")
                .and()
                .withUser("guest").password(new BCryptPasswordEncoder().encode("123123")).roles("vip1");

        //There is no PasswordEncoder mapped for the id "null"

    }
}

我们需要结合thymeleaf中的一些功能

sec:authorize=“isAuthenticated()”:是否认证登录!来显示不同的页面

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值