专题指南
设计用于在一小时或更短的时间内阅读和理解,提供比入门指南更广泛或主观的内容。
Spring安全体系结构
1.1SpringSecurity专题指南,这些位如何组合在一起,以及它们如何与SpringBoot交互
我们只介绍了应用程序安全性的基本知识,但这样做可以消除使用Spring安全性的开发人员所遇到的一些困惑。为了做到这一点,我们研究了安全性在使用过滤器的web应用程序中的应用方式,通常使用方法注释。
1.2身份验证和访问控制
身份验证(您是谁?)以及授权(你可以做什么?)。有时人们会说“访问控制”而不是“授权”,这可能会让人感到困惑,但这样想会有帮助,因为“授权”在其他地方超载了。Spring Security有一个体系结构,该体系结构旨在将身份验证和授权分离开来,并且具有用于两者的策略和扩展点
2.身份验证
public interface AuthenticationProvider {
Authentication authenticate(Authentication authentication)
throws AuthenticationException;
boolean supports(Class<?> authentication);
}
ProviderManager可以通过委托给AuthenticationProviders链在同一个应用程序中支持多个不同的身份验证机制。如果ProviderManager无法识别特定的身份验证实例类型,则将跳过它。
2.1 公共类扩展
@Configuration
public class ApplicationSecurity extends WebSecurityConfigurerAdapter {
... // web stuff here
@Autowired
public void initialize(AuthenticationManagerBuilder builder, DataSource dataSource) {
builder.jdbcAuthentication().dataSource(dataSource).withUser("dave")
.password("secret").roles("USER");
}
}
3.MAVEN库必须包含
项目中安全认证必须包含spring-boot-starter-security依赖。
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
</dependency>
那么当Spring Security启动,会默认一个用户user,代码里面设置的用户名user和密码为password
3.1 代码
package com.dacha.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 {
http
.authorizeRequests()
.antMatchers("/", "/home").permitAll()
.anyRequest().authenticated()
.and()
.formLogin()
.loginPage("/login")
.permitAll()
.and()
.logout()
.permitAll();
}
@Bean
@Override
public UserDetailsService userDetailsService() {
UserDetails user =
User.withDefaultPasswordEncoder()
.username("user")
.password("password")
.roles("USER")
.build();
return new InMemoryUserDetailsManager(user);
}
}
WebSecurityConfig类用@enable web Security注释,以启用springsecurity的web安全支持并提供Spring MVC集成。
它还扩展了WebSecurityConfigurerAdapter,并覆盖了它的一些方法来设置web安全配置的一些细节。
configure(HttpSecurity)方法定义哪些URL路径应该受到保护,哪些不应该受到保护。
所有其他路径都必须经过身份验证。当用户成功登录时,会将其重定向到先前请求的需要身份验证的页面。会去先请求登录界面
3.2 代码运行
userDetailsService()方法使用单个用户设置内存中的用户存储。
该用户被赋予用户名、密码和用户角色。例子中是写死的用户名和密码,实践这里会用用到数据库的地方。
如果输入错误的用户名或者密码,提示
如果登出,就提示这个