SpringSecurity系列——用户认证后的数据获取,跨域解决方案day7-2(源于官网5.7.2版本)
用户认证后的数据获取
关于SecurityContextHolder
在前面的认证架构中我们可以知道:
SecurityContextHolder用来获取登录之后用户信息。Spring Security会将登录用户数据保存在Session中。但是,为了使用方便,Spring Security在此基础上还做了一些改进,其中最主要的一个变化就是线程绑定。当用户登录成功后,Spring Security 会将登录成功的用户信息保存到 SecurityContextHolder中。SecurityContextHolder中的数据保存默认是通过ThreadLocal来实现的,使用ThreadLocal 创建的变量只能被当前线程访问,不能被其他线程访问和修改,也就是用户数据和请求线程绑定在一起。当登录请求处理完毕后,Spring Security 会将SecurityContextHolder中的数据拿出来保存到Session中,同时将SecurityContexHolder中的数据清空。以后每当有请求到来时,Spring Security就会先从 Session中取出用户登录数据,保存到SecurityContextHolder中,方便在该请求的后续处理过程中使用,同时在请求结束时将SecurityContextHolder中的数据拿出来保存到Session中,然后将Security
SecurityContextHolder中的数据清空。这一策略非常方便用户在Controller、Service层以及任何代码中获取当前登录用户数据。
实例
由此我们得知获取用户信息可以先使用SecurityContextHolder获取到Authentication再获取下面的三个具体的用户信息,凭证信息,权限信息
public String test1() throws JsonProcessingException {
//获取SecurityContext
SecurityContext context = SecurityContextHolder.getContext();
//获取Authentication
Authentication authentication = context.getAuthentication();
//获取principal
Object principal = authentication.getPrincipal();
ObjectMapper objectMapper = new ObjectMapper();
String s = objectMapper.writeValueAsString(principal);
//获取authorities
Collection<? extends GrantedAuthority> authorities = authentication.getAuthorities();
//获取credentials
Object credentials = authentication.getCredentials();
String s1 = objectMapper.writeValueAsString(credentials);
System.out.println(context);
System.out.println(authentication);
System.out.println(s);
authorities.forEach(System.out::println);
System.out.println(s1);
return s;
}
SecurityContext:
SecurityContextImpl [Authentication=UsernamePasswordAuthenticationToken [Principal=org.springframework.security.core.userdetails.User [Username=user1, Password=[PROTECTED], Enabled=true, AccountNonExpired=true, credentialsNonExpired=true, AccountNonLocked=true, Granted Authorities=[ROLE_user]], Credentials=[PROTECTED], Authenticated=true, Details=WebAuthenticationDetails [RemoteIpAddress=127.0.0.1, SessionId=8DF5D4862E9A12C22CD5413A6F5CEEDD], Granted Authorities=[ROLE_user]]]
Authentication
UsernamePasswordAuthenticationToken [Principal=org.springframework.security.core.userdetails.User [Username=user1, Password=[PROTECTED], Enabled=true, AccountNonExpired=true, credentialsNonExpired=true, AccountNonLocked=true, Granted Authorities=[ROLE_user]], Credentials=[PROTECTED], Authenticated=true, Details=WebAuthenticationDetails [RemoteIpAddress=127.0.0.1, SessionId=8DF5D4862E9A12C22CD5413A6F5CEEDD], Granted Authorities=[ROLE_user]]
principal
{“password”:null,“username”:“user1”,“authorities”:[{“authority”:“ROLE_user”}],“accountNonExpired”:true,“accountNonLocked”:true,“credentialsNonExpired”:true,“enabled”:true}
authorities
ROLE_user
credentials
null
获取具体用户信息
由上面的实例我们可以知道authentication.getPrincipal()
可以获取用户的具体信息,具体获取里面的信息我们需要将其转换为User类,当然这个类是SpringSecurity内部提供的
Object principal = authentication.getPrincipal();
User user = (User) principal;
System.out.println(user.getUsername());
System.out.println(user.getAuthorities());
System.out.println(user.getPassword());
System.out.println(user.isEnabled());
如下,打印了用户名,权限,密码,是否被启用
当然密码是null不可见形式
注意点:默认子线程不可获取用户信息
默认情况下当我们开启一个子线程时,在我们的子线程中是无法获取用户信息的
new Thread(()->{
User principal1 = (User) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
System.out.println(principal1);
}).start();
如下会报空指针
解决子线程获取问题(多线程情况下)
我们可以通过使用MODE_INHERITABLETHREADLOCAL
实现子线程获取用户数据
但这个修改并不是在代码中的而是系统的,所以我们要通过修改虚拟机参数来实现
首先编辑配置
填入虚拟机选项
-Dspring.security.strategy=MODE_INHERITABLETHREADLOCAL
此时子线程(多线程情况下)中就可以获取到用户的信息了
CORS跨域解决方案
什么是CORS
CORS (Cross-Origin Resource Sharing)是由W3C制定的一种跨域资源共享技术标准,其目的就是为了解决前端的跨域请求。在JavaEE开发中,最常见的前端跨域请求解决方案是早期的JSONP,但是JSONP只支持GET请求,这是一个很大的缺陷,而CORS则支特多种HTTTP请求方法,也是目前主流的跨域解决方案。
CORS 中新增了一组HTTP请求头字段,通过这些字段,服务器告诉浏览器,那些网站通过浏览器有权限访问哪些资源。同时规定,对那些可能修改服务器数据的HTTP请求方法(如GET以外的HTTP请求等),浏览器必须首先使用OPTIONS方法发起一个预检请求
(prenightst) ,预检请求的目的是查看服务端是否支持即将发起的跨域请求,如果服务端允许,才发送实际的HTTP请求。在预检请求的返回中,服务器端也可以通知客户端,是否需要携带身份凭证(如Cookies、HTTP认证信息等)。
例如:
8080端口请求9000端口资源,就是跨域
如果服务端支持该跨域请求,那么返回的响应头中将包含如下字段:
Access-Contro1-Allow-Origin:http: // localhost: 8081
Access-Control-Allow-Origin字段用来告诉浏览器可以访问该资源的域,当浏览器收到这样的响应头信息之后,提取出Access-Control-Allow-Origin字段中的值,发现该值包含当前页面所在的域,就知道这个跨域是被允许的,因此就不再对前端的跨域请求进行限制。这属于简单请求,即不需要进行预检请求的跨域。
CORS处理
Spring Framework 为 CORS 提供一流的支持。 CORS 必须在 Spring Security 之前处理,因为 pre-flight 请求不会包含任何 cookie(即 JSESSIONID)。 如果请求不包含任何 cookie 并且 Spring Security 优先,则请求将确定用户未通过身份验证(因为请求中没有 cookie)并拒绝它。
确保首先处理 CORS 的最简单方法是使用 CorsFilter。 用户可以通过使用以下方式提供 CorsConfigurationSource 来将 CorsFilter 与 Spring Security 集成:
@EnableWebSecurity
public class WebSecurityConfig {
@Bean
public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
http
// by default uses a Bean by the name of corsConfigurationSource
.cors(withDefaults())
...
return http.build();
}
@Bean
CorsConfigurationSource corsConfigurationSource() {
CorsConfiguration configuration = new CorsConfiguration();
configuration.setAllowedOrigins(Arrays.asList("https://example.com"));
configuration.setAllowedMethods(Arrays.asList("GET","POST"));
UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
source.registerCorsConfiguration("/**", configuration);
return source;
}
}
如果您使用 Spring MVC 的 CORS 支持,则可以省略指定 CorsConfigurationSource 并且 Spring Security 将利用提供给 Spring MVC 的 CORS 配置。
@EnableWebSecurity
public class WebSecurityConfig {
@Bean
public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
http
// if Spring MVC is on classpath and no CorsConfigurationSource is provided,
// Spring Security will use CORS configuration provided to Spring MVC
.cors(withDefaults())
...
return http.build();
}
}
CORS实例
1.@CrossOrigin注解
Spring 中第一种处理跨域的方式是通过@CrossOrigin注解来标记支持跨域,该注解可以添加在方法上,也可以添加在Controller上。当添加在Controller上时,表示Controller中的所有接口都支持跨域,具体配置如下:
@GetMapping("/index")
@CrossOrigin(origins = "*")
public String indexTest(){
return "index ...";
}
@CrossOrigin注解各属性含义如下:
- alowCredentials:浏览器是否应当发送凭证信息,如Cookie。
- allowedFeaders:请求被允许的请求头宇段,*表示所有宇段
- exposedHeaders:哪些响应头可以作为响应的一部分暴露出来。注意,这里只可以一一列举,通配符*在这里是无效的。
- maxAge:预检请求的有效期,有效期内不必再次发送预检请求,默认是1800秒。
- methods:允许的请求方法,*表示允许所有方法。
- origins:允许的域,*表示允许所有域。
2.SpringMVC跨域配置
@Configuration
public class WebMVCConfig implements WebMvcConfigurer {
@Override
public void addCorsMappings(CorsRegistry registry) {
registry.addMapping("/**")
.allowedOriginPatterns("*")
.allowedMethods("POST","GET")
.allowCredentials(true)
.maxAge(3600);
}
}
前端返回
3.SpringSecurity跨域处理
首先了解一点,SpringSecurity中要是使用以上的跨域处理则会失效
使用SpringSecurity的跨域处理则需要在SpringSecurityConfig中进行
主要配置
//配置CORS策略
@Bean
public CorsConfigurationSource corsConfigurationSource(){
CorsConfiguration corsConfiguration = new CorsConfiguration();
corsConfiguration.setAllowedMethods(Arrays.asList("*"));
corsConfiguration.setAllowedHeaders(Arrays.asList("*"));
corsConfiguration.setMaxAge(3600L);
corsConfiguration.setAllowedOrigins(Arrays.asList("*"));
UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
source.registerCorsConfiguration("/**",corsConfiguration);
return source;
}
//添加策略
httpSecurity.cors()
.configurationSource(corsConfigurationSource())
完整配置
package com.example.pwdencode.config;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.Customizer;
import org.springframework.security.config.annotation.method.configuration.EnableMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
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.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.provisioning.InMemoryUserDetailsManager;
import org.springframework.security.web.SecurityFilterChain;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.CorsConfigurationSource;
import org.springframework.web.cors.UrlBasedCorsConfigurationSource;
import java.util.Arrays;
@EnableMethodSecurity
@EnableWebSecurity
@Configuration
public class SpringSecurityConfig {
@Bean
public CorsConfigurationSource corsConfigurationSource(){
CorsConfiguration corsConfiguration = new CorsConfiguration();
corsConfiguration.setAllowedMethods(Arrays.asList("*"));
corsConfiguration.setAllowedHeaders(Arrays.asList("*"));
corsConfiguration.setMaxAge(3600L);
corsConfiguration.setAllowedOrigins(Arrays.asList("*"));
UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
source.registerCorsConfiguration("/**",corsConfiguration);
return source;
}
@Bean
public PasswordEncoder passwordEncoder(){
return new BCryptPasswordEncoder();
}
@Bean
public UserDetailsService userDetails(){
UserDetails build = User.withUsername("user1").password("$2a$10$laiNvpYlylmnWMhiPjFFHuEfHeZJUY2MlosV1bba4rG.IiadN6Sry").roles("user").build();
InMemoryUserDetailsManager inMemoryUserDetailsManager = new InMemoryUserDetailsManager(build);
return inMemoryUserDetailsManager;
}
@Bean
public SecurityFilterChain securityFilterChain(HttpSecurity httpSecurity) throws Exception {
return httpSecurity.csrf().disable()
.authorizeHttpRequests(auth->auth.mvcMatchers("/index").permitAll())
.formLogin(Customizer.withDefaults())
.httpBasic(Customizer.withDefaults())
.userDetailsService(userDetails())
.cors()
.configurationSource(corsConfigurationSource())
.and()
.build();
}
}