SpringBoot整合SpringSecurity时需要注意的问题

前一段时间整合了一下SpringBoot+SpringSecurity+JWT,整合时JWT还好说,但是SpringSecurity出现的问题比较多,下面上源码图在这里插入图片描述在这里插入图片描述
在这里插入图片描述
这里SpringSecurity中设定死了登录时的用户名和密码的key
为username和password,
在这里插入图片描述
还有表单的提交路径和请求方式都固定了,但是表单提交时的路径可以通过在这里插入图片描述
这里修改,还有别的问题,但是由于时间不充裕,以后有时间补上,文章末尾会提供此处代码

/**
 * @Description: SpringSecurity配置类
 * @Author: 臧东运
 * @CreateTime: 2019/4/15 17:15
 */
@Configuration
@EnableWebSecurity
public class SpringSecurityConfig extends WebSecurityConfigurerAdapter {

    @Autowired
    private JwtUserDetailsService userDetailsService;  // 用户权限认证

    @Autowired
    private PasswordEncoder passwordEncoder;  // 密码编码

    @Autowired
    private JwtAuthenticationEntryPoint authenticationEntryPoint;  //  未登陆

    @Autowired
    private JwtAuthenticationSuccessHandler authenticationSuccessHandler;  // 登录成功

    @Autowired
    private JwtAuthenticationFailureHandler authenticationFailureHandler;  //  登录失败

    @Autowired
    private JwtLogoutSuccessHandler logoutSuccessHandler;  // 注销成功

    @Autowired
    private JwtAccessDeniedHandler accessDeniedHandler;    // 无权访问


    @Value("${jwt.exceptUrl}")
    private String exceptUrl;     // 从配置文件中读取

    @Value("${jwt.loginUrl}")
    private String loginUrl;

    @Value("${jwt.indexUrl}")
    private String indexUrl;

    @Override
    protected void configure(AuthenticationManagerBuilder authenticationManagerBuilder) throws Exception {
        // 加入自定义的安全认证
        authenticationManagerBuilder
//                .inMemoryAuthentication()  // 生成缓存数据
//                .withUser("111").password(passwordEncoder.encode("111")).roles("USER","ADMIN")
//                .and()
//                .withUser("222").password(passwordEncoder.encode("222")).roles("USER")
//                .and()
//                .withUser("333").password("333").roles("ADMIN");
//         设置UserDetailsService
                .userDetailsService(userDetailsService)
//                 使用BCrypt进行密码的hash
                .passwordEncoder(passwordEncoder);
    }

    @Override
    protected void configure(HttpSecurity httpSecurity) throws Exception {
        httpSecurity
                // 由于使用的是JWT,我们这里不需要csrf
                .csrf().disable()

                .authorizeRequests()
                // 允许无授权访问
                .antMatchers(exceptUrl).permitAll()
                .antMatchers(loginUrl,"/js/**","/css/**","/noauth/index.html").permitAll()
                // 除上面外的所有请求全部需要鉴权认证
                .anyRequest().authenticated().and()

                .httpBasic().authenticationEntryPoint(authenticationEntryPoint).and()
                .formLogin().loginPage(loginUrl)  //开启登录
                .loginProcessingUrl("/login").permitAll()//指定自定义form表单请求的路径
                .successHandler(authenticationSuccessHandler) // 登录成功
                .failureHandler(authenticationFailureHandler) // 登录失败
                .permitAll().and()

                .logout()
                .logoutSuccessHandler(logoutSuccessHandler)
                .permitAll().and();


                // 基于token,所以不需要session
//                .sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS).and();

        // 禁用缓存
//        httpSecurity.headers().cacheControl();
    }
}

如果发现什么问题请留言,毕竟代码都是人写的难免会出错。

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Spring Boot整合Spring Security主要是为了提供安全控制功能,帮助开发者快速地在Spring Boot应用中添加身份验证、授权和会话管理等安全性措施。以下是基本步骤: 1. 添加依赖:首先,在Maven或Gradle目中添加Spring Security的相关依赖到pom.xml或build.gradle文件中。 ```xml <!-- Maven --> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-security</artifactId> </dependency> <!-- Gradle --> implementation 'org.springframework.boot:spring-boot-starter-security' ``` 2. 配置WebSecurityConfigurerAdapter:在`src/main/resources/application.properties`或application.yml中配置一些基础属性,如启用HTTPS、密码加密策略等。然后创建一个实现了`WebSecurityConfigurerAdapter`的类,进行具体的配置,如设置登录页面、认证器、过滤器等。 ```java @Configuration @EnableWebSecurity public class SecurityConfig extends WebSecurityConfigurerAdapter { @Override protected void configure(HttpSecurity http) throws Exception { http.authorizeRequests() .antMatchers("/css/**", "/js/**", "/images/**").permitAll() // 允许静态资源访问 .anyRequest().authenticated() // 所有其他请求需要认证 .and() .formLogin() // 设置基于表单的身份验证 .loginPage("/login") // 登录页URL .defaultSuccessUrl("/") // 登录成功后的默认跳转URL .usernameParameter("username") .passwordParameter("password") .and() .logout() // 注销功能 .logoutUrl("/logout") .logoutSuccessUrl("/") .deleteCookies("JSESSIONID"); } // ... 其他配置如自定义用户DetailsService、密码编码器等 } ``` 3. 用户服务(UserDetailsService):如果需要从数据库或其他数据源获取用户信息,需要实现`UserDetailsService`接口并提供用户查询逻辑。 4. 运行应用:启动Spring Boot应用后,Spring Security将自动处理HTTP请求的安全检查,例如身份验证和授权。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值