Spring Security 官方demo学习

Spring Security提供了一种简单、灵活且强大的机制来保护Web应用程序。借助一系列Servlet Filter能够控制对Web资源的访问,包括MVC控制器。借助于Java配置模型,能够简洁的声明Web安全性功能。
当认证用户是,可以使用基于内存用户库、关系型数据库、LDAP目录服务器来配置认证功能。

一. 查看Spring Security 官方文档

https://spring.io/projects/spring-security#learn

二. 上面的文档界面一直拉到底,可以看到如下界面,Guides会教你创建一个 Spring Security 的demo

https://spring.io/projects/spring-security#learn

三. 点开 Securing a Web Application,进入到Guides具体的创建步骤界面,如下:

https://spring.io/guides/gs/securing-web/

四. Demo验证

在浏览器中输入 http://localhost:8080,点击here

会跳转到登陆页,http://localhost:8080/login

登录成功页面:http://localhost:8080/hello

当你退出登录后,直接在浏览器中输入hello界面,会被自动拦截到登录页面。

五. 主要逻辑代码片段

package com.example.securingweb;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
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.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.provisioning.InMemoryUserDetailsManager;

@Configuration
@EnableWebSecurity
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
	@Override
	protected void configure(HttpSecurity http) throws Exception {

		/**
		 *  @auther: TF12778
		 *  @date:   2020/6/10 10:41
		 *  @description:
		 *  1. 允许访问路径"/"或者"/home",而不需要登录。
		 *  除过"/"或者"/home",其他页面都需要登录。
		 *  2. 表单登录,路径是"/login",允许所有用户都可以发起登录操作
		 *  3. 允许所有用户都可以退出登录
		 */
		http
			.authorizeRequests()
				.antMatchers("/", "/home").permitAll() // 假如去掉这行的话,所有页面都需要登录
				.anyRequest().authenticated()
				.and()
			.formLogin()
				.loginPage("/login")
				.permitAll()
				.and()
			.logout()
				.permitAll();
	}

	@Bean
	@Override
	public UserDetailsService userDetailsService() {
		
		/**
		 *  @auther: TF12778
		 *  @date:   2020/6/10 10:45
		 *  @description:
		 *  登录的帐号:"user"和密码:"password"
		 */
		UserDetails user =
			 User.withDefaultPasswordEncoder()
				.username("user")
				.password("password")
				.roles("USER")
				.build();

		return new InMemoryUserDetailsManager(user);
	}
}

猜你喜欢

转载自blog.csdn.net/robinson_911/article/details/106646560