本篇文章将介绍

1.使用SpringSecurity默认账号密码登录

2.使用配置文件配置账号密码登录

3.使用配置类 设置账号 并设置权限

4.连接数据库,使用数据库中数据账号密码进行登陆

1.创建Boot项目 导入相应的依赖

2.配置文件

spring:devtools:restart:enabled: false  #开启热部署 true# additional-paths: src/main/java  #设置重启目录# exclude: WEB-INF/** 设置classpath目录下的WEB-INF文件夹内容修改不重启datasource:driver-class-name: com.mysql.jdbc.Driverurl: jdbc:mysql://localhost:3306/test?useUnicode=true&characterEncoding=utf-8&allowMultiQueries=true&useSSL=false&serverTimezone=GMT%2B8hikari: # springboot 2.0 整合了hikari ,据说这是目前性能最好的java数据库连接池username: xxxxpassword: xxxxjpa:hibernate:ddl-auto: update  # 第一次建表create  后面用update,要不然每次重启都会新建表show-sql: true#配置文件中配置 登陆账号密码
#  security:
#    user:
#      name: admin
#      password: admin#端口号配置  默认是8080
server:port: 8081

基本准备工作已经做好 下面编写第一个controller方法

一 . 使用SpringSecurity默认账号密码登录

package com.example.reviewsecurity.controller;import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;/*** @Author xiang* @CreatTime 2020/4/17* @Describe*/
@RestController
@RequestMapping("/meetingFriends")
public class SecurityController {@GetMapping("/accost")public String firstTime(){return "hello,we haven't before,have we?";}
}

然后启动项目 会看到 控制台会打印 这样一串字符

这个就是SpringSecurity登陆时的密码passWord 每次都会不同哦  默认的userName  为user

在页面上访问controller中编写的路径http://localhost:8081/meetingFriends/accost   然后SpringSecurity进行拦截

成功输入之后即可进入页面

二.使用配置文件配置账号密码登录

将配置文件中的 注解解开即可

 配置文件中配置 登陆账号密码
security:user:name: adminpassword: admin

然后重启 项目 使用此账号登陆即可  其实不用重启 因为在配置文件中已经设置热部署

如果热部署不好使

IDEA配置

当我们修改了Java类后,IDEA默认是不自动编译的,而spring-boot-devtools又是监测classpath下的文件发生变化才会重启应用,所以需要设置IDEA的自动编译:

(1)File-Settings-Compiler-Build Project automatically

(2)ctrl + shift + alt + /,选择Registry,勾上 Compiler autoMake allow when app running

就OK啦

三 使用配置类 设置账号密码  并设置权限

创建配置类

package com.example.reviewsecurity.config;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.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;/*** @Author xiang* @CreatTime 2020/4/17* @Describe*/
@Configuration
@EnableWebSecurity //开启springSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {@Overrideprotected void configure(AuthenticationManagerBuilder auth) throws Exception {auth.inMemoryAuthentication().withUser("user").password(passwordEncoder().encode("user")).roles("normal");auth.inMemoryAuthentication().withUser("admin").password(passwordEncoder().encode("admin")).roles("manager");}@Bean //不可忘记加 否者此方法无效 依旧会报 java.lang.IllegalArgumentException: There is no PasswordEncoder mapped for the id "null"public PasswordEncoder passwordEncoder(){return new BCryptPasswordEncoder();}
}

如果对设置账号时 你是这样设置的

 auth.inMemoryAuthentication().withUser("admin").password("admin").roles();

登陆时报错

java.lang.IllegalArgumentException: There is no PasswordEncoder mapped for the id "null"

原因:

从 Spring5 开始,强制要求密码要加密 Spring Security 中提供了 BCryptPasswordEncoder 密码编码工具,可以非常方便的实现密码的加密加盐,相同明文加密出来的结果总是不同,这样就不需要用户去额外保存的字段了,这一点比 Shiro 要方便很多。

设置权限

配置类

package com.example.reviewsecurity.config;import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
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;
import org.springframework.security.crypto.password.PasswordEncoder;import javax.annotation.PostConstruct;/*** @Author xiang* @CreatTime 2020/4/17* @Describe*/
@Configuration
@EnableWebSecurity //开启springSecurity
@EnableGlobalMethodSecurity(prePostEnabled = true)//开启安全级别的权限控制  开启验证权限 prePostEnabled为true的时候会拦截标有@PreAuthorize的方法 验证权限
public class SecurityConfig extends WebSecurityConfigurerAdapter {@Overrideprotected void configure(AuthenticationManagerBuilder auth) throws Exception {auth.inMemoryAuthentication().withUser("user").password(passwordEncoder().encode("user")).roles("normal");auth.inMemoryAuthentication().withUser("admin").password(passwordEncoder().encode("admin")).roles("manager");}@Bean //不可忘记加 否者此方法无效 依旧会报 java.lang.IllegalArgumentException: There is no PasswordEncoder mapped for the id "null"public PasswordEncoder passwordEncoder(){return new BCryptPasswordEncoder();}
}

controller

package com.example.reviewsecurity.controller;import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;/*** @Author xiang* @CreatTime 2020/4/17* @Describe*/
@RestController
@RequestMapping("/meetingFriends")
public class SecurityController {@GetMapping("/accost")public String firstTime(){return "hello,we haven't before,have we?";}@GetMapping("/greet")@PreAuthorize("hasAnyRole('normal','manager')") //设置权限让指定的角色进行访问此方法,多个角色可用逗号隔开public String secondTime(){return "how are you doing?";}/*** 角色 normal 访问此方法时 因权限不足 页面会报错  There was an unexpected error (type=Forbidden, status=403).* */@GetMapping("/familiar")@PreAuthorize("hasAnyRole('manager')")public String thirtyTime(){return "hi,what's up?";}}

当访问权限不足时 页面报错

四 连接数据库 使用数据 登陆

实体类

package com.example.reviewsecurity.domain;import lombok.Data;import javax.persistence.*;/*** @Author xiang* @CreatTime 2020/4/17* @Describe*/
@Entity
@Data
public class UserInfo {@Id    //主键@GeneratedValue  //自增private Long userId;private String userName;private String passWord;@Enumerated(EnumType.STRING)private Role role;public enum  Role{normal,manager;}
}

dao层

package com.example.reviewsecurity.dao;import com.example.reviewsecurity.domain.UserInfo;
import org.springframework.data.jpa.repository.JpaRepository;/*** @Author xiang* @CreatTime 2020/4/17* @Describe*/
public interface SecurityDao extends JpaRepository<UserInfo,Long> {UserInfo getUserInfoByUserName(String userName);
}

service层

package com.example.reviewsecurity.service;import com.example.reviewsecurity.domain.UserInfo;/*** @Author xiang* @CreatTime 2020/4/17* @Describe*/
public interface SecurityService {UserInfo getUserInfoByUserName(String userName);
}

service实现类

package com.example.reviewsecurity.service.impl;import com.example.reviewsecurity.dao.SecurityDao;
import com.example.reviewsecurity.domain.UserInfo;
import com.example.reviewsecurity.service.SecurityService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;/*** @Author xiang* @CreatTime 2020/4/17* @Describe*/
@Service
public class SecurityServiceImpl implements SecurityService {@AutowiredSecurityDao securityDao;@Overridepublic UserInfo getUserInfoByUserName(String userName) {return securityDao.getUserInfoByUserName(userName);}
}

数据初始化

package com.example.reviewsecurity.dataSource;import com.example.reviewsecurity.dao.SecurityDao;
import com.example.reviewsecurity.domain.UserInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Service;import javax.annotation.PostConstruct;/*** @Author xiang* @CreatTime 2020/4/17* @Describe*/
@Service
public class SecurityDataSource {@AutowiredSecurityDao securityDao;@PostConstruct //当项目启动的时候  初始化数据public void dataInit(){UserInfo lili = new  UserInfo();lili.setUserName("lili");lili.setPassWord("lili");lili.setRole(UserInfo.Role.manager);securityDao.save(lili);UserInfo huahua = new  UserInfo();huahua.setUserName("huahua");huahua.setPassWord("huahua");huahua.setRole(UserInfo.Role.normal);securityDao.save(huahua);}
}

配置类

package com.example.reviewsecurity.config;import com.example.reviewsecurity.domain.UserInfo;
import com.example.reviewsecurity.service.SecurityService;
import org.springframework.beans.factory.annotation.Autowired;
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.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Component;import java.util.ArrayList;
import java.util.List;/*** @Author xiang* @CreatTime 2020/4/17* @Describe*/
@Component
public class UserDetail implements UserDetailsService {@AutowiredSecurityService securityService;@AutowiredPasswordEncoder passwordEncoder;@Overridepublic UserDetails loadUserByUsername(String userName) throws UsernameNotFoundException {UserInfo userInfoByUserName = securityService.getUserInfoByUserName(userName);List<GrantedAuthority> role = new ArrayList<>();role.add(new SimpleGrantedAuthority("ROLE_"+userInfoByUserName.getRole().name()));//  User userDetail = new User(userInfoByUserName.getUserName(),userInfoByUserName.getPassWord(),role);User userDetail = new User(userInfoByUserName.getUserName(),passwordEncoder.encode(userInfoByUserName.getPassWord()),role);return userDetail;}
}

user的构造函数中的第三个参数角色是一个集合

编写完之后 在项目启动之前 注意   要注释掉 之前 配置文件中设置的权限账号 否则

页面报 Bad credentials

注释之后  根据数据库中相应的值进行登陆  即可

----------------------------------------------------------------------

项目启动流程

项目启动---初始化数据----登陆----走配置类根据userName获取userDetail----从userDetail中获取角色走controller方法进行验证

SpringSecurity初级入门相关推荐

  1. Jeecg 初级入门

    Jeecg 初级入门 1.部署jeecg 1.1.下载jeecg 请在jeecg 发布地址下载jeecg工程 1.2 导入myeclipse8.5 按照如下视图选择jeecg项目存放路径然后导入项目工 ...

  2. 【技术培训】招收Jeecg门徒 ---javaweb初级入门班

    招收Jeecg门徒[javaweb初级入门班] 最近准备带徒弟,带些人才出来,我带徒弟的理念是实践为王,在实践中掌握原理,积累经验. 我带徒弟的方向是JAVA WEB,掌握各种主流框架.(后期会开展j ...

  3. mui初级入门教程(六)— 模板页面实现原理及多端适配指南

    文章来源:小青年原创 发布时间:2016-07-26 关键词:mui,webview,template,os,多端适配 转载需标注本文原始地址: http://zhaomenghuan.github. ...

  4. Linux初级入门(第一次作业)

    Linux初级入门 在本科期间学过一些Linux的简单命令,再次接触Linux不仅巩固了知识还学习到了很多新的东西. 什么是操作系统? 操作系统,英文名称Operating System,简称OS,是 ...

  5. 【吴刚】电商网站详情页设计初级入门标准视频教程-吴刚-专题视频课程

    [吴刚]电商网站详情页设计初级入门标准视频教程-325人已学习 课程介绍         本套教程在学员有PS软件基础及对网页元素制作有了解的基础上,循序渐进,深入浅出,全篇干货,系统化的讲解电商网站 ...

  6. uni-app项目开发-----初级入门教程(从0到1制作打包自己的app)

    uni-app项目开发-----初级入门教程(从0到1制作打包自己的app) uni-app实现了一套代码,同时运行到多个平台.支持iOS模拟器.Android模拟器.H5.微信开发者工具.支付宝小程 ...

  7. Elasticsearch 使用初级入门 【入门篇】

    Elasticsearch 使用初级入门 整理中.... 1.下载 下载网址:https://www.elastic.co/cn/downloads/elasticsearch 2.安装 因为安全问题 ...

  8. 视频教程-【吴刚】电商活动站设计初级入门标准视频教程-UI

    [吴刚]电商活动站设计初级入门标准视频教程 业内知名UID.UED.用户体验.品牌策略与创意设计师,十三年行业职业教育培训经验,业内"UI视频第一人",教学总监.视觉设计讲师. A ...

  9. 【吴刚】电商活动站设计初级入门标准视频教程-吴刚-专题视频课程

    [吴刚]电商活动站设计初级入门标准视频教程-144人已学习 课程介绍         本套教程在学员有PS软件基础及对网页元素制作有了解的基础上,循序渐进,深入浅出,全篇干货,系统化的讲解电商活动站建 ...

  10. 如何学习虚拟现实技术vr? vr初级入门教程开始

    vr虚拟现实技术应用广泛,是我们所有目共睹的,想要学的人越来越多,如何学习虚拟现实技术vr?千锋作为VR技术培训领先者,先给大家分享一下vr初级入门教程. 随着VR虚拟现实的爆发,越来越多的知名企业开 ...

最新文章

  1. vue结合php增删改查实例,用vue.js写一个简单的增删改查
  2. OpenStack部署之小结
  3. Java程序通过批处理文件定时执行
  4. 如何关闭快递收货隐私手机号 拼多多
  5. 高中计算机思维导图,为高中信息技术教学插上思维导图翅膀
  6. 微信小程序引入 iconfont 图标
  7. HTML CSS——层叠
  8. Self-supervised Heterogeneous Graph Neural Network with Co-contrastive Learning
  9. Mathlab编程-微积分在Matlab中的解法
  10. 建网站还有用吗?现解说您的网站不赚钱,同行在盈利
  11. 猫眼电影MySQL数据库怎么写_Python3爬取猫眼电影榜并将数据存入MySql
  12. Acwing 905. 区间选点
  13. 小米机器人清理主刷和轴承_小米扫地机器人的噪音感觉有点大怎么办?
  14. 51单片机的C语言延时的一些总结
  15. 技术人玩小游戏,如何“不战而胜”
  16. Bi-Noising Diffusion: Towards Conditional Diffusion Models with Generative Restoration Priors
  17. 窗口函数(Window Function)
  18. iOS 10:四、因苹果健康导致闪退 crash
  19. 一文彻底搞懂I/O多路复用及其技术
  20. 设计模式——简单工厂设计模式

热门文章

  1. 开发方法---软件开发模型
  2. 【连接】mac使用Microsoft Remote Desktop Beta 远程win Error code: 0x104
  3. (17)2020-12-23(三栏布局、视口、百分比布局、媒体查询)
  4. 编写函数将一个NxN的二维数组的周边元素 “顺时针”轮转1位。
  5. 【单片机毕业设计】温室大棚 | 大棚环境检测系统 | 农田环境监测系统 | 智能灌溉系统 | 智慧农业系统
  6. 知道MDC,那NDC是什么?这个知识有点冷
  7. 基于pytorch的目标检测数据增强(tensor数据流版本)
  8. LinkedIn增长揭秘:262亿美元的增长引擎是如何练成的?
  9. service crond restart--User has insufficient privilege
  10. 11.23A T4方(思维好题----杜教筛(总复习))