Spring boot +Security 学习

本文介绍了Spring Security框架,一个强大的认证和访问控制框架,适用于Java应用,特别强调了其全面性和可定制性,以及如何在Spring Boot项目中进行集成。

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

1.Security

1.1.简介

Spring Security is a powerful and highly customizable authentication and access-control framework. It is the de-facto standard for securing Spring-based applications.

Spring Security is a framework that focuses on providing both authentication and authorization to Java applications. Like all Spring projects, the real power of Spring Security is found in how easily it can be extended to meet custom requirements

1.2.特点

  • 对身份验证和授权的全面和可扩展的支持
  • 防止会话固定,点击劫持,跨站点请求伪造等攻击
  • Servlet API集成
  • 可选与Spring Web MVC集成
  • 等等

2.Spring boot整合Security

此处我们使用Spring官网的示例做一个简单的Demo

2.1.结构图

此处先展示一下接下来的Demo的结构图

2.2.准备

在pom.xml中添加如下配置,引入对Spring Security的依赖。

        <dependency>
           <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-security</artifactId>
        </dependency>
复制代码
@Configuration
@EnableWebSecurity
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http
                .authorizeRequests().antMatchers("/", "/home1").permitAll()
                .anyRequest().authenticated()
                .and()
                .formLogin().loginPage("/login1").permitAll()
                .and()
                .logout().permitAll();
    }

    @Autowired
    public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
        auth
                .inMemoryAuthentication()
                .withUser("user").password("password").roles("USER")
                .and()
                .passwordEncoder(new CustomPasswordEncoder());
    }
}
复制代码
public class CustomPasswordEncoder implements PasswordEncoder {
    @Override
    public String encode(CharSequence charSequence) {
        return charSequence.toString();
    }

    @Override
    public boolean matches(CharSequence charSequence, String s) {
        return s.equals(charSequence.toString());
    }
}
复制代码
@Configuration
public class MvcConfig implements WebMvcConfigurer {
    @Override
    public void addViewControllers(ViewControllerRegistry registry){
        registry.addViewController("/home1").setViewName("/home");
        registry.addViewController("/").setViewName("/home");
        registry.addViewController("/hello1").setViewName("hello");
        registry.addViewController("/login1").setViewName("login");
    }
}
复制代码

参考&引用

更新时间

发布时间 : 2019年02月21

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值