让Spring Security 来保护你的Spring Boot项目吧

参考资料:

Spring Security 简介

Spring Security是一个能够为基于Spring的企业应用系统提供声明式的安全访问控制解决方案的安全框架。它提供了一组可以在Spring应用上下文中配置的Bean,充分利用了Spring IoC,DI(控制反转Inversion of Control ,DI:Dependency Injection 依赖注入)和AOP(面向切面编程)功能,为应用系统提供声明式的安全访问控制功能,减少了为企业系统安全控制编写大量重复代码的工作。

配置类大概讲解

当Spring Securiy 还是Acegi Security的时候,使用就需要大量的xml配置,典型的Acegi配置有几百行xml是很常见的。

到了2.0版本,Acegi Security 更名为Spring Security。不仅名字换了,还引入了一个全新的、与安全性相关的xml命名空间。使得xml配置从几百行减少到十几行

Spring Security 3.0融入SpEL 进一步简化了安全性的配置。

Spring Security 5.0 今年刚发布

这里不介绍xml的配置,只讲述java配置(官方说这种方式最简洁)

开始之前加入依赖:

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

扩展WebSecurityConfigurerAdapter类

@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {


    //身份验证管理生成器
    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
    }
    //HTTP请求安全处理
    @Override
    protected void configure(HttpSecurity http) throws Exception {

    }
    //WEB安全
    @Override
    public void configure(WebSecurity web) throws Exception {
    }

学习一门新知识的最好的方法就是看源码,按住ctrl 移动鼠标到WebSecurityConfigurerAdapter点击查看源码。

我们首先介绍

//身份验证管理生成器
    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
    }

的重写。

选择查询用户详细信息的服务

@Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        //1.启用内存用户存储
//        auth.inMemoryAuthentication()
//                .withUser("xfy").password(passwordEncoder().encode("1234")).roles("ADMIN").and()
//                .withUser("tom").password(passwordEncoder().encode("1234")).roles("USER");
        //2.基于数据库表进行验证
//        auth.jdbcAuthentication().dataSource(dataSource)
//                .usersByUsernameQuery("select username,password,enabled from user where username = ?")
//                .authoritiesByUsernameQuery("select username,rolename from role where username=?")
//                .passwordEncoder(passwordEncoder());
        //3.配置自定义的用户服务
        auth.userDetailsService(myUserDetailService);
    }

启用内存用户处理和基于数据库表验证都要完全依赖于框架本身的验证逻辑。本人推荐第三种配置自定义的用户服务。

实现security官方的UserDetailsService

源码:

package org.springframework.security.core.userdetails;

public interface UserDetailsService {
    UserDetails loadUserByUsername(String var1) throws UsernameNotFoundException;
}

自己创建实现类

import com.young.security.mysecurity.pojo.Role;
import com.young.security.mysecurity.pojo.User;
import com.young.security.mysecurity.repository.RoleRepository;
import com.young.security.mysecurity.repository.UserRepository;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationCredentialsNotFoundException;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;

/**
 * Create by stefan
 * Date on 2018-05-17  22:49
 * Convertion over Configuration!
 */
@Component
@Slf4j
public class MyUserDetailService implements UserDetailsService {
    @Autowired
    private PasswordEncoder passwordEncoder;
    @Autowired
    UserRepository userRepository;
    @Autowired
    private RoleRepository roleRepository;
    @Override
    public UserDetails loadUserByUsername(String name) throws UsernameNotFoundException {
        User user = userRepository.findByUsername(name);
        if (user==null){
            throw new AuthenticationCredentialsNotFoundException("authError");
        }
        log.info("{}",user);
        List<Role> role = roleRepository.findByUsername(name);
        log.info("{}",role);
        List<GrantedAuthority> authorities = new ArrayList<>();
        role.forEach(role1 -> authorities.addAll(AuthorityUtils.commaSeparatedStringToAuthorityList("ROLE_"+role1.getRolename())));
        log.info("{}",authorities);
        return new org.springframework.security.core.userdetails.User(user.getUsername(),user.getPassword(),authorities);
    }
}

任何关于数据库的业务这里不做解释。详情请看源码。

需要注意的是 Security默认使用了密码加密保护,我们配置密码转换器申明使用什么加密方式。这里推荐BCryptPassword,同样是5.0的推荐。

在刚才配置类SecurityConfig中配置

    @Bean
    public static PasswordEncoder passwordEncoder() {
        return new BCryptPasswordEncoder();
    }

查看源码encode()这个方法是加密,matches()是判断加密密码与输入框明文密码是否一致。

拦截请求

接下来,我们看看

 @Override
       protected void configure(HttpSecurity http){
            super.configure(http);
       }

默认配置是

protected void configure(HttpSecurity http) throws Exception {
    http
        .authorizeRequests()
            .anyRequest().authenticated()
            .and()
        .formLogin()
            .and()
        .httpBasic();
}

自己修改后的配置

@Override
    protected void configure(HttpSecurity http) throws Exception {
        http.formLogin().loginPage("/signIn").loginProcessingUrl("/user/userLogin")
                .and()
                .logout().logoutUrl("/logout")
                .and()
                .authorizeRequests()
                .antMatchers("/signIn","/hello").permitAll()
                .antMatchers("/index").authenticated()
                .antMatchers("/admin/**","/add").hasRole("ADMIN")
                .regexMatchers("/admin1/.*").access("hasRole('ADMIN') or hasRole('ADMIN1')")
                .anyRequest().authenticated()
                .and()
                .requiresChannel().antMatchers("/add").requiresSecure()//https://127.0.0.1:8443/add
                .and()
                .rememberMe().tokenValiditySeconds(2419200).tokenRepository(persistentTokenRepository());

    }

spring security 的拦截语法

我们首先调用authorizeRequests(),然后调用该方法所返回的对象的方法来配置请求级别的安全性细节。

antMatchers的使用(Ant风格的通配符):

指定一个路径
antMatchers("/index")

指定多个路径
antMatchers("/admin/**","/add")

指定请求方式
antMatchers(HttpMethod.POST,"/add")

与之相似的还有一个regexMatchers,接收正则表达式来定义请求路径。

regexMatchers("/admin1/.*")

路径选择好之后我们就要保护路径了。如下表:

《让Spring Security 来保护你的Spring Boot项目吧》 image

注意:这些规则是按配置的先后顺序发挥作用的,所以将具体的请求路径放在前面,而越来越不具体的放在后面,如果不这样的话,不具体的路径配置会覆盖掉更为具体的路径配置。

使用spring 表达式进行安全保护

hasRole()一次仅仅只能限制角色,倘若我们还要同时限制ip地址的权限不好配置了。
这里我们可以使用SpEL 作为声明访问限制的一种,具体使用如下

.regexMatchers("/admin1/.*").access("hasRole('ADMIN') or hasRole('ADMIN1')")

显然access()这种方式更为强大。

强制通道的安全性

现在大部分网路传输都用HTTPS,
将请求变为HTTPS很简单

.requiresChannel().antMatchers("/add").requiresSecure()//https://127.0.0.1:8443/add

当请求http://127.0.0.1:8080/add,security会自动跳转到https://127.0.0.1:8443/add进行加密请求。

防止跨站请求伪造

从Security3.2开始,默认就会启用CSPF防护。可以关闭,也可以在表单中做一些改动。

.csrf().disable()  禁用CSRF防护功能。

为了安全,本人建议启用CSRF防护,在表单中做改动。也很简单在表单中加一个<input>

在freemarker页面form表单中添加

 <input type="hidden" name="${_csrf.parameterName}" value="${_csrf.token}"/>

更具体关于CSRF的知识请自行查找资料。

认证用户

添加自定义的登录页

security默认是提供了一个登陆页面,但是并不能满足我们的要求。我们可以自定义登陆页。

.formLogin().loginPage("/signIn").loginProcessingUrl("/user/userLogin")

对应视图页面:

<html>
<head>
    <meta charset="UTF-8"/>
    <title>login</title>
</head>
<body>
<form action="/user/userLogin" method="post">
    username:<input type="text" name="username"/><br/>
    password:<input type="password" name="password"/><br/>
    <input type="hidden" name="${_csrf.parameterName}" value="${_csrf.token}"/>
    <input type="submit" value="登录">
    <input name="remember-me" type="checkbox">
</form>
</body>
</html>

/user/userLogin这个路由的controller我们无需定义。

启用Remember-me 功能

示例:

//存在cookie,并限定过期时间
 .rememberMe().tokenValiditySeconds(2419200)

记住功能,我们可以把用户信息存在cookie,也可以存在数据库。

要想存在数据库,如下配置,

.rememberMe().tokenValiditySeconds(2419200).tokenRepository(persistentTokenRepository());
@Bean
    public PersistentTokenRepository persistentTokenRepository() {
        JdbcTokenRepositoryImpl tokenRepository = new JdbcTokenRepositoryImpl();
        tokenRepository.setDataSource(dataSource);
        //tokenRepository.setCreateTableOnStartup(true);
        return tokenRepository;
    }

第一次运行
tokenRepository.setCreateTableOnStartup(true);会在数据库自动建立一张表,再次运行时请注释掉,否则会报错。

《让Spring Security 来保护你的Spring Boot项目吧》 image

要想启动Remember-me功能还需要在登录表单中改动

<input name="remember-me" type="checkbox">记住我

name=”remember-me”是固定的。

当然也可以不需要改动前端页面,可以在配置类直接开启记住功能(.alwaysRemember(true)),强制让用户记住。

.rememberMe().tokenValiditySeconds(2419200).tokenRepository(persistentTokenRepository()).alwaysRemember(true);

退出

 .logout().logoutSuccessUrl("/signIn")

开启csrf防护的logout默认是post请求。

<form action="/logout" method="post">
    <input type="hidden" name="${_csrf.parameterName}" value="${_csrf.token}"/>
    <input type="submit" value="注销"/>
</form>

保护视图

为了测试视图保护标签,不得不换了Thymeleaf ,毕竟人家是官方认可的,freemarker虽然好用但是毕竟是屌丝出身,虽说能用jsp的标签库,但是搜集了很多资料依然没弄明白怎么配置,只好用Thymeleaf。

使用Thymeleaf的Spring Security方言

书上还给了一个配置bean 声明SringTemplateEnginebean。但是我试验了,不用配置也可以。

只需两步:
导入依赖:

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

        <dependency>
            <groupId>org.thymeleaf.extras</groupId>
            <artifactId>thymeleaf-extras-springsecurity4</artifactId>
        </dependency>

第二步:
声明使用 sec标签

<html xmlns:th="http://www.thymeleaf.org" xmlns:sec="http://www.thymeleaf.org/extras/spring-security">

示例:

<div sec:authorize="isAuthenticated()"> <!--sec:authorize属性会接受一个SpEL表达式  isAuthenticated() 只有用户已经进行认证了,才会渲染出内容。 -->
    hello <span sec:authentication="name">someone</span> !
</div>
<form th:action="@{/logout}" method="post">
    <input type="submit" value="注销"/>
</form>

<div sec:authorize="hasRole('ADMIN')">
    会员admin可见
</div>

<div sec:authorize="hasRole('ADMIN') or hasRole('ADMIN1')">
    会员admin\ADMIN1可见
</div>

<span sec:authorize-url="/admin/center">
    <a th:href="@{/admin/center}">admin中心</a>
</span>

<span sec:authorize-url="/admin1/index">
    <a th:href="@{/admin1/index}">admin1中心</a>
</span>

用途显而易见,这里就不讲了。

注解保护方式

为了更好的保护我们的应用,注解保护方法也是必要的。

Spring Security提供了三种不同的安全注解:

  • Spring Security 自带的@Secured 注解;
  • JSR-250的@RolesAllowed注解
  • 表达式驱动的注解,包括@PreAuthorize、@PostAuthorize、@PreFilter、@PostFilter

@Secured与@RolesAllowed注解使用基本类似,能够基于用户所授予的权限限制对方法的访问。

使用这些注解前先要开启相应注解,可同时开启

在配置类上加一个注解

@EnableGlobalMethodSecurity(securedEnabled = true,jsr250Enabled = true,prePostEnabled = true)
@Secured({"ADMIN","ADMIN1"})
@RolesAllowed({"ADMIN","ADMIN1"})

使用方式相似,RolesAllowed更正式
@PreAuthorize("hasRole('ADMIN') AND hasRole('ADMIN1')")  的string参数是一个SpEL表达式
@PreAuthorize("hasRole('ADMIN') and #user.username.length() <=6") 可获得参数
@PostAuthorize("returnObject.username == principal.username")  可获得返回值

过滤方法

@PostFilter("hasRole('ADMIN') || filterObject.username == principal.username")   这个可直接获得方法的返回值列表的单个元素filterObject,不需要加#
@PreFilter("hasRole('ADMIN') || #filterObject.endsWith('admin')")  加#filterObject可获得传入参数列表的单个元素

项目源码:

码云: 潇潇漓燃 / springboot_springsecurity

学习建议:

Spring Security的参考资料很难找,上述是我找到的比较全,比较好的资料。

笔记做的很简陋,怕是只有我自己能看的下去,仅供参考。

Spring Security 的用途远不止这些,还没做第三方登录的整合,各方面都是皮毛总结。

学任何一个新知识还需自己悟,慢慢啃。

    原文作者:韵呀
    原文地址: https://www.jianshu.com/p/6df285f30a79
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞