当前位置:网站首页>You can have zongzi if you want, but you have to go through my authentication and authorization
You can have zongzi if you want, but you have to go through my authentication and authorization
2022-06-10 06:50:00 【Running Wang Mumu sir】
s p r i n g b o o t in Such as What Add Enter into Ann whole \textcolor{Orange}{springboot How to add security in } springboot in Such as What Add Enter into Ann whole
learn xi too cheng in Of pen remember , Fang then check reading learn xi \textcolor{green}{ Notes in the learning process , It's easy to check and learn } learn xi too cheng in Of pen remember , Fang then check reading learn xi
pen remember total junction Come on Source On Depending on the frequency B standing crazy god say \textcolor{green}{ The summary of notes comes from the video B Stand up and say } pen remember total junction Come on Source On Depending on the frequency B standing crazy god say
Welcome to pay attention and praise ️ Collect messages
SpringSecurity
Security is a non functional requirement .
Official website :https://spring.io/projects/spring-security
Make a website : Safety should be considered at the beginning of the design .
shiro,SpringSecurity: Except that the class and name are different , Everything else is the same . The main function is authentication and authorization .
be used for : Function permissions , Access right , Menu permissions
Actual operation
Create a project and put web Module and Thymeleaf Module introduction

Import the static file into

Turn off the template engine cache , Convenient debugging
spring.thymeleaf.cache=falseTo configure controller
package com.hxl.controller; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestMapping; @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; } }Start the test
localhost:8080Run successfully
Spring Security
Spring Security Is aimed at Spring Project security framework , It's also Spring Boot The default technology selection of the underlying security module , He can achieve powerful Web safety control , For security control , We just need to introduce spring-boot-starter-security modular , Make a small amount of configuration , To achieve strong security management !
Remember a few classes :
- WebSecurityConfigurerAdapter: Customize Security Strategy
- AuthenticationManagerBuilder: Custom authentication policy
- @EnableWebSecurity: Turn on WebSecurity Pattern
Spring Security The two main goals of are “ authentication ” and “ to grant authorization ”( Access control ).
“ authentication ”(Authentication)
Authentication is about verifying your credentials , Such as user name / user ID And password , To verify your identity .
Authentication is usually done with a user name and password , Sometimes used in combination with authentication factors .
“ to grant authorization ” (Authorization)
Authorization occurs after the system has successfully verified your identity , Finally, you will be granted access to resources ( Such information , file , database , Money , Location , Almost anything ) Full authority of .
The concept is universal , Not just in Spring Security in .
Certificate authority
introduce Spring Security modular
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-security</artifactId> </dependency>To write config
Official website :https://spring.io/projects/spring-security
Write basic configuration class
package com.hxl.config; 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; @EnableWebSecurity // Turn on WebSecurity Pattern public class Security extends WebSecurityConfigurerAdapter { // Chain programming @Override protected void configure(HttpSecurity http) throws Exception { super.configure(http); } }Custom authorization
@Override protected void configure(HttpSecurity http) throws Exception { // The home page is accessible to everyone , The function page can only be accessed by the corresponding authorized person /*http.authorizeRequests() This is an authentication request , hinder . It means that you can access */ http.authorizeRequests() .antMatchers("/").permitAll() .antMatchers("/level1/**").hasRole("vip1") .antMatchers("/level2/**").hasRole("vip2") .antMatchers("/level3/**").hasRole("vip3"); }test
At this time, we found that , In addition to the home page , Nothing else can get in , This is because you do not have permission to log in to the role
Turn on login configuration
In the custom authorization method above , Add the following code
// No permission to jump to the login page by default , You need to open the login page http.formLogin();test
If you don't have permission , Will automatically jump to the login page , And the jump link is
http://localhost:8080/loginauthentication
// authentication , You can authenticate in memory , You can also authenticate in the database @Override protected void configure(AuthenticationManagerBuilder auth) throws Exception { auth.inMemoryAuthentication() .withUser("hxl").password("{noop}123456").roles("vip1","vip2") .and() .withUser("root").password("{noop}123456").roles("vip1","vip2","vip3") .and() .withUser("wode").password("{noop}123456").roles("vip1"); }Pay attention to the top
I found that a new password has been added to the password column
{noop}This is because if you do not add this, the following problem will be reported
This is due to encryption , The password transmitted from the front end should be encrypted in some way , Of course, in addition to the above methods, the following methods can be used for encryption .
auth.inMemoryAuthentication().passwordEncoder(new BCryptPasswordEncoder()) .withUser("hxl").password(new BCryptPasswordEncoder().encode("123456")).roles("vip1","vip2");This way is also possible . The official recommendation is Use bcrypt encryption
test
After that, it is found that each user can only access the rules under his own authentication . No access to other , Otherwise, an error will be reported

Access control and logout
First, enable the configured logoff function
Add the following
logoutSuccessUrlAfter the logout is successful , You can still jump to the home page// Chain programming @Override protected void configure(HttpSecurity http) throws Exception { //.... // Cancellation , Turn on the logout function , Jump to home page http.logout().logoutSuccessUrl("/"); }Add a logout button
<!-- Cancellation --> <a class="item" th:href="@{/logout}"> <i class="sign-out icon"></i> Cancellation </a>test


Click to log out , And you can return to the home page .
Function optimization
After successful login , The navigation bar displays the user information and the logout button . If there is no login, only the login button will be displayed . At the same time, the home page displays only the pages that the user has permission .
Login, logout and user information
Download dependency
<!-- https://mvnrepository.com/artifact/org.thymeleaf.extras/thymeleaf-extras-springsecurity5 --> <dependency> <groupId>org.thymeleaf.extras</groupId> <artifactId>thymeleaf-extras-springsecurity5</artifactId> <version>3.0.4.RELEASE</version> </dependency>stay
index.htmlinAdd namespace
xmlns:sec="http://www.thymeleaf.org/thymeleaf-extras-springsecurity5"If you are writing the following sec There was no hint when I was , Modify the namespace to
xmlns:sec="http://www.thymeleaf.org/extras/spring-security">Modify login / logout function and navigation bar
<!-- Log in and log out --> <div class="right menu"> <!-- Not logged in --> <div sec:authorize="!isAuthenticated()"> <a class="item" th:href="@{/toLogin}"> <i class="address card icon"></i> Sign in </a> </div> <!-- Logged in --> <div sec:authorize="isAuthenticated()"> <a class="item"> <i class="address card icon"></i> user name :<span sec:authentication="principal.username"></span> role :<span sec:authentication="principal.authorities"></span> </a> </div> <!-- Cancellation --> <div sec:authorize="isAuthenticated()"> <a class="item" th:href="@{/logout}"> <i class="address card icon"></i> Cancellation </a> </div> </div>
Role function certification
Take, for example , Others can be added .

<div class="column" sec:authorize="hasRole('vip1')">test

Note that we have to go to when logging in
http://localhost:8080/loginThis page , Not what we started withhttp://localhost:8080/toLogin. Next, we need to solve this problem .
Remember me
@Override
protected void configure(HttpSecurity http) throws Exception {
// The home page is accessible to everyone , The function page can only be accessed by the corresponding authorized person
/*http.authorizeRequests() This is an authentication request , hinder . It means that you can access */
http.authorizeRequests()
.antMatchers("/").permitAll()
.antMatchers("/level1/**").hasRole("vip1")
.antMatchers("/level2/**").hasRole("vip2")
.antMatchers("/level3/**").hasRole("vip3");
// No permission to jump to the login page by default , You need to open the login page
http.formLogin();
// Cancellation , Turn on the logout function , Jump to home page
http.logout().logoutSuccessUrl("/");
// Turn on remember me
http.rememberMe();
}

This is the default login , If you need to log in on your own login page, you still need to do something
How to complete it ?
After we close the browser , Log in again , You can find that users still exist . So how to achieve it ? Let's take a look at the browser cookie, I found him , And the default save time is two weeks .

After successful login , take cookie Send to browser to save , Log in later and bring this cookie, As long as you pass the check, you can log in free . Once deleted manually cookie after , Then it won't exist .
A complete home page
Just add this code later . But it should be consistent with the front end .
// No permission to jump to the login page by default , You need to open the login page
// Customize the landing page
http.formLogin().loginPage("/toLogin");

If the front end is
loginThen the back end needs to become
// Customize the landing page
http.formLogin().loginPage("/toLogin").loginProcessingUrl("/login");
At the same time, if the form information is inconsistent with the default information, it needs to be modified
http.formLogin().usernameParameter("username").passwordParameter("password").loginPage("/toLogin").loginProcessingUrl("/login");
It's over .
Add the function of remembering me
<div class="field"> <input type="checkbox" name="remember"> Remember me </div>The backend needs to be validated
// Turn on the function of remembering me , Customization remember that I receive the parameters of the front end http.rememberMe().rememberMeParameter("remember");
test

边栏推荐
- SM2 国密加密加签操作工具
- tensorflow实验九----------泰坦尼克号
- Where will the alarm messages go? Fly in the flying book
- ROS2+Gazebo11+Car+OpenCV巡线识别和速度转向控制学习
- P1073 [NOIP2009 提高组] 最优贸易 题解 分层图最短路
- Wechat applet page returns and passes parameters
- LabVIEW控制Arduino实现红外测距(进阶篇—6)
- Typecho模板 vCards/简约个性便的个人博客主题模板
- QT---创建对话框3:形状可变对话框的实现
- Stm32f1 and stm32subeide quick start - overview of interrupts, NVIC and exti
猜你喜欢

Common string input stream collation (gets (), fgets, getline (), cin get()、cin. getline())

Using fieldmask to improve c grpc service performance yyds dry inventory

【动态规划】博弈论:取石子游戏合集

LabVIEW控制Arduino实现红外测距(进阶篇—6)

Teleyecontroller v8.69 reconfiguration of keyboard recording function release by:yose

LabVIEW host computer and factory MES docking case communication program, supporting server and client

Practical experience exchange meeting on digital transformation of manufacturing industry held in Yizhuang

Where will the alarm messages go? Fly in the flying book

Alibaba cloud OCR image recognition process

Learn regular expressions in less than one round
随机推荐
Nextcloud internal server error the server cannot complete your request workaround
Teacher lihongyi's notes on machine learning -4.2 batch normalization
Efficiency improvement: realize personal task management and monitoring with notation
bson,json
刘勇智:一码通缺陷分析与架构设计方案丨声网开发者创业讲堂 Vol.02
Alibaba cloud OCR image recognition process
Oriental Star Hotel Management Catering project - query function
Leetcode game 79 biweekly - complete all questions
Saccadenet: use corner features to fine tune the two stage prediction frame | CVPR 2020
Teacher lihongyi's notes on machine learning -4.1 self attention
一本通1281.最长上升子序列 题解 动态规划
Using fieldmask to improve c grpc service performance yyds dry inventory
spark 避免对一个列重复解析json
SM2 state secret encryption and signing operation tool
Fastjson利用笔记
ShardingSphere实践(6)——弹性伸缩
Nignx configuring websocket
Ytu - C language exercises half search
Spark avoids repeatedly parsing JSON for a column
电脑新加内存条后 游戏崩溃 浏览器卡死 电脑蓝屏