SpringSecurity的使用

Spring Security

Spring Security是Spring为JAVA应用程序提供的一个身份认证权限校验的安全框架,Spring Security的两大核心共功能:用户认证和用户授权

1、SpringSecurity的配置,必须继承WebSecurityConfigurerAdapter,并加上@EnableWebSecurity注解。
2、当我们想要开启Spring的方法级安全时,只需要在任何 @Configuration实例上使用 @EnableGlobalMethodSecurity 注解就能达到此目的。同时这个注解为我们提供了prePostEnabled 、securedEnabled 和 jsr250Enabled 三种不同的机制来实现同一种功能。
图片来源于网络

@Configuration
//开启判断用户对某个控制层的方法是否具有访问权限的功能
@EnableGlobalMethodSecurity(prePostEnabled = true)
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
    //注入自定义的UserDetailService
    @Autowired
    @Lazy
    private UserDetailsServiceImpl userDetailsServiceImpl;
    @Autowired
    private StringRedisTemplate stringRedisTemplate;
    @Autowired
    private CorsfConfigurationSource corsfConfigurationSource;

    //替换默认AuthenticationManager中的UserDetailService,使用数据库用户认证方式登录
    //1. 一旦通过 configure 方法自定义 AuthenticationManager实现 就回将工厂中自动配置AuthenticationManager 进行覆盖
    //2. 一旦通过 configure 方法自定义 AuthenticationManager实现 需要在实现中指定认证数据源对象 UserDetailService 实例
    //3. 一旦通过 configure 方法自定义 AuthenticationManager实现 这种方式创建AuthenticationManager对象工厂内部本地一个 AuthenticationManager 对象 不允许在其他自定义组件中进行注入
    @Override
    protected void configure(AuthenticationManagerBuilder builder) throws Exception {
        builder.userDetailsService(userDetailsServiceImpl);
    }

    /**
     * BCryptPasswordEncoder相关知识:
     * 用户表的密码通常使用MD5等不可逆算法加密后存储,为防止彩虹表破解更会先使用一个特定的字符串(如域名)加密,然后再使用一个随机的salt(盐值)加密。
     * 特定字符串是程序代码中固定的,salt是每个密码单独随机,一般给用户表加一个字段单独存储,比较麻烦。
     * BCrypt算法将salt随机并混入最终加密后的密码,验证时也无需单独提供之前的salt,从而无需单独处理salt问题。
     */
    @Bean
    public BCryptPasswordEncoder passwordEncoder() {
        return new BCryptPasswordEncoder();
    }


    //将自定义AuthenticationManager在工厂中进行暴露,可以在任何位置注入
    @Override
    @Bean
    public AuthenticationManager authenticationManagerBean() throws Exception {
        return super.authenticationManagerBean();
    }

    //HttpSecurity配置
    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.cors(withDefaults())
                // 禁用 CSRF
                .csrf().disable()
                .authorizeRequests()
                // 指定的接口直接放行
                // swagger
                .antMatchers(SecurityConstants.SWAGGER_WHITELIST).permitAll()
                .antMatchers(SecurityConstants.H2_CONSOLE).permitAll()
                .antMatchers(HttpMethod.POST, SecurityConstants.SYSTEM_WHITELIST).permitAll()
                // 其他的接口都需要认证后才能请求
                .anyRequest().authenticated()
                .and()
                //添加自定义Filter
                .addFilter(new JwtAuthorizationFilter(authenticationManager(), stringRedisTemplate))
                // 不需要session(不创建会话)
                .sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS).and()
                // 授权异常处理
                .exceptionHandling()
                // json提示用户没有登录不需要用户跳转到登录页面去
                .authenticationEntryPoint(new JwtAuthenticationEntryPoint())
                // 权限拦截器,提示用户没有当前权限
                .accessDeniedHandler(new JwtAccessDeniedHandler())
                //配置springSecurity的跨域
                .and()
                .cors().configurationSource(corsfConfigurationSource);
        // 防止H2 web 页面的Frame 被拦截
        http.headers().frameOptions().disable();
    }

    /**
     * Cors配置优化
     **/
    @Bean
    CorsConfigurationSource corsConfigurationSource() {
        org.springframework.web.cors.CorsConfiguration configuration = new CorsConfiguration();
        configuration.setAllowedOrigins(singletonList("*"));
        // configuration.setAllowedOriginPatterns(singletonList("*"));
        configuration.setAllowedHeaders(singletonList("*"));
        configuration.setAllowedMethods(Arrays.asList("GET", "POST", "DELETE", "PUT", "OPTIONS"));
        configuration.setExposedHeaders(singletonList(SecurityConstants.TOKEN_HEADER));
        configuration.setAllowCredentials(false);
        configuration.setMaxAge(3600L);
        UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
        source.registerCorsConfiguration("/**", configuration);
        return source;
    }
}

UsernamePasswordAuthention的认证基本流程:
1.先获取一个AuthenticationManager的实现类对象==》ProviderManager(提供者管理器)–提供校验方法
//注意:this.getAuthenticationManager(),这里springSecurity在创建UsernamePasswordAuthenticationFilter对象的时候就已 经将"AuthenticationManager"设置为ProviderManager,AuthenticationManager是UsernamePasswordAuthenticationFilter从父类AbstractUserDetailsAuthenticationProvider继承到的属性
2.调用AuthenticationManager(认证管理器)的实现类对象ProviderManager的authenticate方法(传入一个令牌:UsernamePassworldAuthentionToken对象)获取一个Authentication的实现类对象(UsernamePassworldAuthentionToken)
3.在authenticate方法中先获取到所有的Provider(提供者)集合,再对Provider集合进行遍历,通过provider.supports(toTest)从8个Provider中找到支持UsernamePassworld的Provider,调用该Provider的authenticate方法(传入一个令牌:UsernamePassworldAuthentionToken对象)
4.在authenticate方法中调用了一个抽象方法retrieveUser,retrieveUser方法被DaoAuthenticationProvider实现,所以归根结底来说是调用DaoAuthenticationProvider的retrieveUser方法
5.在DaoAuthenticationProvider的retrieveUser方法中通过this.getUserDetailsService()获取了一个UserDetailsService的实现类对象,并调用UserDetailsService的实现类对象的loadUserByUsername方法返回一个UserDetails,最终authenticate方法通过调用retrieveUser方法获取了一个UserDetails对象
6.通过在WebSecurityConfigurerAdapter的子类中指定我们自己的UserDetailsService的实现类,来告诉SpringSecurity使用我们自己编写的实现类中。

package com.qfstudy.websocket.congfig;

import com.qfstudy.websocket.service.MyUserDetailService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.builders.WebSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;

@EnableWebSecurity
@EnableGlobalMethodSecurity(prePostEnabled = true,securedEnabled = true)
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
    @Autowired
    private BCryptPasswordEncoder bCryptPassworldEncoder;
    @Autowired
    private MyUserDetailService myUserDetailService;
    @Override
    //配置数据库认证以及密码的加密规则
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
/*      1.先获取一个AuthenticationManager的实现类对象==》ProviderManager(提供者管理器)--提供校验方法
        //注意:this.getAuthenticationManager(),这里springSecurity在创建UsernamePasswordAuthenticationFilter对象的时候就已经将"AuthenticationManager"设置为ProviderManager,AuthenticationManager是UsernamePasswordAuthenticationFilter从父类AbstractUserDetailsAuthenticationProvider继承到的属性
        2.调用AuthenticationManager(认证管理器)的实现类对象ProviderManager的authenticate方法(传入一个令牌:UsernamePassworldAuthentionToken对象)获取一个Authentication的实现类对象(UsernamePassworldAuthentionToken)
        3.在authenticate方法中先获取到所有的Provider(提供者)集合,再对Provider集合进行遍历,通过provider.supports(toTest)从8个Provider中找到支持UsernamePassworld的Provider,调用该Provider的authenticate方法(传入一个令牌:UsernamePassworldAuthentionToken对象)
        4.在authenticate方法中调用了一个抽象方法retrieveUser,retrieveUser方法被DaoAuthenticationProvider实现,所以归根结底来说是调用DaoAuthenticationProvider的retrieveUser方法
        5.在DaoAuthenticationProvider的retrieveUser方法中通过this.getUserDetailsService()获取了一个UserDetailsService的实现类对象,并调用UserDetailsService的实现类对象的loadUserByUsername方法返回一个UserDetails,最终authenticate方法通过调用retrieveUser方法获取了一个UserDetails对象
        6.通过在WebSecurityConfigurerAdapter的子类中指定我们自己的UserDetailsService的实现类,来告诉SpringSecurity使用我们自己编写的实现类中。
*/
        auth.userDetailsService(myUserDetailService).passwordEncoder(bCryptPassworldEncoder);
    }
    //配置静态资源的放行策略
    @Override
    public void configure(WebSecurity web) throws Exception {
        super.configure(web);
    }
    //配置http的访问规则
    @Override
    protected void configure(HttpSecurity http) throws Exception {
        super.configure(http);
    }
}

参考:https://liush.blog.csdn.net/article/details/129396711

在这里插入图片描述

SpringSecurity重写DaoAuthenticationProvider,自定义密码对比类

参考1

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值