Spring框架中SecurityContextHolder类的使用详解(未完待续)

5 篇文章 0 订阅
3 篇文章 0 订阅


Spring框架借助ThreadLocal来保存和传递用户登录信息。我们通常是使用下面这段代码,来获取保存在ThreadLocal中的用户信息。

SecurityContextHolder.getContext().getAuthentication().getPrincipal();


如果我们想获取用户的ID,可以这样:

String userId = SecurityContextHolder.getContext().getAuthentication().getPrincipal().getUserId();



一,我们来看一下源代码


public class SecurityContextHolder extends Object,这个类直接继承自Object
官方文档说明如下:
Associates a given SecurityContext with the current execution thread.
    这句话大概的意思是,SecurityContextHolder的主要功能是将当前正在执行的thread与SecurityContext关联起来。


进一步详细的说明是:
This class provides a series of static methods that delegate to an instance of 
SecurityContextHolderStrategy. The purpose of the class is to provide a convenient way to specify the strategy 
that should be used for a given JVM. This is a JVM-wide setting, since everything in this class is static to facilitate 

ease of use in calling code.


To specify which strategy should be used, you must provide a mode setting. A mode setting is one of the three valid 
MODE_ settings defined as static final fields, or a fully qualified classname to a concrete implementation of 
SecurityContextHolderStrategy that provides a public no-argument constructor.


There are two ways to specify the desired strategy mode String. The first is to specify it via the system property 
keyed on SYSTEM_PROPERTY. The second is to call setStrategyName(String) before using the class. If neither approach is used,
 the class will default to using MODE_THREADLOCAL, which is backwards compatible, has fewer JVM incompatibilities and is 
appropriate on servers (whereas MODE_GLOBAL is definitely inappropriate for server use).


SecurityContextHolder 类提供了8个成员方法,大部分都是static类型:
static SecurityContext getContext() 通过这个方法获得当前的SecurityContext 


SecurityContextHolder 类提供了8个成员方法,大部分都是static类型:
static SecurityContext getContext() 通过这个方法获得当前的SecurityContext 


然后,调用public interface SecurityContext extends Serializable,这个接口的  Authentication getAuthentication() 方法,
最后,调用public interface Authentication extends Principal, Serializable 接口的 Object getPrincipal() 方法,这个方法的官方说明
是:The identity of the principal being authenticated.


二,Spring的权限机制

流程:

1,用户登录;

2,根据用户ID,获取当前用户所拥有的所有权限;

3,把权限放到session中;

4,显示用户所拥有的资源。


下面我们来说一下详细的实现细节:


  • 6
    点赞
  • 18
    收藏
    觉得还不错? 一键收藏
  • 11
    评论
以下是在Spring Boot项目使用Spring Security的示例代码: 1. 添加依赖项: 在Maven构建文件添加以下依赖项: ``` <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-security</artifactId> </dependency> ``` 2. 创建Security配置: 创建一个来配置Spring Security,该需要继承WebSecurityConfigurerAdapter。以下是一个简单的示例: ``` @Configuration @EnableWebSecurity public class SecurityConfig extends WebSecurityConfigurerAdapter { @Autowired private UserDetailsService userDetailsService; @Autowired public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception { auth.userDetailsService(userDetailsService); } @Override protected void configure(HttpSecurity http) throws Exception { http .authorizeRequests() .antMatchers("/admin/**").hasRole("ADMIN") .antMatchers("/user/**").hasAnyRole("ADMIN", "USER") .anyRequest().authenticated() .and() .formLogin() .loginPage("/login") .permitAll() .and() .logout() .permitAll(); } } ``` 在上面的配置,我们指定了哪些URL需要保护,并定义了用户身份验证方式。具体来说: - configureGlobal方法用于配置用户存储,我们使用了一个实现了UserDetailsService接口的来加载用户信息。 - configure方法用于配置访问控制和身份验证方式。我们使用了一个基于角色的访问控制策略,指定了哪些URL需要哪些角色。我们还配置了登录页面和注销功能。 3. 配置用户存储: 我们可以使用内存,数据库或LDAP等不同型的存储来存储用户及其角色信息。以下是一个使用内存存储的示例: ``` @Service public class UserDetailsServiceImpl implements UserDetailsService { private Map<String, UserDetails> users = new HashMap<>(); public UserDetailsServiceImpl() { User admin = new User("admin", "{noop}admin123", AuthorityUtils.createAuthorityList("ROLE_ADMIN")); User user = new User("user", "{noop}user123", AuthorityUtils.createAuthorityList("ROLE_USER")); users.put(admin.getUsername(), admin); users.put(user.getUsername(), user); } @Override public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException { UserDetails user = users.get(username); if (user == null) { throw new UsernameNotFoundException("User not found: " + username); } return user; } } ``` 在上述示例,我们创建了两个用户,一个是管理员,一个是普通用户。我们使用了NoOpPasswordEncoder来存储用户密码。在实际项目,建议使用更安全的PasswordEncoder。 4. 配置登录和注销: 在Security配置,我们可以通过配置登录和注销URL,以及相关的身份验证和授权逻辑,来实现用户登录和注销功能。以下是一个简单的示例: ``` @Controller public class LoginController { @GetMapping("/login") public String login() { return "login"; } @GetMapping("/logout") public String logout(HttpServletRequest request, HttpServletResponse response) { Authentication auth = SecurityContextHolder.getContext().getAuthentication(); if (auth != null) { new SecurityContextLogoutHandler().logout(request, response, auth); } return "redirect:/login?logout"; } } ``` 在上述示例,我们定义了/login和/logout两个URL,分别用于用户登录和注销。我们使用Spring Security提供的SecurityContextHolder和SecurityContextLogoutHandler来实现注销功能。 5. 配置访问控制: 我们可以通过配置访问规则,以及使用注解或表达式来控制用户访问应用程序的各个部分。以下是一个使用注解控制访问的示例: ``` @Controller @RequestMapping("/user") public class UserController { @PreAuthorize("hasRole('USER')") @GetMapping("/profile") public String profile() { return "profile"; } } ``` 在上述示例,我们在UserController定义了/profile URL,并使用了@PreAuthorize注解来指定只有拥有USER角色的用户才能访问该URL。 这些示例代码可以帮助您在Spring Boot项目使用Spring Security。请注意,这只是一个简单的概述,实际实现可能会更加复杂。建议您查看Spring Security官方文档,以获取更详细的信息和示例代码。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 11
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值