SpringSecurity

阿里云国内75折 回扣 微信号:monov8
阿里云国际,腾讯云国际,低至75折。AWS 93折 免费开户实名账号 代冲值 优惠多多 微信号:monov8 飞机:@monov6

SpringSecurity框架简介

  1. 1.1 概要

    1. Spring 是非常流行和成功的 Java 应用开发框架,Spring Security 正是 Spring 家族中的

      成员。Spring Security 基于 Spring 框架,提供了一套 Web 应用安全性的完整解决方

      案。

      正如你可能知道的关于安全方面的两个主要区域是“认证”和“授权”(或者访问控

      制),一般来说,Web 应用的安全性包括用户认证(Authentication)和用户授权

      (Authorization)两个部分,这两点也是 Spring Security 重要核心功能。

      (1)用户认证指的是:验证某个用户是否为系统中的合法主体,也就是说用户能否访问

      该系统。用户认证一般要求用户提供用户名和密码。系统通过校验用户名和密码来完成认

      证过程。通俗点说就是系统认为用户是否能登录

      (2)用户授权指的是验证某个用户是否有权限执行某个操作。在一个系统中,不同用户

      所具有的权限是不同的。比如对一个文件来说,有的用户只能进行读取,而有的用户可以

      进行修改。一般来说,系统会为不同的用户分配不同的角色,而每个角色则对应一系列的

      权限。通俗点讲就是系统判断用户是否有权限去做某些事情。

  2. 1.2 历史

    “Spring Security 开始于 2003 年年底,““spring 的 acegi 安全系统”。 起因是 Spring

    开发者邮件列表中的一个问题,有人提问是否考虑提供一个基于 spring 的安全实现。

    Spring Security 以“The Acegi Secutity System for Spring” 的名字始于 2013 年晚些

    时候。一个问题提交到 Spring 开发者的邮件列表,询问是否已经有考虑一个机遇 Spring

    的安全性社区实现。那时候 Spring 的社区相对较小(相对现在)。实际上 Spring 自己在

    2013 年只是一个存在于 ScourseForge 的项目,这个问题的回答是一个值得研究的领

    域,虽然目前时间的缺乏组织了我们对它的探索。

    考虑到这一点,一个简单的安全实现建成但是并没有发布。几周后,Spring 社区的其他成

    员询问了安全性,这次这个代码被发送给他们。其他几个请求也跟随而来。到 2014 年一

    月大约有 20 万人使用了这个代码。这些创业者的人提出一个 SourceForge 项目加入是为

    了,这是在 2004 三月正式成立。

    在早些时候,这个项目没有任何自己的验证模块,身份验证过程依赖于容器管理的安全性

    和 Acegi 安全性。而不是专注于授权。开始的时候这很适合,但是越来越多的用户请求额

    外的容器支持。容器特定的认证领域接口的基本限制变得清晰。还有一个相关的问题增加

    新的容器的路径,这是最终用户的困惑和错误配置的常见问题。

    Acegi 安全特定的认证服务介绍。大约一年后,Acegi 安全正式成为了 Spring 框架的子项

    目。1.0.0 最终版本是出版于 2006 -在超过两年半的大量生产的软件项目和数以百计的改

    进和积极利用社区的贡献。

    Acegi 安全 2007 年底正式成为了 Spring 组合项目,更名为"Spring Security"。

SpringSecurity入门

  • 1.创建SpringBoot工程
  • 2.引入依赖
  • 3.编写controller进行测试

SpringSecurity两个重要的接口

  • UserDetailsService

当什么也没有配置的时候,账号和密码是由Spring Security定义生成的。而在实际项目中账号和密码都是从数据库中查询出来的。所以我们要通过自定义逻辑控制认证逻辑

img点击并拖拽以移动编辑

  • PasswordEncoder

数据加密的一个接口,用于返回User对象里面的密码加密

自定义实现类设置

  • 第一步创建 配置类,使用UserDetailsService实现类
package com.lkjedu.boot.config;

import com.lkjedu.boot.service.MyUserDetailsService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;

@Configuration
public class SecurityConfigTest extends WebSecurityConfigurerAdapter {
//    @Autowired
//    private UserDetailsService userDetailsService;
    @Autowired
    private MyUserDetailsService userDetailsService;


    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.userDetailsService(userDetailsService).passwordEncoder(password());
    }

    @Bean
    PasswordEncoder password() {
        return new BCryptPasswordEncoder();
    }
}

点击并拖拽以移动

  • 第二步编写实现类,返回User对象,User对象有对用户名和密码的操作权限
package com.lkjedu.boot.service;

import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.userdetails.User;
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.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;

import java.util.List;

@Service()
public class MyUserDetailsService implements UserDetailsService {
    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        List<GrantedAuthority> auths = AuthorityUtils.commaSeparatedStringToAuthorityList("admin,ROLE_sale");
        //从查询数据库返回users对象,得到用户名和密码,返回
        return new User("user",
                new BCryptPasswordEncoder().encode("1234"),auths);
    }
}

点击并拖拽以移动

查询数据库完成用户验证

整合MyBatisPlus完成数据库查询

  • 第一步引入相关依赖
 <!--mybatis-plus-->
 <dependency>
 <groupId>com.baomidou</groupId>
 <artifactId>mybatis-plus-boot-starter</artifactId>
 <version>3.0.5</version>
 </dependency>
 <!--mysql-->
 <dependency>
 <groupId>mysql</groupId>
 <artifactId>mysql-connector-java</artifactId>
 </dependency>
 <!--lombok 用来简化实体类-->
 <dependency>
 <groupId>org.projectlombok</groupId>
 <artifactId>lombok</artifactId>
 </dependency>

点击并拖拽以移动

  • 第二部编写实体类
package com.lkjedu.boot.beans;

import com.baomidou.mybatisplus.annotation.TableName;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import lombok.ToString;

@Data
@AllArgsConstructor
@NoArgsConstructor
@ToString
@TableName("User")
public class UserBean {
    private int id;
    private String user;
    private String password;
}

点击并拖拽以移动

  • 第三步编写Mapper接口
package com.lkjedu.boot.beans;

import com.baomidou.mybatisplus.annotation.TableName;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import lombok.ToString;

@Data
@AllArgsConstructor
@NoArgsConstructor
@ToString
@TableName("User")
public class UserBean {
    private int id;
    private String user;
    private String password;
}

点击并拖拽以移动

  • 第四步编写实现类,返回User对象,User对象有对用户名和密码的操作权限
package com.lkjedu.boot.service;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.lkjedu.boot.beans.UserBean;
import com.lkjedu.boot.mapper.UserMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.userdetails.User;
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.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;

import java.util.List;

@Service()
public class MyUserDetailsService implements UserDetailsService {

    @Autowired
    private UserMapper userMapper;


    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        QueryWrapper<UserBean> wrapper = new QueryWrapper<>();
        wrapper.eq("user",username);
        UserBean user = userMapper.selectOne(wrapper);

        if (user == null){
            throw new UsernameNotFoundException("用户名不存在!");
        }


        List<GrantedAuthority> auths = AuthorityUtils.commaSeparatedStringToAuthorityList("admin,ROLE_sale");
        //从查询数据库返回users对象,得到用户名和密码,返回
        return new User(user.getUser(),
                new BCryptPasswordEncoder().encode(user.getPassword()),auths);
    }
}

点击并拖拽以移动

自定义登录页面

重写protected void configure(HttpSecurity http)方法:

img点击并拖拽以移动编辑

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.formLogin()//自定义自己编辑的登录页面
                .loginPage("/login.html")//登录页面设置
                .loginProcessingUrl("/user/login")//登录访问路径
                .defaultSuccessUrl("/index").permitAll()//登录成功后跳转路径
                .and().authorizeHttpRequests()
                .antMatchers("/","/add","/user/login").permitAll()//设置那些路径可以直接访问不需要认证
                .antMatchers("/index").hasAuthority("admins")//当前用户只有,admins权限才能访问这个路径

                .anyRequest().authenticated()
                .and().csrf().disable();//关闭csrf保护

    }

点击并拖拽以移动

基于角色授权进行访问

  • 第一个方法:hasAuthority:

    • 如果当前的主体具有指定的权限,则返回 true,否则返回 false
  • 第二个方法:hasAnyAuthority

    • 如果当前的主体有任何提供的角色(给定的作为一个逗号分隔的字符串列表)的话,返回

      true.

  • 第三个方法:hasRole

    • 如果用户具备给定角色就允许访问,否则出现 403。 如果当前主体具有指定的角色,则返回 true。因为底层源码是"ROLE_"拼接上role所以给用户权限必须加上"ROLE_"

    • 底层源码:

      img点击并拖拽以移动编辑

      给用户添加角色:

      img点击并拖拽以移动编辑

  • 第四个方法:

    hasAnyRole

    • 表示用户具备任何一个条件都可以访问。

配置没有权限跳转页面img点击并拖拽以移动编辑

注解使用

@Secured

判断是否具有角色,另外需要注意的是这里匹配的字符串需要添加前缀“ROLE_“。

使用注解先要开启注解功能!*@EnableGlobalMethodSecurity(securedEnabled=true)*

// 测试注解:
@RequestMapping("testSecured")
@ResponseBody
@Secured({"ROLE_normal","ROLE_admin"})
public String helloUser() {
return "hello,user";
}
@Secured({"ROLE_normal","ROLE_管理员"})

点击并拖拽以移动

@PreAuthorize

先开启注解功能:@EnableGlobalMethodSecurity(prePostEnabled = true)

@PreAuthorize:注解适合进入方法前的权限验证,

@PreAuthorize 可以将登录用 户的 roles/permissions 参数传到方法中。

@RequestMapping("/preAuthorize")
@ResponseBody
//@PreAuthorize("hasRole('ROLE_管理员')")
@PreAuthorize("hasAnyAuthority('menu:system')")
public String preAuthorize(){
 System.out.println("preAuthorize");
return "preAuthorize";
}

点击并拖拽以移动

@PostAuthorize

先开启注解功能: @EnableGlobalMethodSecurity(prePostEnabled = true)

@PostAuthorize 注解使用并不多,在方法执行后再进行权限验证,适合验证带有返回值

的权限.

@RequestMapping("/testPostAuthorize")
@ResponseBody
@PostAuthorize("hasAnyAuthority('menu:system')")
public String preAuthorize(){
 System.out.println("test--PostAuthorize");
return "PostAuthorize";
}

点击并拖拽以移动

@PostFilter

@PostFilter :权限验证之后对数据进行过滤 留下用户名是 admin1 的数据

表达式中的 filterObject 引用的是方法返回值 List 中的某一个元素

@RequestMapping("getAll")
@PreAuthorize("hasRole('ROLE_管理员')")
@PostFilter("filterObject.username == 'admin1'")
@ResponseBody
public List<UserInfo> getAllUser(){
 ArrayList<UserInfo> list = new ArrayList<>();
 list.add(new UserInfo(1l,"admin1","6666"));
 list.add(new UserInfo(2l,"admin2","888"));
return list;
}

点击并拖拽以移动

@PreFilter

@PreFilter: 进入控制器之前对数据进行过滤

@RequestMapping("getTestPreFilter")
@PreAuthorize("hasRole('ROLE_管理员')")
@PreFilter(value = "filterObject.id%2==0")
@ResponseBody
public List<UserInfo> getTestPreFilter(@RequestBody List<UserInfo> 
list){
 list.forEach(t-> {
 System.out.println(t.getId()+"\t"+t.getUsername());
 });
return list;
}

点击并拖拽以移动

账号注销

在登录页面添加一个退出连接

<body>
登录成功<br>
<a href="/logout">退出</a>
</body>

点击并拖拽以移动

在配置类中添加退出映射地址

http.logout().logoutUrl("/logout").logoutSuccessUrl("/index").permitAll

点击并拖拽以移动

自动登录

1.使cookie技术实现

2.使用SpringSecurity安全框架实现

  • 实现原理

img点击并拖拽以移动编辑

img点击并拖拽以移动编辑

阿里云国内75折 回扣 微信号:monov8
阿里云国际,腾讯云国际,低至75折。AWS 93折 免费开户实名账号 代冲值 优惠多多 微信号:monov8 飞机:@monov6
标签: Spring