security配置

该文章详细展示了如何在SpringBoot应用中配置SpringSecurity进行用户认证和授权,包括自定义登录页面、表单登录处理、记住我功能以及使用JdbcTokenRepositoryImpl存储持久化token。同时,文章还涉及到跨域配置和密码编码器BCryptPasswordEncoder的使用。
摘要由CSDN通过智能技术生成
package login.config;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.web.authentication.rememberme.JdbcTokenRepositoryImpl;
import org.springframework.security.web.authentication.rememberme.PersistentTokenRepository;

import javax.sql.DataSource;

@Configuration
public class RememberMeConfig {
    @Autowired
    private DataSource dataSource;

    // 令牌Repository
    @Bean
    public PersistentTokenRepository getPersistentTokenRepository() {
// 为Spring Security自带的令牌控制器设置数据源
        JdbcTokenRepositoryImpl jdbcTokenRepositoryImpl = new JdbcTokenRepositoryImpl();
        jdbcTokenRepositoryImpl.setDataSource(dataSource);
//自动建表,第一次启动时需要,第二次启动时注释掉

//        jdbcTokenRepositoryImpl.setCreateTableOnStartup(true);
        return jdbcTokenRepositoryImpl;
    }
}
import login.service.MyAuthenticationService;
import login.service.MyDetailsService;
import login.service.MyLogoutSuccessHandler;
import org.springframework.beans.factory.annotation.Autowired;
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.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.builders.WebSecurity;
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;
import org.springframework.security.web.authentication.rememberme.PersistentTokenRepository;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.CorsConfigurationSource;
import org.springframework.web.cors.UrlBasedCorsConfigurationSource;


@Configuration
public class SecurityConfig extends WebSecurityConfigurerAdapter {
    @Autowired
    private MyDetailsService myDetailsService;
    @Autowired
    private PersistentTokenRepository persistentTokenRepository;
    @Autowired
    private UserDetailsService userDetailsService;
    @Autowired
    private MyAuthenticationService myAuthenticationService;

    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.userDetailsService(myDetailsService);
    }

    @Override
    public void configure(WebSecurity web) throws Exception {web.ignoring().antMatchers("/setUser").antMatchers("/user");
        super.configure(web);
    }

    //Spring Security配置
    @Override
    protected void configure(HttpSecurity http) throws Exception {
//         自定义表单登录
        http.formLogin()
                .loginPage("/loginU")
//                .loginProcessingUrl("/loginU")
//                .successForwardUrl("/details")
                .usernameParameter("name")
                .passwordParameter("password")
                .loginProcessingUrl("/loginU")
                .successHandler(myAuthenticationService)
                .failureHandler(myAuthenticationService);

//                .and().rememberMe()
//                .tokenValiditySeconds(120960000)
//                .and().authorizeRequests().antMatchers("/sendyzm").permitAll()
//                .anyRequest().authenticated();


        // 需要认证的资源
        http.authorizeRequests()
                .antMatchers("/loginUser").permitAll() //登录页不需要认证
                .antMatchers("/setUser").permitAll()

                ; //其余所有请求都需要认证

        // 退出登录配置
        http.logout()
                .logoutUrl("/logout") // 退出登录路径
                .logoutSuccessHandler(new MyLogoutSuccessHandler())
                .clearAuthentication(true) //清除认证状态,默认为true
                .invalidateHttpSession(true); // 销毁HttpSession对象,默认为true
//
// 记住我配置
        http.rememberMe()
                .userDetailsService(userDetailsService)//登 录逻辑交给哪个对象
                .tokenRepository(persistentTokenRepository)//持久 层对象
                .tokenValiditySeconds(60); //保存时间,单位:秒

        http.authorizeHttpRequests()
                .anyRequest()
                .authenticated()
                .and()
                .formLogin()
                .and()
                .rememberMe()
                .and()
                .csrf()
                .disable();

        http.cors();//跨域

    }
        //关闭csrf防护
//        http.csrf().disable();

//    public CorsConfigurationSource corsConfigurationSource(){
//        CorsConfiguration corsConfiguration = new CorsConfiguration();
//        //允许跨域的站点
//        corsConfiguration.addAllowedOrigin("*");
//        //允许跨域的方法
//        corsConfiguration.addAllowedMethod("*");
//        //允许跨域的请求头
//        corsConfiguration.addAllowedHeader("*");
//        //对所有url都生效
//
//        UrlBasedCorsConfigurationSource urlBasedCorsConfigurationSource = new UrlBasedCorsConfigurationSource();
//
//        urlBasedCorsConfigurationSource.registerCorsConfiguration("/**",corsConfiguration);
//        return urlBasedCorsConfigurationSource;
//    }


//
//
//    @Override
//    public void configure(WebSecurity web) throws Exception {
//        // 静态资源放行
//        web.ignoring().antMatchers("/css/**");
//    }

    //密码编码器
    @Bean
    public PasswordEncoder passwordEncoder() {
        return new BCryptPasswordEncoder();
    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值