Spring Security使用

本文介绍了在Spring Security实践中遇到的问题及解决方法。当出现'No bean named 'springSecurityFilterChain' available'异常时,解决方案是调整ContextLoaderListener的扫描范围。通过配置DelegatingFilterProxy和WebSecurityConfigurerAdapter,可以轻松创建一个登陆页面。当在configure(HttpSecurity)中添加formLogin(),即可恢复默认的登陆页面功能。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

写在前面,实践Spring Security遇到的坑:

org.springframework.beans.factory.NoSuchBeanDefinitionException: No bean named 'springSecurityFilterChain' available

出现该原因是Spring ContextLoaderListener 上下面加载不到该bean,应当让配置ContextLoaderListener上下文的扫描到该包:

/**
 * @Date 2019-05-03
 * @Author lifei
 */
@Configuration
@ComponentScan(basePackages = {"com.hef.spittr", "config"}, excludeFilters = {@ComponentScan.Filter(type = FilterType.ANNOTATION,
        classes = {EnableWebMvc.class})})
public class RootConfig {
}

详细代码在github上:StompUserSpringSecuritySpittr

一、使用下面 Spring Security最简单的配置,就能无偿地得到一个登陆页面

配置DelegatingFilterProxy:

package com.hef.spittr.config;

import org.springframework.security.web.context.AbstractSecurityWebApplicationInitializer;

public class SecurityWebInitializer extends AbstractSecurityWebApplicationInitializer {


}

配置WebSecurityConfigurerAdapter:

package com.hef.spittr.config;

import com.hef.spittr.service.SpitterUserService;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.HttpMethod;
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.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;

@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {

    /**
     * 基于内存的用户存储
     * inMemoryAuthentication() 启动用户存储
     * @param auth
     * @throws Exception
     */
    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        //super.configure(auth);
        // 用两个用户来配置内存用户存储
        auth.inMemoryAuthentication()
                .withUser("user").password("password").roles("USER").and()
                .withUser("admin").password("password").roles("USER", "ADMIN");
    }
}

使用Spring Security无偿得到一个登陆页面一旦重写configure(HttpSecurity)方法,就失去了这个简单的登陆页面。在configure(HttpSecurity)方法中调用formLogin()之后,还能找回这个功能,此时访问应用的"/login"或者导航到需要认证的页面时,将会在浏览器中展示登陆页面。

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值