1、基础概念

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

2、核心API解读

1、SecurityContextHolder

最基本的对象,保存着当前会话用户认证,权限,鉴权等核心数据。SecurityContextHolder默认使用ThreadLocal策略来存储认证信息,与线程绑定的策略。用户退出时,自动清除当前线程的认证信息。

初始化源码:明显使用ThreadLocal线程。

private static void initialize() {
if (!StringUtils.hasText(strategyName)) {
strategyName = "MODE_THREADLOCAL";
}
if (strategyName.equals("MODE_THREADLOCAL")) {
strategy = new ThreadLocalSecurityContextHolderStrategy();
} else if (strategyName.equals("MODE_INHERITABLETHREADLOCAL")) {
strategy = new InheritableThreadLocalSecurityContextHolderStrategy();
} else if (strategyName.equals("MODE_GLOBAL")) {
strategy = new GlobalSecurityContextHolderStrategy();
} else {
try {
Class<?> clazz = Class.forName(strategyName);
Constructor<?> customStrategy = clazz.getConstructor();
strategy = (SecurityContextHolderStrategy)customStrategy.newInstance();
} catch (Exception var2) {
ReflectionUtils.handleReflectionException(var2);
}
}
++initializeCount;
}

2、Authentication

源码

public interface Authentication extends Principal, Serializable {
Collection<? extends GrantedAuthority> getAuthorities();
Object getCredentials();
Object getDetails();
Object getPrincipal();
boolean isAuthenticated();
void setAuthenticated(boolean var1) throws IllegalArgumentException;
}

源码分析

1)、getAuthorities,权限列表,通常是代表权限的字符串集合;

2)、getCredentials,密码,认证之后会移出,来保证安全性;

3)、getDetails,请求的细节参数;

4)、getPrincipal, 核心身份信息,一般返回UserDetails的实现类。

3、UserDetails

封装了用户的详细的信息。

public interface UserDetails extends Serializable {
Collection<? extends GrantedAuthority> getAuthorities();
String getPassword();
String getUsername();
boolean isAccountNonExpired();
boolean isAccountNonLocked();
boolean isCredentialsNonExpired();
boolean isEnabled();
}

4、 UserDetailsService

实现该接口,自定义用户认证流程,通常读取数据库,对比用户的登录信息,完成认证,授权。

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

5、 AuthenticationManager

认证流程顶级接口。可以通过实现AuthenticationManager接口来自定义自己的认证方式

Spring提供了一个默认的实现,ProviderManager。

public interface AuthenticationManager {
Authentication authenticate(Authentication var1) throws AuthenticationException;
}

3.整合

1、流程描述

1)、模拟增删改查
2)、未登录授权都不可以访问
3)、登录后根据用户权限,访问指定页面
4)、对于未授权页面,访问返回403:资源不可用

2、核心依赖

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

3、核心配置

package com.Boot.config;

import com.Boot.Security.UserDetailServiceImpl;
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.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder; /**
* @Classname SpringSecurityConfig
* @Description TODO
* @Date 2019/11/6 19:59
* @Created by 远
*/
@Configuration
@EnableWebSecurity //启动springSecurity启动链
public class SpringSecurityConfig extends WebSecurityConfigurerAdapter { /**
* @return
* @Author 远
* @Description 代替认证管理器
* @Param
**/
/**
* 自定义认证数据源
*/
@Override
protected void configure(AuthenticationManagerBuilder builder) throws Exception{
builder.userDetailsService(userDetailService())
.passwordEncoder(passwordEncoder());
}
@Bean
public UserDetailServiceImpl userDetailService (){
return new UserDetailServiceImpl () ;
}
/**
* 密码加密
*/
@Bean
public BCryptPasswordEncoder passwordEncoder(){
return new BCryptPasswordEncoder();
} /**
* @Author 远
* @Description 硬编码一个用户用于测试
* @Param
* @return
**/
/*@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
auth.inMemoryAuthentication().withUser("ljw").password("123").authorities("ROLE_ADD");
}*/ /**
* @return
* @Author 远
* @Description 代替之前配置<security:http></security:http>
**/
@Override
protected void configure(HttpSecurity http) throws Exception { http.authorizeRequests()
//antMatchers指定页面,hasAnyAuthority指定拥有什么样的权限的用户可以访问
.antMatchers("/add").hasAnyAuthority("ROLE_ADD")
.antMatchers("/update").hasAnyAuthority("ROLE_UPDATE")
.antMatchers("/list").hasAnyAuthority("ROLE_SELECT")
.antMatchers("/delete").hasAnyAuthority("ROLE_DELETE")
//放行index和login页面
.antMatchers("/login").permitAll()
.antMatchers("/index").permitAll()
//拦截全部
.antMatchers("/**")
.fullyAuthenticated()
.and()
//解决页面csrf报错
.csrf().disable();
// 配置登录功能
http.formLogin().usernameParameter("user")
.passwordParameter("pwd")
.loginPage("/userLogin");
// 注销成功跳转首页
http.logout().logoutSuccessUrl("/");
//开启记住我功能
http.rememberMe().rememberMeParameter("remeber");
}
}

4、认证

package com.Boot.Security;

import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
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.stereotype.Service; import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List; /**
* @Classname UserDetailServiceImpl
* @Description 认证
* @Date 2019/11/6 22:22
* @Created by 远
*/
@Service
public class UserDetailServiceImpl implements UserDetailsService {
@Resource
private UserRoleMapper userRoleMapper ;
@Override
public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
// 这里可以捕获异常,使用异常映射,抛出指定的提示信息
// 用户校验的操作
// 假设密码是数据库查询的 123
String password = "$2a$10$XcigeMfToGQ2bqRToFtUi.sG1V.HhrJV6RBjji1yncXReSNNIPl1K";
// 假设角色是数据库查询的
//查询数据里所有的用户对应角色的权限
List<String> roleList = userRoleMapper.selectByUserName(username) ;
List<GrantedAuthority> grantedAuthorityList = new ArrayList<>() ;
/*
* Spring Boot 2.0 版本踩坑
* 必须要 ROLE_ 前缀, 因为 hasRole("LEVEL1")判断时会自动加上ROLE_前缀变成 ROLE_LEVEL1 ,
* 如果不加前缀一般就会出现403错误
* 在给用户赋权限时,数据库存储必须是完整的权限标识ROLE_LEVEL1
*/
if (roleList != null && roleList.size()>0){
for (String role : roleList){
//将所有的角色遍历到GrantedAuthority
grantedAuthorityList.add(new SimpleGrantedAuthority(role)) ;
}
}
//返回用户,用户的用户名,密码,以及权限
return new User(username,password,grantedAuthorityList);
}
}

5、接口

package com.Boot.Controller;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping; /**
* @Classname productController
* @Description 增删改查
* @Date 2019/11/1 14:41
* @Created by 远
*/ @Controller
public class productController {
/**
* @Author 远
* @Description
* @Param
* @return
**/
@RequestMapping("/add")
public String add() {
return "product/add";
}
/**
* @Author 远
* @Description 商品修改
**/
@RequestMapping("update")
public String Update() {
return "product/update";
} /**
* @Author 远
* @Description 商品显示
**/
@RequestMapping("list")
public String list() {
return "product/list";
} /**
* @Author 远
* @Description 商品删除
**/
@RequestMapping("delete")
public String del() {
return "product/delete";
}
@RequestMapping("/login")
public String login(){
return "login";
}
@RequestMapping("index")
public String index(){
return"index";
}
@RequestMapping("403")
public String forbidden(){
return "403";
} }

6、前端登录页面

这里要和Security的配置文件相对应。

<div align="center">
<form th:action="@{/userLogin}" method="post">
用户名:<input name="user"/><br>
密&nbsp;&nbsp;&nbsp;码:<input name="pwd"><br/>
<input type="checkbox" name="remeber"> 记住我<br/>
<input type="submit" value="Login">
</form>
</div>

Security整合spring boot的更多相关文章

  1. Spring Kafka整合Spring Boot创建生产者客户端案例

    每天学习一点点 编程PDF电子书.视频教程免费下载:http://www.shitanlife.com/code 创建一个kafka-producer-master的maven工程.整个项目结构如下: ...

  2. PART 5: INTEGRATING SPRING SECURITY WITH SPRING BOOT WEB

    转自:http://justinrodenbostel.com/2014/05/30/part-5-integrating-spring-security-with-spring-boot-web/ ...

  3. Keycloak 团队宣布他们正在弃用大多数 Keycloak 适配器,包括Spring Security和Spring Boot

    2月14日,Keycloak 团队宣布他们正在弃用大多数 Keycloak 适配器. 其中包括Spring Security和Spring Boot的适配器,这意味着今后Keycloak团队将不再提供 ...

  4. 漫谈Spring Security 在Spring Boot 2.x endpoints中的应用(一)

    Spring Boot 2.x极大简化了默认的安全配置,并不是说有很多安全相关的配置,现在你只需要提供一个WebSecurityConfigurerAdapter继承类这样一个简单的操作,Spring ...

  5. spring boot:用spring security加强spring boot admin的安全(spring boot admin 2.3.0 / spring boot 2.3.3)

    一,spring boot admin的安全环节: 1,修改context-path,默认时首页就是admin, 我们修改这个地址可以更安全 2,配置ip地址白名单,有ip限制才安全, 我们使用了sp ...

  6. idea整合 spring boot jsp mybatis

    spring  boot  开发起来确实要简单许多 ,spring boot  包含了 spring mvc ;内置tomcat   ;启动只需要主方法即可 1.使用idea新建一个spring bo ...

  7. Spring Security +Oauth2 +Spring boot 动态定义权限

    Oauth2介绍:Oauth2是为用户资源的授权定义了一个安全.开放及简单的标准,第三方无需知道用户的账号及密码,就可获取到用户的授权信息,并且这是安全的. 简单的来说,当用户登陆网站的时候,需要账号 ...

  8. 面试官:小伙子,你给我简单说一下RocketMQ 整合 Spring Boot吧

    前言 在使用SpringBoot的starter集成包时,要特别注意版本.因为SpringBoot集成RocketMQ的starter依赖是由Spring社区提供的,目前正在快速迭代的过程当中,不同版 ...

  9. 整合spring boot时操作数据库时报错Caused by: java.lang.InstantiationException: tk.mybatis.mapper.provider.base.B

    原文:https://blog.csdn.net/u__f_o/article/details/82756701 一般出现这种情况,应该是没有扫描到对应的mapper包,即在启动类下配置MapperS ...

随机推荐

  1. 死磕 java同步系列之redis分布式锁进化史

    问题 (1)redis如何实现分布式锁? (2)redis分布式锁有哪些优点? (3)redis分布式锁有哪些缺点? (4)redis实现分布式锁有没有现成的轮子可以使用? 简介 Redis(全称:R ...

  2. 如何搭建基于Docker的gitlab服务器集成CI/CD实现DEVOPS(完整版)

    From this lesson you will learn about 1,How to install and configure a docker based gitlab server 2, ...

  3. 当我们在聊 Serverless 时你应该知道这些

    作者 | 杨泽强(竹涧)阿里云技术专家 说起当前最火的技术,除了最新的区块链.AI,还有一个不得不提的概念是 Serverless.Serverless 作为一种新型的互联网架构,直接或间接推动了云计 ...

  4. wdcp 开启某个Mysql数据库远程访问

    wdcp 开启某个Mysql数据库远程访问 登录wdcp后台-Mysql管理-phpmyadmin 输入Mysql的root密码登录进入 示例代码: update mysql.user set hos ...

  5. 针对永久不过期的key 批量设置过期时间

    问题需求: redis内存暴增,后来发现有很多设置永久不过期. 解决:查找出来之后针对前缀批量设置过期时间 (过期时间与开发沟通 保证服务不受影响) 来源于网上杨一的代码 正好解决了我遇到的问题 在这 ...

  6. 【从刷面试题到构建知识体系】Java底层-synchronized锁-1

    在技术论坛中,经常看到一种言论:面试造火箭,干活拧螺丝.我们平时写的大部分代码的确是CRDU,再提一个层次,也无非就是揉进去复杂一些的业务逻辑,把一堆的CRDU组合起来. 那么问题来了:我们提倡的研究 ...

  7. rest_framework视图

    知识预览 视图 回到顶部 视图 使用混合(mixins) 上一节的视图部分:   from rest_framework.views import APIView from rest_framewor ...

  8. RMAN详细教程(二):备份、检查、维护、恢复

    RMAN详细教程(一):基本命令代码 一.创建增量备份 增量备份级别为0-4,但为方便备份管理,oracle建议只限于0级和1级. 1.差异增量备份(differential incremental ...

  9. 02-19 k近邻算法(鸢尾花分类)

    [TOC] 更新.更全的<机器学习>的更新网站,更有python.go.数据结构与算法.爬虫.人工智能教学等着你:https://www.cnblogs.com/nickchen121/ ...

  10. python编程基础之十六

    for in 循环,与其说是循环不如说精确点交遍历 for 变量名 in + 迭代对象 语句A else: 语句B 作用:一次访问迭代对象中的元素并赋值给变量 循环终止时,执行else语句块,如果br ...