Spring Security 认证相关知识点总结

yml 配置

spring:
  security:
    user:
      name: 自定义用户名(不推荐)
      password: 自定义密码(不推荐)
      
 logging:
  level:
    # 打印 spring security 全部日志信息
    org.springframework.security: trace

web安全接口适配器

org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter

认证核心过滤器

org.springframework.security.web.authentication.AbstractAuthenticationProcessingFilter

用户核心信息接口

org.springframework.security.core.userdetails.UserDetails

获取用户信息核心服务

org.springframework.security.core.userdetails.UserDetailsService

获取当前线程中用户信息

Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
 Object principal = authentication.getPrincipal();
 if(principal instanceof UserDetails){
 // 获取用户名
 		String userName = ((UserDetails)principal).getUsername();
 }else{
 		String userName = principal.toString();
 }

用户登陆存储信息对象

org.springframework.security.authentication.UsernamePasswordAuthenticationToken

基础属性

authenticated 为 true 时,认证通过
authenticated 为 false 时,未认证通过

基础方法

getCredentials()

获取用户对象,大多数时候未UserDetails实现类

getDetails()

获取认证时的一些信息,返回通常是org.springframework.security.web.authentication.WebAuthenticationDetails用于获取获取sessionId和ip

用户权限创建工具

org.springframework.security.core.authority.AuthorityUtils

用户密码加密核心接口

org.springframework.security.crypto.password.PasswordEncoder

用户密码加密工具集

org.springframework.security.crypto.factory.PasswordEncoderFactories


用户账户权限认证(冻结、激活等)

org.springframework.security.core.userdetails.UserDetailsChecker

默认用户账户权限认证(账户冻结、激活等)

org.springframework.security.authentication.dao.AbstractUserDetailsAuthenticationProvider.DefaultPreAuthenticationChecks


csrf 安全过滤器

org.springframework.security.web.csrf.CsrfFilter

认证管理器

org.springframework.security.authentication.AuthenticationManager

用户缓存接口

org.springframework.security.core.userdetails.UserCache
可以实现此接口,实现用户信息集中缓存,例如存储到redis中


/**
* 核心认证接口,传入的时待认证对象,认证成功或失败,都会返回该对象
* 
* @param authentication 认证对象,authenticated为false,表示未经过认证
* @return 传入的参数,authenticated为false,表示未经过认证,为true时,通过认证
*/
Authentication authenticate(Authentication authentication) throws AuthenticationException;

配置推荐使用的密码加密工具

  @Bean
    public PasswordEncoder passwordEncoder(){
        return new BCryptPasswordEncoder();
    }

配置自定义获取用户信息接口

package com.example.securitydemo.componet;

import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Component;

/**
 * @author chunyang.leng
 * @date 2020/12/22 12:56 下午
 */
@Component("myUserDetailService")
public class MyUserDetailServiceImpl implements UserDetailsService {

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        // 执行数据库查询
        return null;
    }
}

重写配置并注入自己的相关配置

package com.example.securitydemo.config;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;

/**
 * @author chunyang.leng
 * @date 2020/12/21 1:18 下午
 */
@Configuration
public class MyWebSecurityConfig extends WebSecurityConfigurerAdapter {

    /**
     * 配置自己的用户获取方式
     */
    @Autowired
    @Qualifier("myUserDetailService")
    private UserDetailsService myUserDetailsService;

    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        // 在处理器中注入自己的获取用户实现类
        auth.userDetailsService(myUserDetailsService);
    }
		
     @Override
    protected void configure(HttpSecurity http) throws Exception {
        // 自定义http相关安全配置,比如自定义登陆界面,跨域过滤器等
        http
        // 表单登陆
        .formLogin() 
        // 设置登陆页面
        .loginPage("/login.html")
        .loginProcessingUrl("/user/login")   // 对应自定义页面的登陆接口
        .defaultSuccessUrl("/main")  // 登陆成功跳转的url
        .failureForwardUrl("/loginError") // 登陆失败跳转url
        .usernameParameter("") // 账号属性(默认值user)
        .passwordParameter(""); // 密码属性(默认值 password)
        
        
        // 授权设置
        http
          .authorizeRequests()
          // 配置不需要权限的接口或者页面
          .antMatchers("接口1","/login.html").permitAll()
          // 其他任意请求,均需要授权
          .anyRequest().authenticated();
          
        // 关闭csrf保护
        http.csrf().disable();
    }
    
    /**
    * 使用的密码加密工具
    */
    @Bean
    public PasswordEncoder passwordEncoder(){
        return new BCryptPasswordEncoder();
    }
}

鉴权使用注解:@PreAuthorize、@PostAuthorize、@PreFilter和@PostFilter
常用注解:@PreAuthorize
备注:该注解内部可以直接使用spring bean
示例:

   /**
     * 获取用户列表
     */
    @PreAuthorize("@auth.hasPermissionCode('system:user:list')")
    @GetMapping("/list")
    public TableDataInfo list(SysUser user) {
        return getDataTable(list);
    }

@Service("auth")
public class PermissionService {
	// 检查是否有权限
	public boolean hasPermissionCode(String permissionCode){
		return true;
	}
}
  • 0
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 1
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

北漂的菜小白

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值